blob: 3b7812f96c2a9a19c62965925e96d4b4447158cc [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
Rushabh Mehta3966f1d2012-02-23 12:35:32 +05303
Chillar Anand915b3432021-09-02 16:44:59 +05304
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
Nabin Hait3cf67a42015-07-24 13:26:36 +05306import frappe.share
Nabin Haita1c96de2014-02-21 14:44:35 +05307from frappe import _
Nabin Haitf904ac52022-06-10 11:15:22 +05308from frappe.utils import cint, flt, get_time, now_datetime
Chillar Anand915b3432021-09-02 16:44:59 +05309
Rushabh Mehta1f847992013-12-12 19:12:19 +053010from erpnext.controllers.status_updater import StatusUpdater
Anand Doshi756dca72013-01-15 18:39:21 +053011
Achilles Rasquinha1697a7a2018-02-15 11:39:45 +053012
Ankush Menat494bd9e2022-03-28 18:52:46 +053013class UOMMustBeIntegerError(frappe.ValidationError):
14 pass
15
Rushabh Mehtab09d9da2014-01-02 11:47:23 +053016
Nabin Haitb5be7ba2014-01-30 18:47:12 +053017class TransactionBase(StatusUpdater):
Anand Doshiee3d5cc2013-03-13 12:58:54 +053018 def validate_posting_time(self):
Makarand Bauskarb0df6612017-05-16 07:59:58 +053019 # set Edit Posting Date and Time to 1 while data import
Sagar Vora67fe1012017-06-19 12:12:22 +053020 if frappe.flags.in_import and self.posting_date:
Makarand Bauskarb0df6612017-05-16 07:59:58 +053021 self.set_posting_time = 1
22
Ankush Menat494bd9e2022-03-28 18:52:46 +053023 if not getattr(self, "set_posting_time", None):
Rushabh Mehta6b537922017-03-14 16:59:11 +053024 now = now_datetime()
Ankush Menat494bd9e2022-03-28 18:52:46 +053025 self.posting_date = now.strftime("%Y-%m-%d")
26 self.posting_time = now.strftime("%H:%M:%S.%f")
Manas Solankic6d56112018-01-18 11:20:24 +053027 elif self.posting_time:
Faris Ansari184491b2018-01-15 14:18:53 +053028 try:
29 get_time(self.posting_time)
30 except ValueError:
Ankush Menat494bd9e2022-03-28 18:52:46 +053031 frappe.throw(_("Invalid Posting Time"))
Rushabh Mehta2c458992014-04-15 14:36:12 +053032
s-aga-r9a290fd2024-04-17 21:45:27 +053033 def validate_uom_is_integer(self, uom_field, qty_fields, child_dt=None):
34 validate_uom_is_integer(self, uom_field, qty_fields, child_dt)
Rushabh Mehta2c458992014-04-15 14:36:12 +053035
Nabin Haitdd38a262014-12-26 13:15:21 +053036 def validate_with_previous_doc(self, ref):
Ankush Menat494bd9e2022-03-28 18:52:46 +053037 self.exclude_fields = ["conversion_factor", "uom"] if self.get("is_return") else []
rohitwaghchaure0df95fa2018-03-01 11:31:33 +053038
Nabin Hait2bd37772013-07-08 19:00:29 +053039 for key, val in ref.items():
Nabin Hait6e68e0e2013-07-10 15:33:29 +053040 is_child = val.get("is_child_table")
Nabin Hait2bd37772013-07-08 19:00:29 +053041 ref_doc = {}
Nabin Haita9ec49e2013-07-15 16:33:24 +053042 item_ref_dn = []
Nabin Haitdd38a262014-12-26 13:15:21 +053043 for d in self.get_all_children(self.doctype + " Item"):
Anand Doshif78d1ae2014-03-28 13:55:00 +053044 ref_dn = d.get(val["ref_dn_field"])
Nabin Hait6e68e0e2013-07-10 15:33:29 +053045 if ref_dn:
46 if is_child:
47 self.compare_values({key: [ref_dn]}, val["compare_fields"], d)
Nabin Haita9ec49e2013-07-15 16:33:24 +053048 if ref_dn not in item_ref_dn:
49 item_ref_dn.append(ref_dn)
Nabin Hait5e200e42013-07-29 15:29:51 +053050 elif not val.get("allow_duplicate_prev_row_id"):
Rushabh Mehta2c458992014-04-15 14:36:12 +053051 frappe.throw(_("Duplicate row {0} with same {1}").format(d.idx, key))
Nabin Haita9ec49e2013-07-15 16:33:24 +053052 elif ref_dn:
Nabin Hait6e68e0e2013-07-10 15:33:29 +053053 ref_doc.setdefault(key, [])
54 if ref_dn not in ref_doc[key]:
55 ref_doc[key].append(ref_dn)
56 if ref_doc:
Nabin Hait2bd37772013-07-08 19:00:29 +053057 self.compare_values(ref_doc, val["compare_fields"])
Rushabh Mehta2c458992014-04-15 14:36:12 +053058
Nabin Hait2bd37772013-07-08 19:00:29 +053059 def compare_values(self, ref_doc, fields, doc=None):
Rushabh Mehta611b5132015-03-19 17:15:45 +053060 for reference_doctype, ref_dn_list in ref_doc.items():
Akhil Narang3effaf22024-03-27 11:37:26 +053061 prev_doc_detail_map = self.get_prev_doc_reference_details(ref_dn_list, reference_doctype, fields)
Rushabh Mehta611b5132015-03-19 17:15:45 +053062 for reference_name in ref_dn_list:
Deepesh Garg4c61ee32023-04-02 09:35:27 +053063 prevdoc_values = prev_doc_detail_map.get(reference_name)
Rushabh Mehtaafacc3d2015-12-01 15:53:07 +053064 if not prevdoc_values:
65 frappe.throw(_("Invalid reference {0} {1}").format(reference_doctype, reference_name))
66
Nabin Hait6e68e0e2013-07-10 15:33:29 +053067 for field, condition in fields:
rohitwaghchaure0df95fa2018-03-01 11:31:33 +053068 if prevdoc_values[field] is not None and field not in self.exclude_fields:
Anand Doshi63d844b2013-07-10 20:55:15 +053069 self.validate_value(field, condition, prevdoc_values[field], doc)
Anand Doshi414248b2015-08-26 17:56:40 +053070
Deepesh Garg4c61ee32023-04-02 09:35:27 +053071 def get_prev_doc_reference_details(self, reference_names, reference_doctype, fields):
72 prev_doc_detail_map = {}
73 details = frappe.get_all(
74 reference_doctype,
75 filters={"name": ("in", reference_names)},
76 fields=["name"] + [d[0] for d in fields],
77 )
78
79 for d in details:
80 prev_doc_detail_map.setdefault(d.name, d)
81
82 return prev_doc_detail_map
83
Nabin Hait28a9e352015-07-08 13:10:52 +053084 def validate_rate_with_reference_doc(self, ref_details):
Rohit Waghchaureb4a102d2022-09-06 16:22:00 +053085 if self.get("is_internal_supplier"):
86 return
87
Marica5f299a02020-07-06 18:26:56 +053088 buying_doctypes = ["Purchase Order", "Purchase Invoice", "Purchase Receipt"]
Marica5f299a02020-07-06 18:26:56 +053089
90 if self.doctype in buying_doctypes:
Deepesh Garg4c61ee32023-04-02 09:35:27 +053091 action, role_allowed_to_override = frappe.get_cached_value(
92 "Buying Settings", "None", ["maintain_same_rate_action", "role_to_override_stop_action"]
93 )
Marica5f299a02020-07-06 18:26:56 +053094 else:
Deepesh Garg4c61ee32023-04-02 09:35:27 +053095 action, role_allowed_to_override = frappe.get_cached_value(
96 "Selling Settings", "None", ["maintain_same_rate_action", "role_to_override_stop_action"]
97 )
Marica5f299a02020-07-06 18:26:56 +053098
Devin Slauenwhite3f6d8052023-11-23 12:12:12 -050099 stop_actions = []
Nabin Hait28a9e352015-07-08 13:10:52 +0530100 for ref_dt, ref_dn_field, ref_link_field in ref_details:
Deepesh Garg4c61ee32023-04-02 09:35:27 +0530101 reference_names = [d.get(ref_link_field) for d in self.get("items") if d.get(ref_link_field)]
102 reference_details = self.get_reference_details(reference_names, ref_dt + " Item")
Nabin Hait28a9e352015-07-08 13:10:52 +0530103 for d in self.get("items"):
104 if d.get(ref_link_field):
Deepesh Garg4c61ee32023-04-02 09:35:27 +0530105 ref_rate = reference_details.get(d.get(ref_link_field))
Anand Doshi414248b2015-08-26 17:56:40 +0530106
Ankush Menat494bd9e2022-03-28 18:52:46 +0530107 if abs(flt(d.rate - ref_rate, d.precision("rate"))) >= 0.01:
Deepesh Gargb7174202021-04-14 10:43:45 +0530108 if action == "Stop":
Deepesh Gargb7174202021-04-14 10:43:45 +0530109 if role_allowed_to_override not in frappe.get_roles():
Devin Slauenwhite3f6d8052023-11-23 12:12:12 -0500110 stop_actions.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530111 _("Row #{0}: Rate must be same as {1}: {2} ({3} / {4})").format(
112 d.idx, ref_dt, d.get(ref_dn_field), d.rate, ref_rate
113 )
114 )
Deepesh Gargb7174202021-04-14 10:43:45 +0530115 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530116 frappe.msgprint(
117 _("Row #{0}: Rate must be same as {1}: {2} ({3} / {4})").format(
118 d.idx, ref_dt, d.get(ref_dn_field), d.rate, ref_rate
119 ),
120 title=_("Warning"),
121 indicator="orange",
122 )
Devin Slauenwhite3f6d8052023-11-23 12:12:12 -0500123 if stop_actions:
124 frappe.throw(stop_actions, as_list=True)
Rushabh Mehta2c458992014-04-15 14:36:12 +0530125
Deepesh Garg4c61ee32023-04-02 09:35:27 +0530126 def get_reference_details(self, reference_names, reference_doctype):
127 return frappe._dict(
128 frappe.get_all(
129 reference_doctype,
130 filters={"name": ("in", reference_names)},
131 fields=["name", "rate"],
132 as_list=1,
133 )
134 )
135
Saurabh8f24ecb2016-06-16 18:01:58 +0530136 def get_link_filters(self, for_doctype):
Saurabhb6d6b842016-06-27 14:48:26 +0530137 if hasattr(self, "prev_link_mapper") and self.prev_link_mapper.get(for_doctype):
Saurabh8f24ecb2016-06-16 18:01:58 +0530138 fieldname = self.prev_link_mapper[for_doctype]["fieldname"]
Rushabh Mehta6b537922017-03-14 16:59:11 +0530139
Ankush Menat98917802021-06-11 18:40:22 +0530140 values = filter(None, tuple(item.as_dict()[fieldname] for item in self.items))
Saurabh8f24ecb2016-06-16 18:01:58 +0530141
142 if values:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530143 ret = {for_doctype: {"filters": [[for_doctype, "name", "in", values]]}}
Saurabh8f24ecb2016-06-16 18:01:58 +0530144 else:
145 ret = None
146 else:
147 ret = None
Rushabh Mehta6b537922017-03-14 16:59:11 +0530148
Saurabh8f24ecb2016-06-16 18:01:58 +0530149 return ret
Anand Doshif9fc04c2015-02-23 22:14:12 +0530150
Sagar Sharma6485ac42021-12-09 17:04:00 +0530151 def reset_default_field_value(self, default_field: str, child_table: str, child_table_field: str):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530152 """Reset "Set default X" fields on forms to avoid confusion.
Sagar Sharma6485ac42021-12-09 17:04:00 +0530153
Ankush Menat494bd9e2022-03-28 18:52:46 +0530154 example:
155 doc = {
156 "set_from_warehouse": "Warehouse A",
157 "items": [{"from_warehouse": "warehouse B"}, {"from_warehouse": "warehouse A"}],
158 }
159 Since this has dissimilar values in child table, the default field will be erased.
Sagar Sharma6485ac42021-12-09 17:04:00 +0530160
Ankush Menat494bd9e2022-03-28 18:52:46 +0530161 doc.reset_default_field_value("set_from_warehouse", "items", "from_warehouse")
162 """
Sagar Sharma6485ac42021-12-09 17:04:00 +0530163 child_table_values = set()
164
165 for row in self.get(child_table):
166 child_table_values.add(row.get(child_table_field))
167
168 if len(child_table_values) > 1:
169 self.set(default_field, None)
Sagar Sharma6485ac42021-12-09 17:04:00 +0530170
Ankush Menat494bd9e2022-03-28 18:52:46 +0530171
Anand Doshi11d31132013-06-17 12:51:36 +0530172def delete_events(ref_type, ref_name):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530173 events = (
174 frappe.db.sql_list(
175 """ SELECT
Rohit Waghchaure8f62aec2019-01-01 13:54:54 +0530176 distinct `tabEvent`.name
177 from
178 `tabEvent`, `tabEvent Participants`
179 where
180 `tabEvent`.name = `tabEvent Participants`.parent
181 and `tabEvent Participants`.reference_doctype = %s
182 and `tabEvent Participants`.reference_docname = %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530183 """,
184 (ref_type, ref_name),
185 )
186 or []
187 )
Rohit Waghchaure8f62aec2019-01-01 13:54:54 +0530188
189 if events:
190 frappe.delete_doc("Event", events, for_reload=True)
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530191
Ankush Menat494bd9e2022-03-28 18:52:46 +0530192
Nabin Haitc5fb88c2015-02-09 16:46:46 +0530193def validate_uom_is_integer(doc, uom_field, qty_fields, child_dt=None):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530194 if isinstance(qty_fields, str):
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530195 qty_fields = [qty_fields]
Rushabh Mehta2c458992014-04-15 14:36:12 +0530196
Ankush Menat98917802021-06-11 18:40:22 +0530197 distinct_uoms = list(set(d.get(uom_field) for d in doc.get_all_children()))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530198 integer_uoms = list(
199 filter(
200 lambda uom: frappe.db.get_value("UOM", uom, "must_be_whole_number", cache=True) or None,
201 distinct_uoms,
202 )
203 )
Rushabh Mehta2c458992014-04-15 14:36:12 +0530204
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530205 if not integer_uoms:
206 return
207
Nabin Haitc5fb88c2015-02-09 16:46:46 +0530208 for d in doc.get_all_children(parenttype=child_dt):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530209 if d.get(uom_field) in integer_uoms:
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530210 for f in qty_fields:
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530211 qty = d.get(f)
212 if qty:
s-aga-r9a290fd2024-04-17 21:45:27 +0530213 precision = d.precision(f)
214 if abs(cint(qty) - flt(qty, precision)) > 0.0000001:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530215 frappe.throw(
216 _(
217 "Row {1}: Quantity ({0}) cannot be a fraction. To allow this, disable '{2}' in UOM {3}."
218 ).format(
s-aga-r9a290fd2024-04-17 21:45:27 +0530219 flt(qty, precision),
s-aga-r6ec75902023-04-03 14:06:07 +0530220 d.idx,
221 frappe.bold(_("Must be Whole Number")),
222 frappe.bold(d.get(uom_field)),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530223 ),
224 UOMMustBeIntegerError,
225 )