blob: 49a76da697635bee077553f461cfb270459aada9 [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
Chillar Anand915b3432021-09-02 16:44:59 +05305
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05306import frappe
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05307from frappe import _
Anand Doshi424c0332014-04-21 15:06:56 +05308from frappe.model.document import Document
Chillar Anand915b3432021-09-02 16:44:59 +05309from frappe.utils import comma_or, flt, getdate, now, nowdate
10
Nabin Hait0feebc12013-06-03 16:45:38 +053011
Nabin Hait868766d2019-07-15 18:02:58 +053012class OverAllowanceError(frappe.ValidationError): pass
13
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053014def validate_status(status, options):
15 if status not in options:
16 frappe.throw(_("Status must be one of {0}").format(comma_or(options)))
17
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053018status_map = {
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053019 "Lead": [
Nabin Haitf49bbe12016-12-15 11:51:54 +053020 ["Lost Quotation", "has_lost_quotation"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053021 ["Opportunity", "has_opportunity"],
Alec Ruiz-Ramonfcaaa292016-06-09 14:19:51 -040022 ["Quotation", "has_quotation"],
23 ["Converted", "has_customer"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053024 ],
25 "Opportunity": [
Valmik Jangla29563272016-03-29 11:13:07 +053026 ["Lost", "eval:self.status=='Lost'"],
Alec Ruiz-Ramonfcaaa292016-06-09 14:19:51 -040027 ["Lost", "has_lost_quotation"],
Nabin Hait6a5cf672017-05-30 15:34:20 +053028 ["Quotation", "has_active_quotation"],
29 ["Converted", "has_ordered_quotation"],
Valmik Jangla29563272016-03-29 11:13:07 +053030 ["Closed", "eval:self.status=='Closed'"]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053031 ],
32 "Quotation": [
Rushabh Mehta4ac30942015-04-13 16:56:03 +053033 ["Draft", None],
Deepesh Gargea057462019-06-26 11:05:51 +053034 ["Open", "eval:self.docstatus==1"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053035 ["Lost", "eval:self.status=='Lost'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053036 ["Ordered", "has_sales_order"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053037 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053038 ],
39 "Sales Order": [
40 ["Draft", None],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053041 ["To Deliver and Bill", "eval:self.per_delivered < 100 and self.per_billed < 100 and self.docstatus == 1"],
Mangesh-Khairnar4ed9b452019-10-12 19:33:11 +053042 ["To Bill", "eval:(self.per_delivered == 100 or self.skip_delivery_note) and self.per_billed < 100 and self.docstatus == 1"],
43 ["To Deliver", "eval:self.per_delivered < 100 and self.per_billed == 100 and self.docstatus == 1 and not self.skip_delivery_note"],
44 ["Completed", "eval:(self.per_delivered == 100 or self.skip_delivery_note) and self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053045 ["Cancelled", "eval:self.docstatus==2"],
Saurabhc6dbe702015-10-19 14:17:52 +053046 ["Closed", "eval:self.status=='Closed'"],
Mangesh-Khairnar5eb66ae2019-03-01 16:23:27 +053047 ["On Hold", "eval:self.status=='On Hold'"],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053048 ],
49 "Purchase Order": [
50 ["Draft", None],
51 ["To Receive and Bill", "eval:self.per_received < 100 and self.per_billed < 100 and self.docstatus == 1"],
KanchanChauhand114c8f2019-09-05 15:11:43 +053052 ["To Bill", "eval:self.per_received >= 100 and self.per_billed < 100 and self.docstatus == 1"],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053053 ["To Receive", "eval:self.per_received < 100 and self.per_billed == 100 and self.docstatus == 1"],
KanchanChauhand114c8f2019-09-05 15:11:43 +053054 ["Completed", "eval:self.per_received >= 100 and self.per_billed == 100 and self.docstatus == 1"],
Saurabh6d64fe32015-10-23 10:40:32 +053055 ["Delivered", "eval:self.status=='Delivered'"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053056 ["Cancelled", "eval:self.docstatus==2"],
Mangesh-Khairnar439546c2019-03-11 16:40:27 +053057 ["On Hold", "eval:self.status=='On Hold'"],
Saurabh98b28752015-10-19 15:16:17 +053058 ["Closed", "eval:self.status=='Closed'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053059 ],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053060 "Delivery Note": [
61 ["Draft", None],
Nabin Hait5b13b992015-12-28 13:03:55 +053062 ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
marinationba37fe72020-07-31 20:01:06 +053063 ["Return Issued", "eval:self.per_returned == 100 and self.docstatus == 1"],
Nabin Hait5b13b992015-12-28 13:03:55 +053064 ["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053065 ["Cancelled", "eval:self.docstatus==2"],
Saurabha8a91cc2015-11-02 12:57:08 +053066 ["Closed", "eval:self.status=='Closed'"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053067 ],
68 "Purchase Receipt": [
69 ["Draft", None],
Nabin Haitbdab0ee2015-12-30 19:08:11 +053070 ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
marination66069df2020-07-31 15:54:05 +053071 ["Return Issued", "eval:self.per_returned == 100 and self.docstatus == 1"],
Nabin Haitbdab0ee2015-12-30 19:08:11 +053072 ["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'"],
tundebabzy99b734b2017-06-07 07:32:07 +010075 ],
76 "Material Request": [
77 ["Draft", None],
78 ["Stopped", "eval:self.status == 'Stopped'"],
79 ["Cancelled", "eval:self.docstatus == 2"],
80 ["Pending", "eval:self.status != 'Stopped' and self.per_ordered == 0 and self.docstatus == 1"],
tundebabzy99b734b2017-06-07 07:32:07 +010081 ["Ordered", "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'"],
82 ["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 +053083 ["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 +053084 ["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 +053085 ["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'"],
Ganga Manoj18cfced2021-05-25 19:54:07 +053086 ["Partially Ordered", "eval:self.status != 'Stopped' and self.per_ordered < 100 and self.per_ordered > 0 and self.docstatus == 1"],
Anurag Mishra305da792019-07-22 11:35:16 +053087 ["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 +053088 ],
89 "Bank Transaction": [
90 ["Unreconciled", "eval:self.docstatus == 1 and self.unallocated_amount>0"],
Saqib62114b22021-08-25 16:25:51 +053091 ["Reconciled", "eval:self.docstatus == 1 and self.unallocated_amount<=0"],
92 ["Cancelled", "eval:self.docstatus == 2"]
Saqiba6f98d42020-07-23 18:51:26 +053093 ],
94 "POS Opening Entry": [
95 ["Draft", None],
96 ["Open", "eval:self.docstatus == 1 and not self.pos_closing_entry"],
97 ["Closed", "eval:self.docstatus == 1 and self.pos_closing_entry"],
98 ["Cancelled", "eval:self.docstatus == 2"],
Saqib675a8332021-01-28 18:42:43 +053099 ],
100 "POS Closing Entry": [
101 ["Draft", None],
102 ["Submitted", "eval:self.docstatus == 1"],
103 ["Queued", "eval:self.status == 'Queued'"],
Saqib900a8fb2021-05-06 17:02:47 +0530104 ["Failed", "eval:self.status == 'Failed'"],
Saqib675a8332021-01-28 18:42:43 +0530105 ["Cancelled", "eval:self.docstatus == 2"],
Ganga Manojf2eb8dd2021-05-10 14:02:58 +0530106 ],
107 "Transaction Deletion Record": [
108 ["Draft", None],
109 ["Completed", "eval:self.docstatus == 1"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +0530110 ]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530111}
112
Anand Doshi424c0332014-04-21 15:06:56 +0530113class StatusUpdater(Document):
Nabin Hait0feebc12013-06-03 16:45:38 +0530114 """
115 Updates the status of the calling records
116 Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
117 Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
118 Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation
119 """
120
121 def update_prevdoc_status(self):
122 self.update_qty()
123 self.validate_qty()
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530124
Saurabh70ed6ed2015-12-08 14:02:53 +0530125 def set_status(self, update=False, status=None, update_modified=True):
Rushabh Mehtacb067aa2014-08-19 16:20:04 +0530126 if self.is_new():
Rohit Waghchaure29458832017-01-13 12:51:19 +0530127 if self.get('amended_from'):
128 self.status = 'Draft'
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530129 return
Anand Doshi6b71ef52016-01-06 16:32:06 +0530130
Anand Doshif78d1ae2014-03-28 13:55:00 +0530131 if self.doctype in status_map:
Nabin Haitcabf9c52014-08-21 16:34:38 +0530132 _status = self.status
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530133 if status and update:
134 self.db_set("status", status)
135
Anand Doshif78d1ae2014-03-28 13:55:00 +0530136 sl = status_map[self.doctype][:]
Rushabh Mehta6856d742013-10-03 18:12:36 +0530137 sl.reverse()
138 for s in sl:
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530139 if not s[1]:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530140 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530141 break
Rushabh Mehta6856d742013-10-03 18:12:36 +0530142 elif s[1].startswith("eval:"):
Alcheze52ae4e2018-09-06 18:27:06 +0530143 if frappe.safe_eval(s[1][5:], None, { "self": self.as_dict(), "getdate": getdate,
Nabin Hait8a27cf32017-05-16 12:43:00 +0530144 "nowdate": nowdate, "get_value": frappe.db.get_value }):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530145 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530146 break
147 elif getattr(self, s[1])():
Anand Doshif78d1ae2014-03-28 13:55:00 +0530148 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530149 break
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530150
tundebabzy99b734b2017-06-07 07:32:07 +0100151 if self.status != _status and self.status not in ("Cancelled", "Partially Ordered",
152 "Ordered", "Issued", "Transferred"):
Anand Doshi7b34ebe2015-01-07 15:41:32 +0530153 self.add_comment("Label", _(self.status))
Anand Doshi6b71ef52016-01-06 16:32:06 +0530154
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530155 if update:
Rushabh Mehtafc8e5892016-07-20 12:08:47 +0530156 self.db_set('status', self.status, update_modified = update_modified)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530157
Nabin Hait0feebc12013-06-03 16:45:38 +0530158 def validate_qty(self):
Rushabh Mehtaa9ba5ef2014-12-19 16:20:32 +0530159 """Validates qty at row level"""
Nabin Hait868766d2019-07-15 18:02:58 +0530160 self.item_allowance = {}
161 self.global_qty_allowance = None
162 self.global_amount_allowance = None
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530163
Nabin Hait0feebc12013-06-03 16:45:38 +0530164 for args in self.status_updater:
Anand Doshife13bfe2015-08-25 12:49:40 +0530165 if "target_ref_field" not in args:
166 # if target_ref_field is not specified, the programmer does not want to validate qty / amount
167 continue
168
Nabin Hait0feebc12013-06-03 16:45:38 +0530169 # get unique transactions to update
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530170 for d in self.get_all_children():
rohitwaghchaure12aa4262018-03-12 11:20:30 +0530171 if hasattr(d, 'qty') and d.qty < 0 and not self.get('is_return'):
172 frappe.throw(_("For an item {0}, quantity must be positive number").format(d.item_code))
173
rohitwaghchaure70489252018-06-11 12:02:14 +0530174 if hasattr(d, 'qty') and d.qty > 0 and self.get('is_return'):
175 frappe.throw(_("For an item {0}, quantity must be negative number").format(d.item_code))
176
Anand Doshif78d1ae2014-03-28 13:55:00 +0530177 if d.doctype == args['source_dt'] and d.get(args["join_field"]):
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530178 args['name'] = d.get(args['join_field'])
Nabin Hait0feebc12013-06-03 16:45:38 +0530179
180 # get all qty where qty > target_field
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530181 item = frappe.db.sql("""select item_code, `{target_ref_field}`,
182 `{target_field}`, parenttype, parent from `tab{target_dt}`
183 where `{target_ref_field}` < `{target_field}`
184 and name=%s and docstatus=1""".format(**args),
Nabin Hait4d713ac2014-03-03 15:51:13 +0530185 args['name'], as_dict=1)
Nabin Hait0feebc12013-06-03 16:45:38 +0530186 if item:
187 item = item[0]
188 item['idx'] = d.idx
189 item['target_ref_field'] = args['target_ref_field'].replace('_', ' ')
190
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530191 # if not item[args['target_ref_field']]:
192 # 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 +0530193 if args.get('no_allowance'):
nabinhaitd5fb5d92014-07-09 17:36:38 +0530194 item['reduce_by'] = item[args['target_field']] - item[args['target_ref_field']]
Nabin Hait0feebc12013-06-03 16:45:38 +0530195 if item['reduce_by'] > .01:
Marica4e6b3ad2020-01-15 19:22:35 +0530196 self.limits_crossed_error(args, item, "qty")
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530197
Nabin Hait47a3f632016-08-26 11:39:23 +0530198 elif item[args['target_ref_field']]:
Nabin Hait868766d2019-07-15 18:02:58 +0530199 self.check_overflow_with_allowance(item, args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530200
Nabin Hait868766d2019-07-15 18:02:58 +0530201 def check_overflow_with_allowance(self, item, args):
Nabin Hait0feebc12013-06-03 16:45:38 +0530202 """
Nabin Hait868766d2019-07-15 18:02:58 +0530203 Checks if there is overflow condering a relaxation allowance
Nabin Hait0feebc12013-06-03 16:45:38 +0530204 """
Nabin Hait868766d2019-07-15 18:02:58 +0530205 qty_or_amount = "qty" if "qty" in args['target_ref_field'] else "amount"
206
207 # check if overflow is within allowance
208 allowance, self.item_allowance, self.global_qty_allowance, self.global_amount_allowance = \
209 get_allowance_for(item['item_code'], self.item_allowance,
210 self.global_qty_allowance, self.global_amount_allowance, qty_or_amount)
211
Deepesh Gargcb718fc2021-04-19 13:25:15 +0530212 role_allowed_to_over_deliver_receive = frappe.db.get_single_value('Stock Settings', 'role_allowed_to_over_deliver_receive')
213 role_allowed_to_over_bill = frappe.db.get_single_value('Accounts Settings', 'role_allowed_to_over_bill')
214 role = role_allowed_to_over_deliver_receive if qty_or_amount == 'qty' else role_allowed_to_over_bill
nabinhait711e8be2014-07-19 17:00:15 +0530215
Deepesh Gargcb718fc2021-04-19 13:25:15 +0530216 overflow_percent = ((item[args['target_field']] - item[args['target_ref_field']]) /
217 item[args['target_ref_field']]) * 100
218
Ankush Menat6ec047c2021-10-27 10:30:05 +0530219 if overflow_percent - allowance > 0.01:
Nabin Hait868766d2019-07-15 18:02:58 +0530220 item['max_allowed'] = flt(item[args['target_ref_field']] * (100+allowance)/100)
Nabin Hait0feebc12013-06-03 16:45:38 +0530221 item['reduce_by'] = item[args['target_field']] - item['max_allowed']
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530222
Ankush Menat6ec047c2021-10-27 10:30:05 +0530223 if role not in frappe.get_roles():
224 self.limits_crossed_error(args, item, qty_or_amount)
225 else:
226 self.warn_about_bypassing_with_role(item, qty_or_amount, role)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530227
Nabin Hait868766d2019-07-15 18:02:58 +0530228 def limits_crossed_error(self, args, item, qty_or_amount):
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530229 '''Raise exception for limits crossed'''
Nabin Hait868766d2019-07-15 18:02:58 +0530230 if qty_or_amount == "qty":
231 action_msg = _('To allow over receipt / delivery, update "Over Receipt/Delivery Allowance" in Stock Settings or the Item.')
232 else:
233 action_msg = _('To allow over billing, update "Over Billing Allowance" in Accounts Settings or the Item.')
234
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530235 frappe.throw(_('This document is over limit by {0} {1} for item {4}. Are you making another {3} against the same {2}?')
236 .format(
237 frappe.bold(_(item["target_ref_field"].title())),
238 frappe.bold(item["reduce_by"]),
239 frappe.bold(_(args.get('target_dt'))),
240 frappe.bold(_(self.doctype)),
241 frappe.bold(item.get('item_code'))
Nabin Hait868766d2019-07-15 18:02:58 +0530242 ) + '<br><br>' + action_msg, OverAllowanceError, title = _('Limit Crossed'))
Nabin Hait0feebc12013-06-03 16:45:38 +0530243
Ankush Menat6ec047c2021-10-27 10:30:05 +0530244 def warn_about_bypassing_with_role(self, item, qty_or_amount, role):
245 action = _("Over Receipt/Delivery") if qty_or_amount == "qty" else _("Overbilling")
246
247 msg = (_("{} of {} {} ignored for item {} because you have {} role.")
248 .format(
249 action,
250 _(item["target_ref_field"].title()),
251 frappe.bold(item["reduce_by"]),
252 frappe.bold(item.get('item_code')),
253 role)
254 )
255 frappe.msgprint(msg, indicator="orange", alert=True)
256
Anand Doshi6b71ef52016-01-06 16:32:06 +0530257 def update_qty(self, update_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530258 """Updates qty or amount at row level
259
Anand Doshi6b71ef52016-01-06 16:32:06 +0530260 :param update_modified: If true, updates `modified` and `modified_by` for target parent doc
Nabin Hait0feebc12013-06-03 16:45:38 +0530261 """
262 for args in self.status_updater:
263 # condition to include current record (if submit or no if cancel)
Anand Doshif78d1ae2014-03-28 13:55:00 +0530264 if self.docstatus == 1:
265 args['cond'] = ' or parent="%s"' % self.name.replace('"', '\"')
Nabin Hait0feebc12013-06-03 16:45:38 +0530266 else:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530267 args['cond'] = ' and parent!="%s"' % self.name.replace('"', '\"')
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530268
Anand Doshi6b71ef52016-01-06 16:32:06 +0530269 self._update_children(args, update_modified)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530270
marination66069df2020-07-31 15:54:05 +0530271 if "percent_join_field" in args or "percent_join_field_parent" in args:
Anand Doshi6b71ef52016-01-06 16:32:06 +0530272 self._update_percent_field_in_targets(args, update_modified)
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530273
Anand Doshi6b71ef52016-01-06 16:32:06 +0530274 def _update_children(self, args, update_modified):
Anand Doshife13bfe2015-08-25 12:49:40 +0530275 """Update quantities or amount in child table"""
276 for d in self.get_all_children():
277 if d.doctype != args['source_dt']:
278 continue
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530279
Anand Doshi6b71ef52016-01-06 16:32:06 +0530280 self._update_modified(args, update_modified)
281
Anand Doshife13bfe2015-08-25 12:49:40 +0530282 # updates qty in the child table
283 args['detail_id'] = d.get(args['join_field'])
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530284
Anand Doshife13bfe2015-08-25 12:49:40 +0530285 args['second_source_condition'] = ""
286 if args.get('second_source_dt') and args.get('second_source_field') \
287 and args.get('second_join_field'):
288 if not args.get("second_source_extra_cond"):
289 args["second_source_extra_cond"] = ""
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530290
Rohit Waghchaure3eea3c62020-11-18 20:17:52 +0530291 args['second_source_condition'] = frappe.db.sql(""" select ifnull((select sum(%(second_source_field)s)
Anand Doshife13bfe2015-08-25 12:49:40 +0530292 from `tab%(second_source_dt)s`
293 where `%(second_join_field)s`="%(detail_id)s"
Rohit Waghchaure3eea3c62020-11-18 20:17:52 +0530294 and (`tab%(second_source_dt)s`.docstatus=1)
295 %(second_source_extra_cond)s), 0) """ % args)[0][0]
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530296
Anand Doshife13bfe2015-08-25 12:49:40 +0530297 if args['detail_id']:
298 if not args.get("extra_cond"): args["extra_cond"] = ""
Alcheze52ae4e2018-09-06 18:27:06 +0530299
Rohit Waghchaure3eea3c62020-11-18 20:17:52 +0530300 args["source_dt_value"] = frappe.db.sql("""
Anand Doshi6b71ef52016-01-06 16:32:06 +0530301 (select ifnull(sum(%(source_field)s), 0)
302 from `tab%(source_dt)s` where `%(join_field)s`="%(detail_id)s"
303 and (docstatus=1 %(cond)s) %(extra_cond)s)
Rohit Waghchaure3eea3c62020-11-18 20:17:52 +0530304 """ % args)[0][0] or 0.0
305
306 if args['second_source_condition']:
307 args["source_dt_value"] += flt(args['second_source_condition'])
308
309 frappe.db.sql("""update `tab%(target_dt)s`
310 set %(target_field)s = %(source_dt_value)s %(update_modified)s
Anand Doshife13bfe2015-08-25 12:49:40 +0530311 where name='%(detail_id)s'""" % args)
Anand Doshi6b71ef52016-01-06 16:32:06 +0530312
313 def _update_percent_field_in_targets(self, args, update_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530314 """Update percent field in parent transaction"""
marination66069df2020-07-31 15:54:05 +0530315 if args.get('percent_join_field_parent'):
316 # if reference to target doc where % is to be updated, is
317 # in source doc's parent form, consider percent_join_field_parent
318 args['name'] = self.get(args['percent_join_field_parent'])
319 self._update_percent_field(args, update_modified)
320 else:
Ankush Menat98917802021-06-11 18:40:22 +0530321 distinct_transactions = set(d.get(args['percent_join_field'])
322 for d in self.get_all_children(args['source_dt']))
Anand Doshife13bfe2015-08-25 12:49:40 +0530323
marination66069df2020-07-31 15:54:05 +0530324 for name in distinct_transactions:
325 if name:
326 args['name'] = name
327 self._update_percent_field(args, update_modified)
Anand Doshife13bfe2015-08-25 12:49:40 +0530328
Anand Doshi6b71ef52016-01-06 16:32:06 +0530329 def _update_percent_field(self, args, update_modified=True):
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530330 """Update percent field in parent transaction"""
Anand Doshi6b71ef52016-01-06 16:32:06 +0530331
332 self._update_modified(args, update_modified)
Alcheze52ae4e2018-09-06 18:27:06 +0530333
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530334 if args.get('target_parent_field'):
335 frappe.db.sql("""update `tab%(target_parent_dt)s`
336 set %(target_parent_field)s = round(
337 ifnull((select
Rohit Waghchaure5d4d70b2019-07-05 16:59:27 +0530338 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 +0800339 / sum(abs(%(target_ref_field)s)) * 100
rohitwaghchaure85f63a32018-03-27 11:31:44 +0530340 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 +0530341 %(update_modified)s
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530342 where name='%(name)s'""" % args)
Anand Doshife13bfe2015-08-25 12:49:40 +0530343
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530344 # update field
345 if args.get('status_field'):
346 frappe.db.sql("""update `tab%(target_parent_dt)s`
347 set %(status_field)s = if(%(target_parent_field)s<0.001,
rohitwaghchaure85f63a32018-03-27 11:31:44 +0530348 'Not %(keyword)s', if(%(target_parent_field)s>=99.999999,
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530349 'Fully %(keyword)s', 'Partly %(keyword)s'))
350 where name='%(name)s'""" % args)
Anand Doshife13bfe2015-08-25 12:49:40 +0530351
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530352 if update_modified:
353 target = frappe.get_doc(args["target_parent_dt"], args["name"])
354 target.set_status(update=True)
355 target.notify_update()
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530356
Anand Doshi6b71ef52016-01-06 16:32:06 +0530357 def _update_modified(self, args, update_modified):
Sagar Vorad932cba2021-08-17 13:17:09 +0530358 if not update_modified:
359 args['update_modified'] = ''
360 return
361
362 args['update_modified'] = ', modified = {0}, modified_by = {1}'.format(
363 frappe.db.escape(now()),
364 frappe.db.escape(frappe.session.user)
365 )
Anand Doshi6b71ef52016-01-06 16:32:06 +0530366
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530367 def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
Himanshu Mishra70029b82019-05-29 14:19:35 +0530368 ref_fieldname = frappe.scrub(ref_dt)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530369
Himanshu Mishra70029b82019-05-29 14:19:35 +0530370 ref_docs = [item.get(ref_fieldname) for item in (self.get('items') or []) if item.get(ref_fieldname)]
371 if not ref_docs:
372 return
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530373
Himanshu Mishra70029b82019-05-29 14:19:35 +0530374 zero_amount_refdocs = frappe.db.sql_list("""
375 SELECT
376 name
377 from
378 `tab{ref_dt}`
379 where
380 docstatus = 1
381 and base_net_total = 0
382 and name in %(ref_docs)s
383 """.format(ref_dt=ref_dt), {
384 'ref_docs': ref_docs
385 })
386
387 if zero_amount_refdocs:
388 self.update_billing_status(zero_amount_refdocs, ref_dt, ref_fieldname)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530389
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530390 def update_billing_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530391 for ref_dn in zero_amount_refdoc:
Anand Doshiebae7262015-11-25 15:51:01 +0530392 ref_doc_qty = flt(frappe.db.sql("""select ifnull(sum(qty), 0) from `tab%s Item`
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530393 where parent=%s""" % (ref_dt, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530394
Anand Doshiebae7262015-11-25 15:51:01 +0530395 billed_qty = flt(frappe.db.sql("""select ifnull(sum(qty), 0)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530396 from `tab%s Item` where %s=%s and docstatus=1""" %
Anand Doshif78d1ae2014-03-28 13:55:00 +0530397 (self.doctype, ref_fieldname, '%s'), (ref_dn))[0][0])
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530398
Alcheze52ae4e2018-09-06 18:27:06 +0530399 per_billed = (min(ref_doc_qty, billed_qty) / ref_doc_qty) * 100
Rushabh Mehtafc8e5892016-07-20 12:08:47 +0530400
401 ref_doc = frappe.get_doc(ref_dt, ref_dn)
402
403 ref_doc.db_set("per_billed", per_billed)
Rohit Waghchaure770d04e2016-10-05 23:02:15 +0530404 ref_doc.set_status(update=True)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530405
Ankush Menat7eac4a22021-04-19 10:33:39 +0530406def get_allowance_for(item_code, item_allowance=None, global_qty_allowance=None, global_amount_allowance=None, qty_or_amount="qty"):
Nabin Hait7f0406f2014-01-03 17:43:19 +0530407 """
Nabin Hait868766d2019-07-15 18:02:58 +0530408 Returns the allowance for the item, if not set, returns global allowance
Nabin Hait7f0406f2014-01-03 17:43:19 +0530409 """
Ankush Menat7eac4a22021-04-19 10:33:39 +0530410 if item_allowance is None:
411 item_allowance = {}
Nabin Hait868766d2019-07-15 18:02:58 +0530412 if qty_or_amount == "qty":
413 if item_allowance.get(item_code, frappe._dict()).get("qty"):
414 return item_allowance[item_code].qty, item_allowance, global_qty_allowance, global_amount_allowance
415 else:
416 if item_allowance.get(item_code, frappe._dict()).get("amount"):
417 return item_allowance[item_code].amount, item_allowance, global_qty_allowance, global_amount_allowance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530418
Nabin Hait868766d2019-07-15 18:02:58 +0530419 qty_allowance, over_billing_allowance = \
420 frappe.db.get_value('Item', item_code, ['over_delivery_receipt_allowance', 'over_billing_allowance'])
Nabin Hait7f0406f2014-01-03 17:43:19 +0530421
Nabin Hait868766d2019-07-15 18:02:58 +0530422 if qty_or_amount == "qty" and not qty_allowance:
423 if global_qty_allowance == None:
424 global_qty_allowance = flt(frappe.db.get_single_value('Stock Settings', 'over_delivery_receipt_allowance'))
425 qty_allowance = global_qty_allowance
426 elif qty_or_amount == "amount" and not over_billing_allowance:
427 if global_amount_allowance == None:
428 global_amount_allowance = flt(frappe.db.get_single_value('Accounts Settings', 'over_billing_allowance'))
429 over_billing_allowance = global_amount_allowance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530430
Nabin Hait868766d2019-07-15 18:02:58 +0530431 if qty_or_amount == "qty":
432 allowance = qty_allowance
433 item_allowance.setdefault(item_code, frappe._dict()).setdefault("qty", qty_allowance)
434 else:
435 allowance = over_billing_allowance
436 item_allowance.setdefault(item_code, frappe._dict()).setdefault("amount", over_billing_allowance)
437
438 return allowance, item_allowance, global_qty_allowance, global_amount_allowance