blob: 73a248fb531d6667d10493edf822edcf5a51fe0e [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 [
57 "Completed",
58 "eval:(self.per_delivered == 100 or self.skip_delivery_note) and self.per_billed == 100 and self.docstatus == 1",
59 ],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053060 ["Cancelled", "eval:self.docstatus==2"],
Deepesh Garg597ef0a2023-01-20 19:44:06 +053061 ["Closed", "eval:self.status=='Closed' and self.docstatus != 2"],
Mangesh-Khairnar5eb66ae2019-03-01 16:23:27 +053062 ["On Hold", "eval:self.status=='On Hold'"],
Rushabh Mehtad10ba852015-10-02 12:42:48 +053063 ],
64 "Purchase Order": [
65 ["Draft", None],
Ankush Menat494bd9e2022-03-28 18:52:46 +053066 [
67 "To Receive and Bill",
68 "eval:self.per_received < 100 and self.per_billed < 100 and self.docstatus == 1",
69 ],
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 [
76 "Completed",
77 "eval:self.per_received >= 100 and self.per_billed == 100 and self.docstatus == 1",
78 ],
Saurabh6d64fe32015-10-23 10:40:32 +053079 ["Delivered", "eval:self.status=='Delivered'"],
Anand Doshif78d1ae2014-03-28 13:55:00 +053080 ["Cancelled", "eval:self.docstatus==2"],
Mangesh-Khairnar439546c2019-03-11 16:40:27 +053081 ["On Hold", "eval:self.status=='On Hold'"],
Deepesh Garg597ef0a2023-01-20 19:44:06 +053082 ["Closed", "eval:self.status=='Closed' and self.docstatus != 2"],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053083 ],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053084 "Delivery Note": [
85 ["Draft", None],
Nabin Hait5b13b992015-12-28 13:03:55 +053086 ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
marinationba37fe72020-07-31 20:01:06 +053087 ["Return Issued", "eval:self.per_returned == 100 and self.docstatus == 1"],
Nabin Hait5b13b992015-12-28 13:03:55 +053088 ["Completed", "eval:self.per_billed == 100 and self.docstatus == 1"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053089 ["Cancelled", "eval:self.docstatus==2"],
Deepesh Garg597ef0a2023-01-20 19:44:06 +053090 ["Closed", "eval:self.status=='Closed' and self.docstatus != 2"],
Rushabh Mehta9dd8aab2015-05-18 11:18:55 +053091 ],
92 "Purchase Receipt": [
93 ["Draft", None],
Nabin Haitbdab0ee2015-12-30 19:08:11 +053094 ["To Bill", "eval:self.per_billed < 100 and self.docstatus == 1"],
marination66069df2020-07-31 15:54:05 +053095 ["Return Issued", "eval:self.per_returned == 100 and self.docstatus == 1"],
Nabin Haitbdab0ee2015-12-30 19:08:11 +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"],
tundebabzy99b734b2017-06-07 07:32:07 +010099 ],
100 "Material Request": [
101 ["Draft", None],
102 ["Stopped", "eval:self.status == 'Stopped'"],
103 ["Cancelled", "eval:self.docstatus == 2"],
104 ["Pending", "eval:self.status != 'Stopped' and self.per_ordered == 0 and self.docstatus == 1"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530105 [
106 "Ordered",
107 "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'",
108 ],
109 [
110 "Transferred",
111 "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Material Transfer'",
112 ],
113 [
114 "Issued",
115 "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Material Issue'",
116 ],
117 [
118 "Received",
119 "eval:self.status != 'Stopped' and self.per_received == 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'",
120 ],
121 [
122 "Partially Received",
123 "eval:self.status != 'Stopped' and self.per_received > 0 and self.per_received < 100 and self.docstatus == 1 and self.material_request_type == 'Purchase'",
124 ],
125 [
126 "Partially Ordered",
127 "eval:self.status != 'Stopped' and self.per_ordered < 100 and self.per_ordered > 0 and self.docstatus == 1",
128 ],
129 [
130 "Manufactured",
131 "eval:self.status != 'Stopped' and self.per_ordered == 100 and self.docstatus == 1 and self.material_request_type == 'Manufacture'",
132 ],
Nabin Hait34c551d2019-07-03 10:34:31 +0530133 ],
134 "Bank Transaction": [
135 ["Unreconciled", "eval:self.docstatus == 1 and self.unallocated_amount>0"],
Saqib62114b22021-08-25 16:25:51 +0530136 ["Reconciled", "eval:self.docstatus == 1 and self.unallocated_amount<=0"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530137 ["Cancelled", "eval:self.docstatus == 2"],
Saqiba6f98d42020-07-23 18:51:26 +0530138 ],
139 "POS Opening Entry": [
140 ["Draft", None],
141 ["Open", "eval:self.docstatus == 1 and not self.pos_closing_entry"],
142 ["Closed", "eval:self.docstatus == 1 and self.pos_closing_entry"],
143 ["Cancelled", "eval:self.docstatus == 2"],
Saqib675a8332021-01-28 18:42:43 +0530144 ],
145 "POS Closing Entry": [
146 ["Draft", None],
147 ["Submitted", "eval:self.docstatus == 1"],
148 ["Queued", "eval:self.status == 'Queued'"],
Saqib900a8fb2021-05-06 17:02:47 +0530149 ["Failed", "eval:self.status == 'Failed'"],
Saqib675a8332021-01-28 18:42:43 +0530150 ["Cancelled", "eval:self.docstatus == 2"],
Ganga Manojf2eb8dd2021-05-10 14:02:58 +0530151 ],
152 "Transaction Deletion Record": [
153 ["Draft", None],
154 ["Completed", "eval:self.docstatus == 1"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155 ],
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530156}
157
Ankush Menat494bd9e2022-03-28 18:52:46 +0530158
Anand Doshi424c0332014-04-21 15:06:56 +0530159class StatusUpdater(Document):
Nabin Hait0feebc12013-06-03 16:45:38 +0530160 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530161 Updates the status of the calling records
162 Delivery Note: Update Delivered Qty, Update Percent and Validate over delivery
163 Sales Invoice: Update Billed Amt, Update Percent and Validate over billing
164 Installation Note: Update Installed Qty, Update Percent Qty and Validate over installation
Nabin Hait0feebc12013-06-03 16:45:38 +0530165 """
166
167 def update_prevdoc_status(self):
168 self.update_qty()
169 self.validate_qty()
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530170
Saurabh70ed6ed2015-12-08 14:02:53 +0530171 def set_status(self, update=False, status=None, update_modified=True):
Rushabh Mehtacb067aa2014-08-19 16:20:04 +0530172 if self.is_new():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530173 if self.get("amended_from"):
174 self.status = "Draft"
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530175 return
Anand Doshi6b71ef52016-01-06 16:32:06 +0530176
Anand Doshif78d1ae2014-03-28 13:55:00 +0530177 if self.doctype in status_map:
Nabin Haitcabf9c52014-08-21 16:34:38 +0530178 _status = self.status
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530179 if status and update:
180 self.db_set("status", status)
181
Anand Doshif78d1ae2014-03-28 13:55:00 +0530182 sl = status_map[self.doctype][:]
Rushabh Mehta6856d742013-10-03 18:12:36 +0530183 sl.reverse()
184 for s in sl:
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530185 if not s[1]:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530186 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530187 break
Rushabh Mehta6856d742013-10-03 18:12:36 +0530188 elif s[1].startswith("eval:"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530189 if frappe.safe_eval(
190 s[1][5:],
191 None,
192 {
193 "self": self.as_dict(),
194 "getdate": getdate,
195 "nowdate": nowdate,
196 "get_value": frappe.db.get_value,
197 },
198 ):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530199 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530200 break
201 elif getattr(self, s[1])():
Anand Doshif78d1ae2014-03-28 13:55:00 +0530202 self.status = s[0]
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530203 break
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530204
Ankush Menat494bd9e2022-03-28 18:52:46 +0530205 if self.status != _status and self.status not in (
206 "Cancelled",
207 "Partially Ordered",
208 "Ordered",
209 "Issued",
210 "Transferred",
211 ):
Anand Doshi7b34ebe2015-01-07 15:41:32 +0530212 self.add_comment("Label", _(self.status))
Anand Doshi6b71ef52016-01-06 16:32:06 +0530213
Rushabh Mehta800b3aa2013-10-03 17:26:33 +0530214 if update:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530215 self.db_set("status", self.status, update_modified=update_modified)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530216
Nabin Hait0feebc12013-06-03 16:45:38 +0530217 def validate_qty(self):
Rushabh Mehtaa9ba5ef2014-12-19 16:20:32 +0530218 """Validates qty at row level"""
Nabin Hait868766d2019-07-15 18:02:58 +0530219 self.item_allowance = {}
220 self.global_qty_allowance = None
221 self.global_amount_allowance = None
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530222
Nabin Hait0feebc12013-06-03 16:45:38 +0530223 for args in self.status_updater:
Anand Doshife13bfe2015-08-25 12:49:40 +0530224 if "target_ref_field" not in args:
225 # if target_ref_field is not specified, the programmer does not want to validate qty / amount
226 continue
227
Nabin Hait0feebc12013-06-03 16:45:38 +0530228 # get unique transactions to update
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530229 for d in self.get_all_children():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530230 if hasattr(d, "qty") and d.qty < 0 and not self.get("is_return"):
rohitwaghchaure12aa4262018-03-12 11:20:30 +0530231 frappe.throw(_("For an item {0}, quantity must be positive number").format(d.item_code))
232
Ankush Menat494bd9e2022-03-28 18:52:46 +0530233 if hasattr(d, "qty") and d.qty > 0 and self.get("is_return"):
rohitwaghchaure70489252018-06-11 12:02:14 +0530234 frappe.throw(_("For an item {0}, quantity must be negative number").format(d.item_code))
235
ruthra kumara0fc6852023-08-14 17:38:44 +0530236 if not frappe.db.get_single_value("Selling Settings", "allow_negative_rates_for_items"):
237 if hasattr(d, "item_code") and hasattr(d, "rate") and flt(d.rate) < 0:
238 frappe.throw(
239 _(
240 "For item {0}, rate must be a positive number. To Allow negative rates, enable {1} in {2}"
241 ).format(
242 frappe.bold(d.item_code),
243 frappe.bold(_("`Allow Negative rates for Items`")),
244 get_link_to_form("Selling Settings", "Selling Settings"),
245 ),
246 )
Devin Slauenwhitededf24b2023-08-02 06:56:55 -0400247
Ankush Menat494bd9e2022-03-28 18:52:46 +0530248 if d.doctype == args["source_dt"] and d.get(args["join_field"]):
249 args["name"] = d.get(args["join_field"])
Nabin Hait0feebc12013-06-03 16:45:38 +0530250
251 # get all qty where qty > target_field
Ankush Menat494bd9e2022-03-28 18:52:46 +0530252 item = frappe.db.sql(
253 """select item_code, `{target_ref_field}`,
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530254 `{target_field}`, parenttype, parent from `tab{target_dt}`
255 where `{target_ref_field}` < `{target_field}`
Ankush Menat494bd9e2022-03-28 18:52:46 +0530256 and name=%s and docstatus=1""".format(
257 **args
258 ),
259 args["name"],
260 as_dict=1,
261 )
Nabin Hait0feebc12013-06-03 16:45:38 +0530262 if item:
263 item = item[0]
Ankush Menat494bd9e2022-03-28 18:52:46 +0530264 item["idx"] = d.idx
265 item["target_ref_field"] = args["target_ref_field"].replace("_", " ")
Nabin Hait0feebc12013-06-03 16:45:38 +0530266
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530267 # if not item[args['target_ref_field']]:
268 # 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 +0530269 if args.get("no_allowance"):
270 item["reduce_by"] = item[args["target_field"]] - item[args["target_ref_field"]]
271 if item["reduce_by"] > 0.01:
Marica4e6b3ad2020-01-15 19:22:35 +0530272 self.limits_crossed_error(args, item, "qty")
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530273
Ankush Menat494bd9e2022-03-28 18:52:46 +0530274 elif item[args["target_ref_field"]]:
Nabin Hait868766d2019-07-15 18:02:58 +0530275 self.check_overflow_with_allowance(item, args)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530276
Nabin Hait868766d2019-07-15 18:02:58 +0530277 def check_overflow_with_allowance(self, item, args):
Nabin Hait0feebc12013-06-03 16:45:38 +0530278 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530279 Checks if there is overflow condering a relaxation allowance
Nabin Hait0feebc12013-06-03 16:45:38 +0530280 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530281 qty_or_amount = "qty" if "qty" in args["target_ref_field"] else "amount"
Nabin Hait868766d2019-07-15 18:02:58 +0530282
283 # check if overflow is within allowance
Ankush Menat494bd9e2022-03-28 18:52:46 +0530284 (
285 allowance,
286 self.item_allowance,
287 self.global_qty_allowance,
288 self.global_amount_allowance,
289 ) = get_allowance_for(
290 item["item_code"],
291 self.item_allowance,
292 self.global_qty_allowance,
293 self.global_amount_allowance,
294 qty_or_amount,
295 )
Nabin Hait868766d2019-07-15 18:02:58 +0530296
Ankush Menat494bd9e2022-03-28 18:52:46 +0530297 role_allowed_to_over_deliver_receive = frappe.db.get_single_value(
298 "Stock Settings", "role_allowed_to_over_deliver_receive"
299 )
300 role_allowed_to_over_bill = frappe.db.get_single_value(
301 "Accounts Settings", "role_allowed_to_over_bill"
302 )
303 role = (
304 role_allowed_to_over_deliver_receive if qty_or_amount == "qty" else role_allowed_to_over_bill
305 )
nabinhait711e8be2014-07-19 17:00:15 +0530306
Ankush Menat494bd9e2022-03-28 18:52:46 +0530307 overflow_percent = (
308 (item[args["target_field"]] - item[args["target_ref_field"]]) / item[args["target_ref_field"]]
309 ) * 100
Deepesh Gargcb718fc2021-04-19 13:25:15 +0530310
Ankush Menat6ec047c2021-10-27 10:30:05 +0530311 if overflow_percent - allowance > 0.01:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530312 item["max_allowed"] = flt(item[args["target_ref_field"]] * (100 + allowance) / 100)
313 item["reduce_by"] = item[args["target_field"]] - item["max_allowed"]
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530314
Ankush Menat6ec047c2021-10-27 10:30:05 +0530315 if role not in frappe.get_roles():
316 self.limits_crossed_error(args, item, qty_or_amount)
317 else:
318 self.warn_about_bypassing_with_role(item, qty_or_amount, role)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530319
Nabin Hait868766d2019-07-15 18:02:58 +0530320 def limits_crossed_error(self, args, item, qty_or_amount):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530321 """Raise exception for limits crossed"""
Rohit Waghchaureb4a102d2022-09-06 16:22:00 +0530322 if (
323 self.doctype in ["Sales Invoice", "Delivery Note"]
324 and qty_or_amount == "amount"
325 and self.is_internal_customer
326 ):
327 return
328
329 elif (
330 self.doctype in ["Purchase Invoice", "Purchase Receipt"]
331 and qty_or_amount == "amount"
332 and self.is_internal_supplier
333 ):
334 return
335
Nabin Hait868766d2019-07-15 18:02:58 +0530336 if qty_or_amount == "qty":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530337 action_msg = _(
338 'To allow over receipt / delivery, update "Over Receipt/Delivery Allowance" in Stock Settings or the Item.'
339 )
Nabin Hait868766d2019-07-15 18:02:58 +0530340 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530341 action_msg = _(
342 'To allow over billing, update "Over Billing Allowance" in Accounts Settings or the Item.'
343 )
Nabin Hait868766d2019-07-15 18:02:58 +0530344
Ankush Menat494bd9e2022-03-28 18:52:46 +0530345 frappe.throw(
346 _(
347 "This document is over limit by {0} {1} for item {4}. Are you making another {3} against the same {2}?"
348 ).format(
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530349 frappe.bold(_(item["target_ref_field"].title())),
350 frappe.bold(item["reduce_by"]),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530351 frappe.bold(_(args.get("target_dt"))),
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530352 frappe.bold(_(self.doctype)),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530353 frappe.bold(item.get("item_code")),
354 )
355 + "<br><br>"
356 + action_msg,
357 OverAllowanceError,
358 title=_("Limit Crossed"),
359 )
Nabin Hait0feebc12013-06-03 16:45:38 +0530360
Ankush Menat6ec047c2021-10-27 10:30:05 +0530361 def warn_about_bypassing_with_role(self, item, qty_or_amount, role):
barredterra36997d92022-12-13 18:59:20 +0100362 if qty_or_amount == "qty":
363 msg = _("Over Receipt/Delivery of {0} {1} ignored for item {2} because you have {3} role.")
364 else:
365 msg = _("Overbilling of {0} {1} ignored for item {2} because you have {3} role.")
Ankush Menat6ec047c2021-10-27 10:30:05 +0530366
barredterra36997d92022-12-13 18:59:20 +0100367 frappe.msgprint(
368 msg.format(
369 _(item["target_ref_field"].title()),
370 frappe.bold(item["reduce_by"]),
371 frappe.bold(item.get("item_code")),
372 role,
373 ),
374 indicator="orange",
375 alert=True,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530376 )
Ankush Menat6ec047c2021-10-27 10:30:05 +0530377
Anand Doshi6b71ef52016-01-06 16:32:06 +0530378 def update_qty(self, update_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530379 """Updates qty or amount at row level
380
Ankush Menat494bd9e2022-03-28 18:52:46 +0530381 :param update_modified: If true, updates `modified` and `modified_by` for target parent doc
Nabin Hait0feebc12013-06-03 16:45:38 +0530382 """
383 for args in self.status_updater:
384 # condition to include current record (if submit or no if cancel)
Anand Doshif78d1ae2014-03-28 13:55:00 +0530385 if self.docstatus == 1:
Conor74a782d2022-06-17 06:31:27 -0500386 args["cond"] = " or parent='%s'" % self.name.replace('"', '"')
Nabin Hait0feebc12013-06-03 16:45:38 +0530387 else:
Conor74a782d2022-06-17 06:31:27 -0500388 args["cond"] = " and parent!='%s'" % self.name.replace('"', '"')
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530389
Anand Doshi6b71ef52016-01-06 16:32:06 +0530390 self._update_children(args, update_modified)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530391
marination66069df2020-07-31 15:54:05 +0530392 if "percent_join_field" in args or "percent_join_field_parent" in args:
Anand Doshi6b71ef52016-01-06 16:32:06 +0530393 self._update_percent_field_in_targets(args, update_modified)
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530394
Anand Doshi6b71ef52016-01-06 16:32:06 +0530395 def _update_children(self, args, update_modified):
Anand Doshife13bfe2015-08-25 12:49:40 +0530396 """Update quantities or amount in child table"""
397 for d in self.get_all_children():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530398 if d.doctype != args["source_dt"]:
Anand Doshife13bfe2015-08-25 12:49:40 +0530399 continue
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530400
Anand Doshi6b71ef52016-01-06 16:32:06 +0530401 self._update_modified(args, update_modified)
402
Anand Doshife13bfe2015-08-25 12:49:40 +0530403 # updates qty in the child table
Ankush Menat494bd9e2022-03-28 18:52:46 +0530404 args["detail_id"] = d.get(args["join_field"])
ankitjavalkarwork9aadb0d2014-10-07 17:38:46 +0530405
Ankush Menat494bd9e2022-03-28 18:52:46 +0530406 args["second_source_condition"] = ""
407 if (
408 args.get("second_source_dt")
409 and args.get("second_source_field")
410 and args.get("second_join_field")
411 ):
Anand Doshife13bfe2015-08-25 12:49:40 +0530412 if not args.get("second_source_extra_cond"):
413 args["second_source_extra_cond"] = ""
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530414
Ankush Menat494bd9e2022-03-28 18:52:46 +0530415 args["second_source_condition"] = frappe.db.sql(
416 """ select ifnull((select sum(%(second_source_field)s)
Anand Doshife13bfe2015-08-25 12:49:40 +0530417 from `tab%(second_source_dt)s`
Conor74a782d2022-06-17 06:31:27 -0500418 where `%(second_join_field)s`='%(detail_id)s'
Rohit Waghchaure3eea3c62020-11-18 20:17:52 +0530419 and (`tab%(second_source_dt)s`.docstatus=1)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530420 %(second_source_extra_cond)s), 0) """
421 % args
422 )[0][0]
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530423
Ankush Menat494bd9e2022-03-28 18:52:46 +0530424 if args["detail_id"]:
425 if not args.get("extra_cond"):
426 args["extra_cond"] = ""
Alcheze52ae4e2018-09-06 18:27:06 +0530427
Ankush Menat494bd9e2022-03-28 18:52:46 +0530428 args["source_dt_value"] = (
429 frappe.db.sql(
430 """
Anand Doshi6b71ef52016-01-06 16:32:06 +0530431 (select ifnull(sum(%(source_field)s), 0)
Conor74a782d2022-06-17 06:31:27 -0500432 from `tab%(source_dt)s` where `%(join_field)s`='%(detail_id)s'
Anand Doshi6b71ef52016-01-06 16:32:06 +0530433 and (docstatus=1 %(cond)s) %(extra_cond)s)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530434 """
435 % args
436 )[0][0]
437 or 0.0
438 )
Rohit Waghchaure3eea3c62020-11-18 20:17:52 +0530439
Ankush Menat494bd9e2022-03-28 18:52:46 +0530440 if args["second_source_condition"]:
441 args["source_dt_value"] += flt(args["second_source_condition"])
Rohit Waghchaure3eea3c62020-11-18 20:17:52 +0530442
Ankush Menat494bd9e2022-03-28 18:52:46 +0530443 frappe.db.sql(
444 """update `tab%(target_dt)s`
Rohit Waghchaure3eea3c62020-11-18 20:17:52 +0530445 set %(target_field)s = %(source_dt_value)s %(update_modified)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530446 where name='%(detail_id)s'"""
447 % args
448 )
Anand Doshi6b71ef52016-01-06 16:32:06 +0530449
450 def _update_percent_field_in_targets(self, args, update_modified=True):
Anand Doshife13bfe2015-08-25 12:49:40 +0530451 """Update percent field in parent transaction"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530452 if args.get("percent_join_field_parent"):
marination66069df2020-07-31 15:54:05 +0530453 # if reference to target doc where % is to be updated, is
454 # in source doc's parent form, consider percent_join_field_parent
Ankush Menat494bd9e2022-03-28 18:52:46 +0530455 args["name"] = self.get(args["percent_join_field_parent"])
marination66069df2020-07-31 15:54:05 +0530456 self._update_percent_field(args, update_modified)
457 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530458 distinct_transactions = set(
459 d.get(args["percent_join_field"]) for d in self.get_all_children(args["source_dt"])
460 )
Anand Doshife13bfe2015-08-25 12:49:40 +0530461
marination66069df2020-07-31 15:54:05 +0530462 for name in distinct_transactions:
463 if name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530464 args["name"] = name
marination66069df2020-07-31 15:54:05 +0530465 self._update_percent_field(args, update_modified)
Anand Doshife13bfe2015-08-25 12:49:40 +0530466
Anand Doshi6b71ef52016-01-06 16:32:06 +0530467 def _update_percent_field(self, args, update_modified=True):
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530468 """Update percent field in parent transaction"""
Anand Doshi6b71ef52016-01-06 16:32:06 +0530469
470 self._update_modified(args, update_modified)
Alcheze52ae4e2018-09-06 18:27:06 +0530471
Ankush Menat494bd9e2022-03-28 18:52:46 +0530472 if args.get("target_parent_field"):
473 frappe.db.sql(
474 """update `tab%(target_parent_dt)s`
Nabin Haitbdab0ee2015-12-30 19:08:11 +0530475 set %(target_parent_field)s = round(
476 ifnull((select
Conorea28ed12022-06-17 10:47:48 -0500477 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 +0800478 / sum(abs(%(target_ref_field)s)) * 100
Deepesh Garg12ad2aa2023-03-28 15:33:59 +0530479 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 +0530480 %(update_modified)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530481 where name='%(name)s'"""
482 % args
483 )
Anand Doshife13bfe2015-08-25 12:49:40 +0530484
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530485 # update field
Ankush Menat494bd9e2022-03-28 18:52:46 +0530486 if args.get("status_field"):
487 frappe.db.sql(
488 """update `tab%(target_parent_dt)s`
Conorea28ed12022-06-17 10:47:48 -0500489 set %(status_field)s = (case when %(target_parent_field)s<0.001 then 'Not %(keyword)s'
490 else case when %(target_parent_field)s>=99.999999 then 'Fully %(keyword)s'
491 else 'Partly %(keyword)s' end end)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530492 where name='%(name)s'"""
493 % args
494 )
Anand Doshife13bfe2015-08-25 12:49:40 +0530495
rohitwaghchaure7be942d2016-11-16 11:14:33 +0530496 if update_modified:
497 target = frappe.get_doc(args["target_parent_dt"], args["name"])
498 target.set_status(update=True)
499 target.notify_update()
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530500
Anand Doshi6b71ef52016-01-06 16:32:06 +0530501 def _update_modified(self, args, update_modified):
Sagar Vorad932cba2021-08-17 13:17:09 +0530502 if not update_modified:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530503 args["update_modified"] = ""
Sagar Vorad932cba2021-08-17 13:17:09 +0530504 return
505
Ankush Menat494bd9e2022-03-28 18:52:46 +0530506 args["update_modified"] = ", modified = {0}, modified_by = {1}".format(
507 frappe.db.escape(now()), frappe.db.escape(frappe.session.user)
Sagar Vorad932cba2021-08-17 13:17:09 +0530508 )
Anand Doshi6b71ef52016-01-06 16:32:06 +0530509
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530510 def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
Himanshu Mishra70029b82019-05-29 14:19:35 +0530511 ref_fieldname = frappe.scrub(ref_dt)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530512
Ankush Menat494bd9e2022-03-28 18:52:46 +0530513 ref_docs = [
514 item.get(ref_fieldname) for item in (self.get("items") or []) if item.get(ref_fieldname)
515 ]
Himanshu Mishra70029b82019-05-29 14:19:35 +0530516 if not ref_docs:
517 return
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530518
Ankush Menat494bd9e2022-03-28 18:52:46 +0530519 zero_amount_refdocs = frappe.db.sql_list(
520 """
Himanshu Mishra70029b82019-05-29 14:19:35 +0530521 SELECT
522 name
523 from
524 `tab{ref_dt}`
525 where
526 docstatus = 1
527 and base_net_total = 0
528 and name in %(ref_docs)s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530529 """.format(
530 ref_dt=ref_dt
531 ),
532 {"ref_docs": ref_docs},
533 )
Himanshu Mishra70029b82019-05-29 14:19:35 +0530534
535 if zero_amount_refdocs:
536 self.update_billing_status(zero_amount_refdocs, ref_dt, ref_fieldname)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530537
Rushabh Mehtad48c2392015-11-04 15:20:50 +0530538 def update_billing_status(self, zero_amount_refdoc, ref_dt, ref_fieldname):
Nabin Hait39eb7fa2014-01-15 17:36:18 +0530539 for ref_dn in zero_amount_refdoc:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530540 ref_doc_qty = flt(
541 frappe.db.sql(
542 """select ifnull(sum(qty), 0) from `tab%s Item`
543 where parent=%s"""
544 % (ref_dt, "%s"),
545 (ref_dn),
546 )[0][0]
547 )
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530548
Ankush Menat494bd9e2022-03-28 18:52:46 +0530549 billed_qty = flt(
550 frappe.db.sql(
551 """select ifnull(sum(qty), 0)
552 from `tab%s Item` where %s=%s and docstatus=1"""
553 % (self.doctype, ref_fieldname, "%s"),
554 (ref_dn),
555 )[0][0]
556 )
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530557
Alcheze52ae4e2018-09-06 18:27:06 +0530558 per_billed = (min(ref_doc_qty, billed_qty) / ref_doc_qty) * 100
Rushabh Mehtafc8e5892016-07-20 12:08:47 +0530559
560 ref_doc = frappe.get_doc(ref_dt, ref_dn)
561
562 ref_doc.db_set("per_billed", per_billed)
Deepesh Gargd6796922022-02-06 11:35:23 +0530563
564 # set billling status
Ankush Menat494bd9e2022-03-28 18:52:46 +0530565 if hasattr(ref_doc, "billing_status"):
Deepesh Gargd6796922022-02-06 11:35:23 +0530566 if ref_doc.per_billed < 0.001:
567 ref_doc.db_set("billing_status", "Not Billed")
568 elif ref_doc.per_billed > 99.999999:
569 ref_doc.db_set("billing_status", "Fully Billed")
570 else:
571 ref_doc.db_set("billing_status", "Partly Billed")
572
Rohit Waghchaure770d04e2016-10-05 23:02:15 +0530573 ref_doc.set_status(update=True)
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530574
Ankush Menat494bd9e2022-03-28 18:52:46 +0530575
576def get_allowance_for(
577 item_code,
578 item_allowance=None,
579 global_qty_allowance=None,
580 global_amount_allowance=None,
581 qty_or_amount="qty",
582):
Nabin Hait7f0406f2014-01-03 17:43:19 +0530583 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530584 Returns the allowance for the item, if not set, returns global allowance
Nabin Hait7f0406f2014-01-03 17:43:19 +0530585 """
Ankush Menat7eac4a22021-04-19 10:33:39 +0530586 if item_allowance is None:
587 item_allowance = {}
Nabin Hait868766d2019-07-15 18:02:58 +0530588 if qty_or_amount == "qty":
589 if item_allowance.get(item_code, frappe._dict()).get("qty"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530590 return (
591 item_allowance[item_code].qty,
592 item_allowance,
593 global_qty_allowance,
594 global_amount_allowance,
595 )
Nabin Hait868766d2019-07-15 18:02:58 +0530596 else:
597 if item_allowance.get(item_code, frappe._dict()).get("amount"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530598 return (
599 item_allowance[item_code].amount,
600 item_allowance,
601 global_qty_allowance,
602 global_amount_allowance,
603 )
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530604
Ankush Menat494bd9e2022-03-28 18:52:46 +0530605 qty_allowance, over_billing_allowance = frappe.db.get_value(
606 "Item", item_code, ["over_delivery_receipt_allowance", "over_billing_allowance"]
607 )
Nabin Hait7f0406f2014-01-03 17:43:19 +0530608
Nabin Hait868766d2019-07-15 18:02:58 +0530609 if qty_or_amount == "qty" and not qty_allowance:
610 if global_qty_allowance == None:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530611 global_qty_allowance = flt(
612 frappe.db.get_single_value("Stock Settings", "over_delivery_receipt_allowance")
613 )
Nabin Hait868766d2019-07-15 18:02:58 +0530614 qty_allowance = global_qty_allowance
615 elif qty_or_amount == "amount" and not over_billing_allowance:
616 if global_amount_allowance == None:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530617 global_amount_allowance = flt(
618 frappe.db.get_single_value("Accounts Settings", "over_billing_allowance")
619 )
Nabin Hait868766d2019-07-15 18:02:58 +0530620 over_billing_allowance = global_amount_allowance
Anand Doshi9fd50bc2014-04-09 19:20:01 +0530621
Nabin Hait868766d2019-07-15 18:02:58 +0530622 if qty_or_amount == "qty":
623 allowance = qty_allowance
624 item_allowance.setdefault(item_code, frappe._dict()).setdefault("qty", qty_allowance)
625 else:
626 allowance = over_billing_allowance
627 item_allowance.setdefault(item_code, frappe._dict()).setdefault("amount", over_billing_allowance)
628
629 return allowance, item_allowance, global_qty_allowance, global_amount_allowance