blob: 1d8b3a8db67a4b4063a4dfa9ef862950076c5286 [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 _
Chillar Anand915b3432021-09-02 16:44:59 +05308from frappe.utils import cint, cstr, 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
Nabin Hait3cf67a42015-07-24 13:26:36 +053013class UOMMustBeIntegerError(frappe.ValidationError): pass
Rushabh Mehtab09d9da2014-01-02 11:47:23 +053014
Nabin Haitb5be7ba2014-01-30 18:47:12 +053015class TransactionBase(StatusUpdater):
Anand Doshiee3d5cc2013-03-13 12:58:54 +053016 def validate_posting_time(self):
Makarand Bauskarb0df6612017-05-16 07:59:58 +053017 # set Edit Posting Date and Time to 1 while data import
Sagar Vora67fe1012017-06-19 12:12:22 +053018 if frappe.flags.in_import and self.posting_date:
Makarand Bauskarb0df6612017-05-16 07:59:58 +053019 self.set_posting_time = 1
20
Rushabh Mehta131866a2017-03-14 21:06:15 +053021 if not getattr(self, 'set_posting_time', None):
Rushabh Mehta6b537922017-03-14 16:59:11 +053022 now = now_datetime()
23 self.posting_date = now.strftime('%Y-%m-%d')
Nabin Hait945f5022017-09-29 15:11:50 +053024 self.posting_time = now.strftime('%H:%M:%S.%f')
Manas Solankic6d56112018-01-18 11:20:24 +053025 elif self.posting_time:
Faris Ansari184491b2018-01-15 14:18:53 +053026 try:
27 get_time(self.posting_time)
28 except ValueError:
29 frappe.throw(_('Invalid Posting Time'))
Rushabh Mehta2c458992014-04-15 14:36:12 +053030
Anand Doshi670199b2013-06-10 15:38:01 +053031 def add_calendar_event(self, opts, force=False):
Nabin Haite06d01e2015-06-29 18:38:27 +053032 if cstr(self.contact_by) != cstr(self._prev.contact_by) or \
Zarrar0702f292018-03-12 18:49:54 +053033 cstr(self.contact_date) != cstr(self._prev.contact_date) or force or \
34 (hasattr(self, "ends_on") and cstr(self.ends_on) != cstr(self._prev.ends_on)):
Rushabh Mehta2c458992014-04-15 14:36:12 +053035
Anand Doshie53a81d2013-06-10 15:15:40 +053036 self.delete_events()
37 self._add_calendar_event(opts)
Rushabh Mehta2c458992014-04-15 14:36:12 +053038
Anand Doshie53a81d2013-06-10 15:15:40 +053039 def delete_events(self):
Charles-Henri Decultot64b64212018-10-11 13:24:26 +020040 participations = frappe.get_all("Event Participants", filters={"reference_doctype": self.doctype, "reference_docname": self.name,
41 "parenttype": "Event"}, fields=["name", "parent"])
42
43 if participations:
44 for participation in participations:
45 total_participants = frappe.get_all("Event Participants", filters={"parenttype": "Event", "parent": participation.parent})
46
47 if len(total_participants) <= 1:
48 frappe.db.sql("delete from `tabEvent` where name='%s'" % participation.parent)
49
50 frappe.db.sql("delete from `tabEvent Participants` where name='%s'" % participation.name)
51
Anand Doshi414248b2015-08-26 17:56:40 +053052
Anand Doshie53a81d2013-06-10 15:15:40 +053053 def _add_calendar_event(self, opts):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053054 opts = frappe._dict(opts)
Rushabh Mehta2c458992014-04-15 14:36:12 +053055
Anand Doshif78d1ae2014-03-28 13:55:00 +053056 if self.contact_date:
Rushabh Mehta6efbc9d2015-02-13 10:16:41 +053057 event = frappe.get_doc({
Anand Doshie53a81d2013-06-10 15:15:40 +053058 "doctype": "Event",
Anand Doshif78d1ae2014-03-28 13:55:00 +053059 "owner": opts.owner or self.owner,
Anand Doshie53a81d2013-06-10 15:15:40 +053060 "subject": opts.subject,
61 "description": opts.description,
Anand Doshi414248b2015-08-26 17:56:40 +053062 "starts_on": self.contact_date,
Zarrar0702f292018-03-12 18:49:54 +053063 "ends_on": opts.ends_on,
Charles-Henri Decultot64b64212018-10-11 13:24:26 +020064 "event_type": "Private"
Rushabh Mehtae88bc8b2014-03-27 17:51:41 +053065 })
Anand Doshif9fc04c2015-02-23 22:14:12 +053066
Charles-Henri Decultot64b64212018-10-11 13:24:26 +020067 event.append('event_participants', {
68 "reference_doctype": self.doctype,
69 "reference_docname": self.name
70 }
71 )
72
Pratik Vyas7f9489e2015-02-20 16:22:24 +053073 event.insert(ignore_permissions=True)
Rushabh Mehta2c458992014-04-15 14:36:12 +053074
Anand Doshif78d1ae2014-03-28 13:55:00 +053075 if frappe.db.exists("User", self.contact_by):
Anand Doshi414248b2015-08-26 17:56:40 +053076 frappe.share.add("Event", event.name, self.contact_by,
Nabin Hait3b0adc52015-05-21 16:51:15 +053077 flags={"ignore_share_permission": True})
Rushabh Mehta2c458992014-04-15 14:36:12 +053078
Rushabh Mehta4dca4012013-07-25 17:45:59 +053079 def validate_uom_is_integer(self, uom_field, qty_fields):
Rushabh Mehtacfb6ccf2014-04-03 11:46:52 +053080 validate_uom_is_integer(self, uom_field, qty_fields)
Rushabh Mehta2c458992014-04-15 14:36:12 +053081
Nabin Haitdd38a262014-12-26 13:15:21 +053082 def validate_with_previous_doc(self, ref):
rohitwaghchaure0df95fa2018-03-01 11:31:33 +053083 self.exclude_fields = ["conversion_factor", "uom"] if self.get('is_return') else []
84
Nabin Hait2bd37772013-07-08 19:00:29 +053085 for key, val in ref.items():
Nabin Hait6e68e0e2013-07-10 15:33:29 +053086 is_child = val.get("is_child_table")
Nabin Hait2bd37772013-07-08 19:00:29 +053087 ref_doc = {}
Nabin Haita9ec49e2013-07-15 16:33:24 +053088 item_ref_dn = []
Nabin Haitdd38a262014-12-26 13:15:21 +053089 for d in self.get_all_children(self.doctype + " Item"):
Anand Doshif78d1ae2014-03-28 13:55:00 +053090 ref_dn = d.get(val["ref_dn_field"])
Nabin Hait6e68e0e2013-07-10 15:33:29 +053091 if ref_dn:
92 if is_child:
93 self.compare_values({key: [ref_dn]}, val["compare_fields"], d)
Nabin Haita9ec49e2013-07-15 16:33:24 +053094 if ref_dn not in item_ref_dn:
95 item_ref_dn.append(ref_dn)
Nabin Hait5e200e42013-07-29 15:29:51 +053096 elif not val.get("allow_duplicate_prev_row_id"):
Rushabh Mehta2c458992014-04-15 14:36:12 +053097 frappe.throw(_("Duplicate row {0} with same {1}").format(d.idx, key))
Nabin Haita9ec49e2013-07-15 16:33:24 +053098 elif ref_dn:
Nabin Hait6e68e0e2013-07-10 15:33:29 +053099 ref_doc.setdefault(key, [])
100 if ref_dn not in ref_doc[key]:
101 ref_doc[key].append(ref_dn)
102 if ref_doc:
Nabin Hait2bd37772013-07-08 19:00:29 +0530103 self.compare_values(ref_doc, val["compare_fields"])
Rushabh Mehta2c458992014-04-15 14:36:12 +0530104
Nabin Hait2bd37772013-07-08 19:00:29 +0530105 def compare_values(self, ref_doc, fields, doc=None):
Rushabh Mehta611b5132015-03-19 17:15:45 +0530106 for reference_doctype, ref_dn_list in ref_doc.items():
107 for reference_name in ref_dn_list:
108 prevdoc_values = frappe.db.get_value(reference_doctype, reference_name,
Nabin Hait6e68e0e2013-07-10 15:33:29 +0530109 [d[0] for d in fields], as_dict=1)
110
Rushabh Mehtaafacc3d2015-12-01 15:53:07 +0530111 if not prevdoc_values:
112 frappe.throw(_("Invalid reference {0} {1}").format(reference_doctype, reference_name))
113
Nabin Hait6e68e0e2013-07-10 15:33:29 +0530114 for field, condition in fields:
rohitwaghchaure0df95fa2018-03-01 11:31:33 +0530115 if prevdoc_values[field] is not None and field not in self.exclude_fields:
Anand Doshi63d844b2013-07-10 20:55:15 +0530116 self.validate_value(field, condition, prevdoc_values[field], doc)
Anand Doshi414248b2015-08-26 17:56:40 +0530117
118
Nabin Hait28a9e352015-07-08 13:10:52 +0530119 def validate_rate_with_reference_doc(self, ref_details):
Marica5f299a02020-07-06 18:26:56 +0530120 buying_doctypes = ["Purchase Order", "Purchase Invoice", "Purchase Receipt"]
Marica5f299a02020-07-06 18:26:56 +0530121
122 if self.doctype in buying_doctypes:
Deepesh Gargb7174202021-04-14 10:43:45 +0530123 action = frappe.db.get_single_value("Buying Settings", "maintain_same_rate_action")
124 settings_doc = "Buying Settings"
Marica5f299a02020-07-06 18:26:56 +0530125 else:
Deepesh Gargb7174202021-04-14 10:43:45 +0530126 action = frappe.db.get_single_value("Selling Settings", "maintain_same_rate_action")
127 settings_doc = "Selling Settings"
Marica5f299a02020-07-06 18:26:56 +0530128
Nabin Hait28a9e352015-07-08 13:10:52 +0530129 for ref_dt, ref_dn_field, ref_link_field in ref_details:
130 for d in self.get("items"):
131 if d.get(ref_link_field):
132 ref_rate = frappe.db.get_value(ref_dt + " Item", d.get(ref_link_field), "rate")
Anand Doshi414248b2015-08-26 17:56:40 +0530133
Nabin Hait28a9e352015-07-08 13:10:52 +0530134 if abs(flt(d.rate - ref_rate, d.precision("rate"))) >= .01:
Deepesh Gargb7174202021-04-14 10:43:45 +0530135 if action == "Stop":
136 role_allowed_to_override = frappe.db.get_single_value(settings_doc, 'role_to_override_stop_action')
137
138 if role_allowed_to_override not in frappe.get_roles():
139 frappe.throw(_("Row #{0}: Rate must be same as {1}: {2} ({3} / {4})").format(
140 d.idx, ref_dt, d.get(ref_dn_field), d.rate, ref_rate))
141 else:
142 frappe.msgprint(_("Row #{0}: Rate must be same as {1}: {2} ({3} / {4})").format(
143 d.idx, ref_dt, d.get(ref_dn_field), d.rate, ref_rate), title=_("Warning"), indicator="orange")
144
Rushabh Mehta2c458992014-04-15 14:36:12 +0530145
Saurabh8f24ecb2016-06-16 18:01:58 +0530146 def get_link_filters(self, for_doctype):
Saurabhb6d6b842016-06-27 14:48:26 +0530147 if hasattr(self, "prev_link_mapper") and self.prev_link_mapper.get(for_doctype):
Saurabh8f24ecb2016-06-16 18:01:58 +0530148 fieldname = self.prev_link_mapper[for_doctype]["fieldname"]
Rushabh Mehta6b537922017-03-14 16:59:11 +0530149
Ankush Menat98917802021-06-11 18:40:22 +0530150 values = filter(None, tuple(item.as_dict()[fieldname] for item in self.items))
Saurabh8f24ecb2016-06-16 18:01:58 +0530151
152 if values:
153 ret = {
154 for_doctype : {
155 "filters": [[for_doctype, "name", "in", values]]
156 }
157 }
158 else:
159 ret = None
160 else:
161 ret = None
Rushabh Mehta6b537922017-03-14 16:59:11 +0530162
Saurabh8f24ecb2016-06-16 18:01:58 +0530163 return ret
Anand Doshif9fc04c2015-02-23 22:14:12 +0530164
Sagar Sharma6485ac42021-12-09 17:04:00 +0530165 def reset_default_field_value(self, default_field: str, child_table: str, child_table_field: str):
166 """ Reset "Set default X" fields on forms to avoid confusion.
167
168 example:
169 doc = {
170 "set_from_warehouse": "Warehouse A",
171 "items": [{"from_warehouse": "warehouse B"}, {"from_warehouse": "warehouse A"}],
172 }
173 Since this has dissimilar values in child table, the default field will be erased.
174
175 doc.reset_default_field_value("set_from_warehouse", "items", "from_warehouse")
176 """
177 child_table_values = set()
178
179 for row in self.get(child_table):
180 child_table_values.add(row.get(child_table_field))
181
182 if len(child_table_values) > 1:
183 self.set(default_field, None)
184 else:
185 self.set(default_field, list(child_table_values)[0])
186
Anand Doshi11d31132013-06-17 12:51:36 +0530187def delete_events(ref_type, ref_name):
Rohit Waghchaure8f62aec2019-01-01 13:54:54 +0530188 events = frappe.db.sql_list(""" SELECT
189 distinct `tabEvent`.name
190 from
191 `tabEvent`, `tabEvent Participants`
192 where
193 `tabEvent`.name = `tabEvent Participants`.parent
194 and `tabEvent Participants`.reference_doctype = %s
195 and `tabEvent Participants`.reference_docname = %s
196 """, (ref_type, ref_name)) or []
197
198 if events:
199 frappe.delete_doc("Event", events, for_reload=True)
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530200
Nabin Haitc5fb88c2015-02-09 16:46:46 +0530201def validate_uom_is_integer(doc, uom_field, qty_fields, child_dt=None):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530202 if isinstance(qty_fields, str):
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530203 qty_fields = [qty_fields]
Rushabh Mehta2c458992014-04-15 14:36:12 +0530204
Ankush Menat98917802021-06-11 18:40:22 +0530205 distinct_uoms = list(set(d.get(uom_field) for d in doc.get_all_children()))
Rohan7c8aaba2020-01-07 11:23:53 +0530206 integer_uoms = list(filter(lambda uom: frappe.db.get_value("UOM", uom,
207 "must_be_whole_number", cache=True) or None, distinct_uoms))
Rushabh Mehta2c458992014-04-15 14:36:12 +0530208
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530209 if not integer_uoms:
210 return
211
Nabin Haitc5fb88c2015-02-09 16:46:46 +0530212 for d in doc.get_all_children(parenttype=child_dt):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530213 if d.get(uom_field) in integer_uoms:
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530214 for f in qty_fields:
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530215 qty = d.get(f)
216 if qty:
Rushabh Mehtab7b49f62017-06-19 09:58:48 +0530217 if abs(cint(qty) - flt(qty)) > 0.0000001:
Marica9ea1ad42020-04-21 12:52:29 +0530218 frappe.throw(_("Row {1}: Quantity ({0}) cannot be a fraction. To allow this, disable '{2}' in UOM {3}.") \
219 .format(qty, d.idx, frappe.bold(_("Must be Whole Number")), frappe.bold(d.get(uom_field))),
220 UOMMustBeIntegerError)