blob: 2b79b895ebf6d68d5f89a359a189cfd1c1e71bae [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
Chillar Anand915b3432021-09-02 16:44:59 +05304
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
Rushabh Mehtaea0ff232016-07-07 14:02:26 +05306from frappe import _
Anand Doshi424c0332014-04-21 15:06:56 +05307from frappe.model.document import Document
ruthra kumara0fc6852023-08-14 17:38:44 +05308from frappe.utils import comma_or, flt, get_link_to_form, getdate, now, nowdate
Chillar Anand915b3432021-09-02 16:44:59 +05309
Nabin Hait0feebc12013-06-03 16:45:38 +053010
Ankush Menat494bd9e2022-03-28 18:52:46 +053011class OverAllowanceError(frappe.ValidationError):
12 pass
13
Nabin Hait868766d2019-07-15 18:02:58 +053014
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053015def validate_status(status, options):
16 if status not in options:
17 frappe.throw(_("Status must be one of {0}").format(comma_or(options)))
18
Ankush Menat494bd9e2022-03-28 18:52:46 +053019
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053020status_map = {
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053021 "Lead": [
Nabin Haitf49bbe12016-12-15 11:51:54 +053022 ["Lost Quotation", "has_lost_quotation"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053023 ["Opportunity", "has_opportunity"],
Alec Ruiz-Ramonfcaaa292016-06-09 14:19:51 -040024 ["Quotation", "has_quotation"],
25 ["Converted", "has_customer"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053026 ],
27 "Opportunity": [
Valmik Jangla29563272016-03-29 11:13:07 +053028 ["Lost", "eval:self.status=='Lost'"],
Alec Ruiz-Ramonfcaaa292016-06-09 14:19:51 -040029 ["Lost", "has_lost_quotation"],
Nabin Hait6a5cf672017-05-30 15:34:20 +053030 ["Quotation", "has_active_quotation"],
31 ["Converted", "has_ordered_quotation"],
Ankush Menat494bd9e2022-03-28 18:52:46 +053032 ["Closed", "eval:self.status=='Closed'"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053033 ],
34 "Quotation": [
Rushabh Mehta4ac30942015-04-13 16:56:03 +053035 ["Draft", None],
Deepesh Gargea057462019-06-26 11:05:51 +053036 ["Open", "eval:self.docstatus==1"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053037 ["Lost", "eval:self.status=='Lost'"],
Deepesh Garg118c7862022-06-11 21:55:59 +053038 ["Partially Ordered", "is_partially_ordered"],
39 ["Ordered", "is_fully_ordered"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053040 ["Cancelled", "eval:self.docstatus==2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053041 ],
42 "Sales Order": [
43 ["Draft", None],
Ankush Menat494bd9e2022-03-28 18:52:46 +053044 [
45 "To Deliver and Bill",
46 "eval:self.per_delivered < 100 and self.per_billed < 100 and self.docstatus == 1",
47 ],
48 [
49 "To Bill",
50 "eval:(self.per_delivered == 100 or self.skip_delivery_note) and self.per_billed < 100 and self.docstatus == 1",
51 ],
52 [
53 "To Deliver",
54 "eval:self.per_delivered < 100 and self.per_billed == 100 and self.docstatus == 1 and not self.skip_delivery_note",
55 ],
56 [
David Arnold8b21ca22023-10-14 16:34:18 +020057 "To Pay",
58 "eval:self.advance_payment_status == 'Requested' and self.docstatus == 1",
59 ],
60 [
Ankush Menat494bd9e2022-03-28 18:52:46 +053061 "Completed",
62 "eval:(self.per_delivered == 100 or self.skip_delivery_note) and self.per_billed == 100 and self.docstatus == 1",
63 ],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053064 ["Cancelled", "eval:self.docstatus==2"],
Deepesh Garg597ef0a2023-01-20 19:44:06 +053065 ["Closed", "eval:self.status=='Closed' and self.docstatus != 2"],
Mangesh-Khairnar5eb66ae2019-03-01 16:23:27 +053066 ["On Hold", "eval:self.status=='On Hold'"],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053067 ],
68 "Purchase Order": [
69 ["Draft", None],
KanchanChauhand114c8f2019-09-05 15:11:43 +053070 ["To Bill", "eval:self.per_received >= 100 and self.per_billed < 100 and self.docstatus == 1"],
Ankush Menat494bd9e2022-03-28 18:52:46 +053071 [
72 "To Receive",
73 "eval:self.per_received < 100 and self.per_billed == 100 and self.docstatus == 1",
74 ],
75 [
David Arnold8b21ca22023-10-14 16:34:18 +020076 "To Receive and Bill",
77 "eval:self.per_received < 100 and self.per_billed < 100 and self.docstatus == 1",
78 ],
79 [
80 "To Pay",
81 "eval:self.advance_payment_status == 'Initiated' and self.docstatus == 1",
82 ],
83 [
Ankush Menat494bd9e2022-03-28 18:52:46 +053084 "Completed",
85 "eval:self.per_received >= 100 and self.per_billed == 100 and self.docstatus == 1",
86 ],
Saurabh6d64fe32015-10-23 10:40:32 +053087 ["Delivered", "eval:self.status=='Delivered'"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053088 ["Cancelled", "eval:self.docstatus==2"],
Mangesh-Khairnar439546c2019-03-11 16:40:27 +053089 ["On Hold", "eval:self.status=='On Hold'"],
Deepesh Garg597ef0a2023-01-20 19:44:06 +053090 ["Closed", "eval:self.status=='Closed' and self.docstatus != 2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053091 ],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053092 "Delivery Note": [
93 ["Draft", None],
Nabin Hait5b13b992015-12-28 13:03:55 +053094 ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
marinationba37fe72020-07-31 20:01:06 +053095 ["Return Issued", "eval:self.per_returned == 100 and self.docstatus == 1"],
Nabin Hait5b13b992015-12-28 13:03:55 +053096 ["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053097 ["Cancelled", "eval:self.docstatus==2"],
Deepesh Garg597ef0a2023-01-20 19:44:06 +053098 ["Closed", "eval:self.status=='Closed' and self.docstatus != 2"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053099 ],
100 "Purchase Receipt": [
101 ["Draft", None],
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530102 ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
marination66069df2020-07-31 15:54:05 +0530103 ["Return Issued", "eval:self.per_returned == 100 and self.docstatus == 1"],
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530104 ["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +0530105 ["Cancelled", "eval:self.docstatus==2"],
Deepesh Garg597ef0a2023-01-20 19:44:06 +0530106 ["Closed", "eval:self.status=='Closed' and self.docstatus != 2"],
tundebabzy99b734b2017-06-07 07:32:07 +0100107 ],
108 "Material Request": [
109 ["Draft", None],
110 ["Stopped", "eval:self.status == 'Stopped'"],
111 ["Cancelled", "eval:self.docstatus == 2"],
112 ["Pending", "eval:self.status != 'Stopped' and self.per_ordered == 0 and self.docstatus == 1"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530113 [
114 "Ordered",
115 "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'",
116 ],
117 [
118 "Transferred",
119 "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Material Transfer'",
120 ],
121 [
122 "Issued",
123 "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Material Issue'",
124 ],
125 [
126 "Received",
127 "eval:self.status != 'Stopped' and self.per_received == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'",
128 ],
129 [
130 "Partially Received",
131 "eval:self.status != 'Stopped' and self.per_received > 0 and self.per_received < 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'",
132 ],
133 [
134 "Partially Ordered",
135 "eval:self.status != 'Stopped' and self.per_ordered < 100 and self.per_ordered > 0 and self.docstatus == 1",
136 ],
137 [
138 "Manufactured",
139 "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Manufacture'",
140 ],
Nabin Hait34c551d2019-07-03 10:34:31 +0530141 ],
142 "Bank Transaction": [
143 ["Unreconciled", "eval:self.docstatus == 1 and self.unallocated_amount>0"],
Saqib62114b22021-08-25 16:25:51 +0530144 ["Reconciled", "eval:self.docstatus == 1 and self.unallocated_amount<=0"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530145 ["Cancelled", "eval:self.docstatus == 2"],
Saqiba6f98d42020-07-23 18:51:26 +0530146 ],
147 "POS Opening Entry": [
148 ["Draft", None],
149 ["Open", "eval:self.docstatus == 1 and not self.pos_closing_entry"],
150 ["Closed", "eval:self.docstatus == 1 and self.pos_closing_entry"],
151 ["Cancelled", "eval:self.docstatus == 2"],
Saqib675a8332021-01-28 18:42:43 +0530152 ],
153 "POS Closing Entry": [
154 ["Draft", None],
155 ["Submitted", "eval:self.docstatus == 1"],
156 ["Queued", "eval:self.status == 'Queued'"],
Saqib900a8fb2021-05-06 17:02:47 +0530157 ["Failed", "eval:self.status == 'Failed'"],
Saqib675a8332021-01-28 18:42:43 +0530158 ["Cancelled", "eval:self.docstatus == 2"],
Ganga Manojf2eb8dd2021-05-10 14:02:58 +0530159 ],
160 "Transaction Deletion Record": [
161 ["Draft", None],
162 ["Completed", "eval:self.docstatus == 1"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530163 ],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530164}
165
Ankush Menat494bd9e2022-03-28 18:52:46 +0530166
Anand Doshi424c0332014-04-21 15:06:56 +0530167class StatusUpdater(Document):
Nabin Hait0feebc12013-06-03 16:45:38 +0530168 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530169 Updates the status of the calling records
170 Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
171 Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
172 Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation
Nabin Hait0feebc12013-06-03 16:45:38 +0530173 """
174
175 def update_prevdoc_status(self):
176 self.update_qty()
177 self.validate_qty()
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530178
Saurabh70ed6ed2015-12-08 14:02:53 +0530179 def set_status(self, update=False, status=None, update_modified=True):
Rushabh Mehtacb067aa2014-08-19 16:20:04 +0530180 if self.is_new():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530181 if self.get("amended_from"):
182 self.status = "Draft"
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530183 return
Anand Doshi6b71ef52016-01-06 16:32:06 +0530184
Anand Doshif78d1ae2014-03-28 13:55:00 +0530185 if self.doctype in status_map:
Nabin Haitcabf9c52014-08-21 16:34:38 +0530186 _status = self.status
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530187 if status and update:
188 self.db_set("status", status)
189
Anand Doshif78d1ae2014-03-28 13:55:00 +0530190 sl = status_map[self.doctype][:]
Rushabh Mehta6856d742013-10-03 18:12:36 +0530191 sl.reverse()
192 for s in sl:
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530193 if not s[1]:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530194 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530195 break
Rushabh Mehta6856d742013-10-03 18:12:36 +0530196 elif s[1].startswith("eval:"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530197 if frappe.safe_eval(
198 s[1][5:],
199 None,
200 {
201 "self": self.as_dict(),
202 "getdate": getdate,
203 "nowdate": nowdate,
204 "get_value": frappe.db.get_value,
205 },
206 ):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530207 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530208 break
209 elif getattr(self, s[1])():
Anand Doshif78d1ae2014-03-28 13:55:00 +0530210 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530211 break
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530212
Ankush Menat494bd9e2022-03-28 18:52:46 +0530213 if self.status != _status and self.status not in (
214 "Cancelled",
215 "Partially Ordered",
216 "Ordered",
217 "Issued",
218 "Transferred",
219 ):
Anand Doshi7b34ebe2015-01-07 15:41:32 +0530220 self.add_comment("Label", _(self.status))
Anand Doshi6b71ef52016-01-06 16:32:06 +0530221
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530222 if update:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530223 self.db_set("status", self.status, update_modified=update_modified)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530224
Nabin Hait0feebc12013-06-03 16:45:38 +0530225 def validate_qty(self):
Rushabh Mehtaa9ba5ef2014-12-19 16:20:32 +0530226 """Validates qty at row level"""
Nabin Hait868766d2019-07-15 18:02:58 +0530227 self.item_allowance = {}
228 self.global_qty_allowance = None
229 self.global_amount_allowance = None
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530230
Nabin Hait0feebc12013-06-03 16:45:38 +0530231 for args in self.status_updater:
Anand Doshife13bfe2015-08-25 12:49:40 +0530232 if "target_ref_field" not in args:
233 # if target_ref_field is not specified, the programmer does not want to validate qty / amount
234 continue
235
Nabin Hait0feebc12013-06-03 16:45:38 +0530236 # get unique transactions to update
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530237 for d in self.get_all_children():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530238 if hasattr(d, "qty") and d.qty < 0 and not self.get("is_return"):
rohitwaghchaure12aa4262018-03-12 11:20:30 +0530239 frappe.throw(_("For an item {0}, quantity must be positive number").format(d.item_code))
240
Ankush Menat494bd9e2022-03-28 18:52:46 +0530241 if hasattr(d, "qty") and d.qty > 0 and self.get("is_return"):
rohitwaghchaure70489252018-06-11 12:02:14 +0530242 frappe.throw(_("For an item {0}, quantity must be negative number").format(d.item_code))
243
ruthra kumara0fc6852023-08-14 17:38:44 +0530244 if not frappe.db.get_single_value("Selling Settings", "allow_negative_rates_for_items"):
245 if hasattr(d, "item_code") and hasattr(d, "rate") and flt(d.rate) < 0:
246 frappe.throw(
247 _(
248 "For item {0}, rate must be a positive number. To Allow negative rates, enable {1} in {2}"
249 ).format(
250 frappe.bold(d.item_code),
251 frappe.bold(_("`Allow Negative rates for Items`")),
252 get_link_to_form("Selling Settings", "Selling Settings"),
253 ),
254 )
Devin Slauenwhitededf24b2023-08-02 06:56:55 -0400255
Ankush Menat494bd9e2022-03-28 18:52:46 +0530256 if d.doctype == args["source_dt"] and d.get(args["join_field"]):
257 args["name"] = d.get(args["join_field"])
Nabin Hait0feebc12013-06-03 16:45:38 +0530258
259 # get all qty where qty > target_field
Ankush Menat494bd9e2022-03-28 18:52:46 +0530260 item = frappe.db.sql(
261 """select item_code, `{target_ref_field}`,
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530262 `{target_field}`, parenttype, parent from `tab{target_dt}`
263 where `{target_ref_field}` < `{target_field}`
Ankush Menat494bd9e2022-03-28 18:52:46 +0530264 and name=%s and docstatus=1""".format(
265 **args
266 ),
267 args["name"],
268 as_dict=1,
269 )
Nabin Hait0feebc12013-06-03 16:45:38 +0530270 if item:
271 item = item[0]
Ankush Menat494bd9e2022-03-28 18:52:46 +0530272 item["idx"] = d.idx
273 item["target_ref_field"] = args["target_ref_field"].replace("_", " ")
Nabin Hait0feebc12013-06-03 16:45:38 +0530274
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530275 # if not item[args['target_ref_field']]:
276 # msgprint(_("Note: System will not check over-delivery and over-booking for Item {0} as quantity or amount is 0").format(item.item_code))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530277 if args.get("no_allowance"):
278 item["reduce_by"] = item[args["target_field"]] - item[args["target_ref_field"]]
279 if item["reduce_by"] > 0.01:
Marica4e6b3ad2020-01-15 19:22:35 +0530280 self.limits_crossed_error(args, item, "qty")
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530281
Ankush Menat494bd9e2022-03-28 18:52:46 +0530282 elif item[args["target_ref_field"]]:
Nabin Hait868766d2019-07-15 18:02:58 +0530283 self.check_overflow_with_allowance(item, args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530284
Nabin Hait868766d2019-07-15 18:02:58 +0530285 def check_overflow_with_allowance(self, item, args):
Nabin Hait0feebc12013-06-03 16:45:38 +0530286 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530287 Checks if there is overflow condering a relaxation allowance
Nabin Hait0feebc12013-06-03 16:45:38 +0530288 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530289 qty_or_amount = "qty" if "qty" in args["target_ref_field"] else "amount"
Nabin Hait868766d2019-07-15 18:02:58 +0530290
291 # check if overflow is within allowance
Ankush Menat494bd9e2022-03-28 18:52:46 +0530292 (
293 allowance,
294 self.item_allowance,
295 self.global_qty_allowance,
296 self.global_amount_allowance,
297 ) = get_allowance_for(
298 item["item_code"],
299 self.item_allowance,
300 self.global_qty_allowance,
301 self.global_amount_allowance,
302 qty_or_amount,
303 )
Nabin Hait868766d2019-07-15 18:02:58 +0530304
Ankush Menat494bd9e2022-03-28 18:52:46 +0530305 role_allowed_to_over_deliver_receive = frappe.db.get_single_value(
306 "Stock Settings", "role_allowed_to_over_deliver_receive"
307 )
308 role_allowed_to_over_bill = frappe.db.get_single_value(
309 "Accounts Settings", "role_allowed_to_over_bill"
310 )
311 role = (
312 role_allowed_to_over_deliver_receive if qty_or_amount == "qty" else role_allowed_to_over_bill
313 )
nabinhait711e8be2014-07-19 17:00:15 +0530314
Ankush Menat494bd9e2022-03-28 18:52:46 +0530315 overflow_percent = (
316 (item[args["target_field"]] - item[args["target_ref_field"]]) / item[args["target_ref_field"]]
317 ) * 100
Deepesh Gargcb718fc2021-04-19 13:25:15 +0530318
Ankush Menat6ec047c2021-10-27 10:30:05 +0530319 if overflow_percent - allowance > 0.01:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530320 item["max_allowed"] = flt(item[args["target_ref_field"]] * (100 + allowance) / 100)
321 item["reduce_by"] = item[args["target_field"]] - item["max_allowed"]
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530322
Ankush Menat6ec047c2021-10-27 10:30:05 +0530323 if role not in frappe.get_roles():
324 self.limits_crossed_error(args, item, qty_or_amount)
325 else:
326 self.warn_about_bypassing_with_role(item, qty_or_amount, role)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530327
Nabin Hait868766d2019-07-15 18:02:58 +0530328 def limits_crossed_error(self, args, item, qty_or_amount):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530329 """Raise exception for limits crossed"""
Rohit Waghchaureb4a102d2022-09-06 16:22:00 +0530330 if (
331 self.doctype in ["Sales Invoice", "Delivery Note"]
332 and qty_or_amount == "amount"
333 and self.is_internal_customer
334 ):
335 return
336
337 elif (
338 self.doctype in ["Purchase Invoice", "Purchase Receipt"]
339 and qty_or_amount == "amount"
340 and self.is_internal_supplier
341 ):
342 return
343
Nabin Hait868766d2019-07-15 18:02:58 +0530344 if qty_or_amount == "qty":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530345 action_msg = _(
346 'To allow over receipt / delivery, update "Over Receipt/Delivery Allowance" in Stock Settings or the Item.'
347 )
Nabin Hait868766d2019-07-15 18:02:58 +0530348 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530349 action_msg = _(
350 'To allow over billing, update "Over Billing Allowance" in Accounts Settings or the Item.'
351 )
Nabin Hait868766d2019-07-15 18:02:58 +0530352
Ankush Menat494bd9e2022-03-28 18:52:46 +0530353 frappe.throw(
354 _(
355 "This document is over limit by {0} {1} for item {4}. Are you making another {3} against the same {2}?"
356 ).format(
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530357 frappe.bold(_(item["target_ref_field"].title())),
358 frappe.bold(item["reduce_by"]),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530359 frappe.bold(_(args.get("target_dt"))),
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530360 frappe.bold(_(self.doctype)),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530361 frappe.bold(item.get("item_code")),
362 )
363 + "<br><br>"
364 + action_msg,
365 OverAllowanceError,
366 title=_("Limit Crossed"),
367 )
Nabin Hait0feebc12013-06-03 16:45:38 +0530368
Ankush Menat6ec047c2021-10-27 10:30:05 +0530369 def warn_about_bypassing_with_role(self, item, qty_or_amount, role):
barredterra36997d92022-12-13 18:59:20 +0100370 if qty_or_amount == "qty":
371 msg = _("Over Receipt/Delivery of {0} {1} ignored for item {2} because you have {3} role.")
372 else:
373 msg = _("Overbilling of {0} {1} ignored for item {2} because you have {3} role.")
Ankush Menat6ec047c2021-10-27 10:30:05 +0530374
barredterra36997d92022-12-13 18:59:20 +0100375 frappe.msgprint(
376 msg.format(
377 _(item["target_ref_field"].title()),
378 frappe.bold(item["reduce_by"]),
379 frappe.bold(item.get("item_code")),
380 role,
381 ),
382 indicator="orange",
383 alert=True,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530384 )
Ankush Menat6ec047c2021-10-27 10:30:05 +0530385
Anand Doshi6b71ef52016-01-06 16:32:06 +0530386 def update_qty(self, update_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530387 """Updates qty or amount at row level
388
Ankush Menat494bd9e2022-03-28 18:52:46 +0530389 :param update_modified: If true, updates `modified` and `modified_by` for target parent doc
Nabin Hait0feebc12013-06-03 16:45:38 +0530390 """
391 for args in self.status_updater:
392 # condition to include current record (if submit or no if cancel)
Anand Doshif78d1ae2014-03-28 13:55:00 +0530393 if self.docstatus == 1:
Conor74a782d2022-06-17 06:31:27 -0500394 args["cond"] = " or parent='%s'" % self.name.replace('"', '"')
Nabin Hait0feebc12013-06-03 16:45:38 +0530395 else:
Conor74a782d2022-06-17 06:31:27 -0500396 args["cond"] = " and parent!='%s'" % self.name.replace('"', '"')
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530397
Anand Doshi6b71ef52016-01-06 16:32:06 +0530398 self._update_children(args, update_modified)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530399
marination66069df2020-07-31 15:54:05 +0530400 if "percent_join_field" in args or "percent_join_field_parent" in args:
Anand Doshi6b71ef52016-01-06 16:32:06 +0530401 self._update_percent_field_in_targets(args, update_modified)
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530402
Anand Doshi6b71ef52016-01-06 16:32:06 +0530403 def _update_children(self, args, update_modified):
Anand Doshife13bfe2015-08-25 12:49:40 +0530404 """Update quantities or amount in child table"""
405 for d in self.get_all_children():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530406 if d.doctype != args["source_dt"]:
Anand Doshife13bfe2015-08-25 12:49:40 +0530407 continue
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530408
Anand Doshi6b71ef52016-01-06 16:32:06 +0530409 self._update_modified(args, update_modified)
410
Anand Doshife13bfe2015-08-25 12:49:40 +0530411 # updates qty in the child table
Ankush Menat494bd9e2022-03-28 18:52:46 +0530412 args["detail_id"] = d.get(args["join_field"])
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530413
Ankush Menat494bd9e2022-03-28 18:52:46 +0530414 args["second_source_condition"] = ""
415 if (
416 args.get("second_source_dt")
417 and args.get("second_source_field")
418 and args.get("second_join_field")
419 ):
Anand Doshife13bfe2015-08-25 12:49:40 +0530420 if not args.get("second_source_extra_cond"):
421 args["second_source_extra_cond"] = ""
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530422
Ankush Menat494bd9e2022-03-28 18:52:46 +0530423 args["second_source_condition"] = frappe.db.sql(
424 """ select ifnull((select sum(%(second_source_field)s)
Anand Doshife13bfe2015-08-25 12:49:40 +0530425 from `tab%(second_source_dt)s`
Conor74a782d2022-06-17 06:31:27 -0500426 where `%(second_join_field)s`='%(detail_id)s'
Rohit Waghchaure3eea3c62020-11-18 20:17:52 +0530427 and (`tab%(second_source_dt)s`.docstatus=1)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530428 %(second_source_extra_cond)s), 0) """
429 % args
430 )[0][0]
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530431
Ankush Menat494bd9e2022-03-28 18:52:46 +0530432 if args["detail_id"]:
433 if not args.get("extra_cond"):
434 args["extra_cond"] = ""
Alcheze52ae4e2018-09-06 18:27:06 +0530435
Ankush Menat494bd9e2022-03-28 18:52:46 +0530436 args["source_dt_value"] = (
437 frappe.db.sql(
438 """
Anand Doshi6b71ef52016-01-06 16:32:06 +0530439 (select ifnull(sum(%(source_field)s), 0)
Conor74a782d2022-06-17 06:31:27 -0500440 from `tab%(source_dt)s` where `%(join_field)s`='%(detail_id)s'
Anand Doshi6b71ef52016-01-06 16:32:06 +0530441 and (docstatus=1 %(cond)s) %(extra_cond)s)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530442 """
443 % args
444 )[0][0]
445 or 0.0
446 )
Rohit Waghchaure3eea3c62020-11-18 20:17:52 +0530447
Ankush Menat494bd9e2022-03-28 18:52:46 +0530448 if args["second_source_condition"]:
449 args["source_dt_value"] += flt(args["second_source_condition"])
Rohit Waghchaure3eea3c62020-11-18 20:17:52 +0530450
Ankush Menat494bd9e2022-03-28 18:52:46 +0530451 frappe.db.sql(
452 """update `tab%(target_dt)s`
Rohit Waghchaure3eea3c62020-11-18 20:17:52 +0530453 set %(target_field)s = %(source_dt_value)s %(update_modified)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530454 where name='%(detail_id)s'"""
455 % args
456 )
Anand Doshi6b71ef52016-01-06 16:32:06 +0530457
458 def _update_percent_field_in_targets(self, args, update_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530459 """Update percent field in parent transaction"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530460 if args.get("percent_join_field_parent"):
marination66069df2020-07-31 15:54:05 +0530461 # if reference to target doc where % is to be updated, is
462 # in source doc's parent form, consider percent_join_field_parent
Ankush Menat494bd9e2022-03-28 18:52:46 +0530463 args["name"] = self.get(args["percent_join_field_parent"])
marination66069df2020-07-31 15:54:05 +0530464 self._update_percent_field(args, update_modified)
465 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530466 distinct_transactions = set(
467 d.get(args["percent_join_field"]) for d in self.get_all_children(args["source_dt"])
468 )
Anand Doshife13bfe2015-08-25 12:49:40 +0530469
marination66069df2020-07-31 15:54:05 +0530470 for name in distinct_transactions:
471 if name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530472 args["name"] = name
marination66069df2020-07-31 15:54:05 +0530473 self._update_percent_field(args, update_modified)
Anand Doshife13bfe2015-08-25 12:49:40 +0530474
Anand Doshi6b71ef52016-01-06 16:32:06 +0530475 def _update_percent_field(self, args, update_modified=True):
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530476 """Update percent field in parent transaction"""
Anand Doshi6b71ef52016-01-06 16:32:06 +0530477
478 self._update_modified(args, update_modified)
Alcheze52ae4e2018-09-06 18:27:06 +0530479
Ankush Menat494bd9e2022-03-28 18:52:46 +0530480 if args.get("target_parent_field"):
481 frappe.db.sql(
482 """update `tab%(target_parent_dt)s`
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530483 set %(target_parent_field)s = round(
484 ifnull((select
Conorea28ed12022-06-17 10:47:48 -0500485 ifnull(sum(case when abs(%(target_ref_field)s) > abs(%(target_field)s) then abs(%(target_field)s) else abs(%(target_ref_field)s) end), 0)
RobertSchoutendb33ebb2016-09-12 14:54:46 +0800486 / sum(abs(%(target_ref_field)s)) * 100
Deepesh Garg12ad2aa2023-03-28 15:33:59 +0530487 from `tab%(target_dt)s` where parent='%(name)s' and parenttype='%(target_parent_dt)s' having sum(abs(%(target_ref_field)s)) > 0), 0), 6)
Anand Doshi6b71ef52016-01-06 16:32:06 +0530488 %(update_modified)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530489 where name='%(name)s'"""
490 % args
491 )
Anand Doshife13bfe2015-08-25 12:49:40 +0530492
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530493 # update field
Ankush Menat494bd9e2022-03-28 18:52:46 +0530494 if args.get("status_field"):
495 frappe.db.sql(
496 """update `tab%(target_parent_dt)s`
Conorea28ed12022-06-17 10:47:48 -0500497 set %(status_field)s = (case when %(target_parent_field)s<0.001 then 'Not %(keyword)s'
498 else case when %(target_parent_field)s>=99.999999 then 'Fully %(keyword)s'
499 else 'Partly %(keyword)s' end end)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530500 where name='%(name)s'"""
501 % args
502 )
Anand Doshife13bfe2015-08-25 12:49:40 +0530503
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530504 if update_modified:
505 target = frappe.get_doc(args["target_parent_dt"], args["name"])
506 target.set_status(update=True)
507 target.notify_update()
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530508
Anand Doshi6b71ef52016-01-06 16:32:06 +0530509 def _update_modified(self, args, update_modified):
Sagar Vorad932cba2021-08-17 13:17:09 +0530510 if not update_modified:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530511 args["update_modified"] = ""
Sagar Vorad932cba2021-08-17 13:17:09 +0530512 return
513
Ankush Menat494bd9e2022-03-28 18:52:46 +0530514 args["update_modified"] = ", modified = {0}, modified_by = {1}".format(
515 frappe.db.escape(now()), frappe.db.escape(frappe.session.user)
Sagar Vorad932cba2021-08-17 13:17:09 +0530516 )
Anand Doshi6b71ef52016-01-06 16:32:06 +0530517
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530518 def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
Himanshu Mishra70029b82019-05-29 14:19:35 +0530519 ref_fieldname = frappe.scrub(ref_dt)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530520
Ankush Menat494bd9e2022-03-28 18:52:46 +0530521 ref_docs = [
522 item.get(ref_fieldname) for item in (self.get("items") or []) if item.get(ref_fieldname)
523 ]
Himanshu Mishra70029b82019-05-29 14:19:35 +0530524 if not ref_docs:
525 return
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530526
Ankush Menat494bd9e2022-03-28 18:52:46 +0530527 zero_amount_refdocs = frappe.db.sql_list(
528 """
Himanshu Mishra70029b82019-05-29 14:19:35 +0530529 SELECT
530 name
531 from
532 `tab{ref_dt}`
533 where
534 docstatus = 1
535 and base_net_total = 0
536 and name in %(ref_docs)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530537 """.format(
538 ref_dt=ref_dt
539 ),
540 {"ref_docs": ref_docs},
541 )
Himanshu Mishra70029b82019-05-29 14:19:35 +0530542
543 if zero_amount_refdocs:
544 self.update_billing_status(zero_amount_refdocs, ref_dt, ref_fieldname)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530545
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530546 def update_billing_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530547 for ref_dn in zero_amount_refdoc:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530548 ref_doc_qty = flt(
549 frappe.db.sql(
550 """select ifnull(sum(qty), 0) from `tab%s Item`
551 where parent=%s"""
552 % (ref_dt, "%s"),
553 (ref_dn),
554 )[0][0]
555 )
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530556
Ankush Menat494bd9e2022-03-28 18:52:46 +0530557 billed_qty = flt(
558 frappe.db.sql(
559 """select ifnull(sum(qty), 0)
560 from `tab%s Item` where %s=%s and docstatus=1"""
561 % (self.doctype, ref_fieldname, "%s"),
562 (ref_dn),
563 )[0][0]
564 )
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530565
Alcheze52ae4e2018-09-06 18:27:06 +0530566 per_billed = (min(ref_doc_qty, billed_qty) / ref_doc_qty) * 100
Rushabh Mehtafc8e5892016-07-20 12:08:47 +0530567
568 ref_doc = frappe.get_doc(ref_dt, ref_dn)
569
570 ref_doc.db_set("per_billed", per_billed)
Deepesh Gargd6796922022-02-06 11:35:23 +0530571
572 # set billling status
Ankush Menat494bd9e2022-03-28 18:52:46 +0530573 if hasattr(ref_doc, "billing_status"):
Deepesh Gargd6796922022-02-06 11:35:23 +0530574 if ref_doc.per_billed < 0.001:
575 ref_doc.db_set("billing_status", "Not Billed")
576 elif ref_doc.per_billed > 99.999999:
577 ref_doc.db_set("billing_status", "Fully Billed")
578 else:
579 ref_doc.db_set("billing_status", "Partly Billed")
580
Rohit Waghchaure770d04e2016-10-05 23:02:15 +0530581 ref_doc.set_status(update=True)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530582
Ankush Menat494bd9e2022-03-28 18:52:46 +0530583
584def get_allowance_for(
585 item_code,
586 item_allowance=None,
587 global_qty_allowance=None,
588 global_amount_allowance=None,
589 qty_or_amount="qty",
590):
Nabin Hait7f0406f2014-01-03 17:43:19 +0530591 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530592 Returns the allowance for the item, if not set, returns global allowance
Nabin Hait7f0406f2014-01-03 17:43:19 +0530593 """
Ankush Menat7eac4a22021-04-19 10:33:39 +0530594 if item_allowance is None:
595 item_allowance = {}
Nabin Hait868766d2019-07-15 18:02:58 +0530596 if qty_or_amount == "qty":
597 if item_allowance.get(item_code, frappe._dict()).get("qty"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530598 return (
599 item_allowance[item_code].qty,
600 item_allowance,
601 global_qty_allowance,
602 global_amount_allowance,
603 )
Nabin Hait868766d2019-07-15 18:02:58 +0530604 else:
605 if item_allowance.get(item_code, frappe._dict()).get("amount"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530606 return (
607 item_allowance[item_code].amount,
608 item_allowance,
609 global_qty_allowance,
610 global_amount_allowance,
611 )
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530612
Ankush Menat494bd9e2022-03-28 18:52:46 +0530613 qty_allowance, over_billing_allowance = frappe.db.get_value(
614 "Item", item_code, ["over_delivery_receipt_allowance", "over_billing_allowance"]
615 )
Nabin Hait7f0406f2014-01-03 17:43:19 +0530616
Nabin Hait868766d2019-07-15 18:02:58 +0530617 if qty_or_amount == "qty" and not qty_allowance:
618 if global_qty_allowance == None:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530619 global_qty_allowance = flt(
620 frappe.db.get_single_value("Stock Settings", "over_delivery_receipt_allowance")
621 )
Nabin Hait868766d2019-07-15 18:02:58 +0530622 qty_allowance = global_qty_allowance
623 elif qty_or_amount == "amount" and not over_billing_allowance:
624 if global_amount_allowance == None:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530625 global_amount_allowance = flt(
626 frappe.db.get_single_value("Accounts Settings", "over_billing_allowance")
627 )
Nabin Hait868766d2019-07-15 18:02:58 +0530628 over_billing_allowance = global_amount_allowance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530629
Nabin Hait868766d2019-07-15 18:02:58 +0530630 if qty_or_amount == "qty":
631 allowance = qty_allowance
632 item_allowance.setdefault(item_code, frappe._dict()).setdefault("qty", qty_allowance)
633 else:
634 allowance = over_billing_allowance
635 item_allowance.setdefault(item_code, frappe._dict()).setdefault("amount", over_billing_allowance)
636
637 return allowance, item_allowance, global_qty_allowance, global_amount_allowance