blob: 2359648c95cbd826e43ccf2ed9fa1b83812e53cc [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
Anand Doshi486f9df2012-07-19 13:40:31 +05304from __future__ import unicode_literals
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 _
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05308from frappe.utils import cstr, now_datetime, cint, flt, get_time, get_datetime, get_link_to_form
Rushabh Mehta1f847992013-12-12 19:12:19 +05309from erpnext.controllers.status_updater import StatusUpdater
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053010from erpnext.accounts.utils import get_fiscal_year
Anand Doshi756dca72013-01-15 18:39:21 +053011
Achilles Rasquinha1697a7a2018-02-15 11:39:45 +053012from six import string_types
13
Nabin Hait3cf67a42015-07-24 13:26:36 +053014class UOMMustBeIntegerError(frappe.ValidationError): pass
Rushabh Mehtab09d9da2014-01-02 11:47:23 +053015
Nabin Haitb5be7ba2014-01-30 18:47:12 +053016class TransactionBase(StatusUpdater):
Anand Doshiee3d5cc2013-03-13 12:58:54 +053017 def validate_posting_time(self):
Makarand Bauskarb0df6612017-05-16 07:59:58 +053018 # set Edit Posting Date and Time to 1 while data import
Sagar Vora67fe1012017-06-19 12:12:22 +053019 if frappe.flags.in_import and self.posting_date:
Makarand Bauskarb0df6612017-05-16 07:59:58 +053020 self.set_posting_time = 1
21
Rushabh Mehta131866a2017-03-14 21:06:15 +053022 if not getattr(self, 'set_posting_time', None):
Rushabh Mehta6b537922017-03-14 16:59:11 +053023 now = now_datetime()
24 self.posting_date = now.strftime('%Y-%m-%d')
Nabin Hait945f5022017-09-29 15:11:50 +053025 self.posting_time = now.strftime('%H:%M:%S.%f')
Manas Solankic6d56112018-01-18 11:20:24 +053026 elif self.posting_time:
Faris Ansari184491b2018-01-15 14:18:53 +053027 try:
28 get_time(self.posting_time)
29 except ValueError:
30 frappe.throw(_('Invalid Posting Time'))
Rushabh Mehta2c458992014-04-15 14:36:12 +053031
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053032 self.validate_with_last_transaction_posting_time()
33
Anand Doshi670199b2013-06-10 15:38:01 +053034 def add_calendar_event(self, opts, force=False):
Nabin Haite06d01e2015-06-29 18:38:27 +053035 if cstr(self.contact_by) != cstr(self._prev.contact_by) or \
Zarrar0702f292018-03-12 18:49:54 +053036 cstr(self.contact_date) != cstr(self._prev.contact_date) or force or \
37 (hasattr(self, "ends_on") and cstr(self.ends_on) != cstr(self._prev.ends_on)):
Rushabh Mehta2c458992014-04-15 14:36:12 +053038
Anand Doshie53a81d2013-06-10 15:15:40 +053039 self.delete_events()
40 self._add_calendar_event(opts)
Rushabh Mehta2c458992014-04-15 14:36:12 +053041
Anand Doshie53a81d2013-06-10 15:15:40 +053042 def delete_events(self):
Charles-Henri Decultot64b64212018-10-11 13:24:26 +020043 participations = frappe.get_all("Event Participants", filters={"reference_doctype": self.doctype, "reference_docname": self.name,
44 "parenttype": "Event"}, fields=["name", "parent"])
45
46 if participations:
47 for participation in participations:
48 total_participants = frappe.get_all("Event Participants", filters={"parenttype": "Event", "parent": participation.parent})
49
50 if len(total_participants) <= 1:
51 frappe.db.sql("delete from `tabEvent` where name='%s'" % participation.parent)
52
53 frappe.db.sql("delete from `tabEvent Participants` where name='%s'" % participation.name)
54
Anand Doshi414248b2015-08-26 17:56:40 +053055
Anand Doshie53a81d2013-06-10 15:15:40 +053056 def _add_calendar_event(self, opts):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053057 opts = frappe._dict(opts)
Rushabh Mehta2c458992014-04-15 14:36:12 +053058
Anand Doshif78d1ae2014-03-28 13:55:00 +053059 if self.contact_date:
Rushabh Mehta6efbc9d2015-02-13 10:16:41 +053060 event = frappe.get_doc({
Anand Doshie53a81d2013-06-10 15:15:40 +053061 "doctype": "Event",
Anand Doshif78d1ae2014-03-28 13:55:00 +053062 "owner": opts.owner or self.owner,
Anand Doshie53a81d2013-06-10 15:15:40 +053063 "subject": opts.subject,
64 "description": opts.description,
Anand Doshi414248b2015-08-26 17:56:40 +053065 "starts_on": self.contact_date,
Zarrar0702f292018-03-12 18:49:54 +053066 "ends_on": opts.ends_on,
Charles-Henri Decultot64b64212018-10-11 13:24:26 +020067 "event_type": "Private"
Rushabh Mehtae88bc8b2014-03-27 17:51:41 +053068 })
Anand Doshif9fc04c2015-02-23 22:14:12 +053069
Charles-Henri Decultot64b64212018-10-11 13:24:26 +020070 event.append('event_participants', {
71 "reference_doctype": self.doctype,
72 "reference_docname": self.name
73 }
74 )
75
Pratik Vyas7f9489e2015-02-20 16:22:24 +053076 event.insert(ignore_permissions=True)
Rushabh Mehta2c458992014-04-15 14:36:12 +053077
Anand Doshif78d1ae2014-03-28 13:55:00 +053078 if frappe.db.exists("User", self.contact_by):
Anand Doshi414248b2015-08-26 17:56:40 +053079 frappe.share.add("Event", event.name, self.contact_by,
Nabin Hait3b0adc52015-05-21 16:51:15 +053080 flags={"ignore_share_permission": True})
Rushabh Mehta2c458992014-04-15 14:36:12 +053081
Rushabh Mehta4dca4012013-07-25 17:45:59 +053082 def validate_uom_is_integer(self, uom_field, qty_fields):
Rushabh Mehtacfb6ccf2014-04-03 11:46:52 +053083 validate_uom_is_integer(self, uom_field, qty_fields)
Rushabh Mehta2c458992014-04-15 14:36:12 +053084
Nabin Haitdd38a262014-12-26 13:15:21 +053085 def validate_with_previous_doc(self, ref):
rohitwaghchaure0df95fa2018-03-01 11:31:33 +053086 self.exclude_fields = ["conversion_factor", "uom"] if self.get('is_return') else []
87
Nabin Hait2bd37772013-07-08 19:00:29 +053088 for key, val in ref.items():
Nabin Hait6e68e0e2013-07-10 15:33:29 +053089 is_child = val.get("is_child_table")
Nabin Hait2bd37772013-07-08 19:00:29 +053090 ref_doc = {}
Nabin Haita9ec49e2013-07-15 16:33:24 +053091 item_ref_dn = []
Nabin Haitdd38a262014-12-26 13:15:21 +053092 for d in self.get_all_children(self.doctype + " Item"):
Anand Doshif78d1ae2014-03-28 13:55:00 +053093 ref_dn = d.get(val["ref_dn_field"])
Nabin Hait6e68e0e2013-07-10 15:33:29 +053094 if ref_dn:
95 if is_child:
96 self.compare_values({key: [ref_dn]}, val["compare_fields"], d)
Nabin Haita9ec49e2013-07-15 16:33:24 +053097 if ref_dn not in item_ref_dn:
98 item_ref_dn.append(ref_dn)
Nabin Hait5e200e42013-07-29 15:29:51 +053099 elif not val.get("allow_duplicate_prev_row_id"):
Rushabh Mehta2c458992014-04-15 14:36:12 +0530100 frappe.throw(_("Duplicate row {0} with same {1}").format(d.idx, key))
Nabin Haita9ec49e2013-07-15 16:33:24 +0530101 elif ref_dn:
Nabin Hait6e68e0e2013-07-10 15:33:29 +0530102 ref_doc.setdefault(key, [])
103 if ref_dn not in ref_doc[key]:
104 ref_doc[key].append(ref_dn)
105 if ref_doc:
Nabin Hait2bd37772013-07-08 19:00:29 +0530106 self.compare_values(ref_doc, val["compare_fields"])
Rushabh Mehta2c458992014-04-15 14:36:12 +0530107
Nabin Hait2bd37772013-07-08 19:00:29 +0530108 def compare_values(self, ref_doc, fields, doc=None):
Rushabh Mehta611b5132015-03-19 17:15:45 +0530109 for reference_doctype, ref_dn_list in ref_doc.items():
110 for reference_name in ref_dn_list:
111 prevdoc_values = frappe.db.get_value(reference_doctype, reference_name,
Nabin Hait6e68e0e2013-07-10 15:33:29 +0530112 [d[0] for d in fields], as_dict=1)
113
Rushabh Mehtaafacc3d2015-12-01 15:53:07 +0530114 if not prevdoc_values:
115 frappe.throw(_("Invalid reference {0} {1}").format(reference_doctype, reference_name))
116
Nabin Hait6e68e0e2013-07-10 15:33:29 +0530117 for field, condition in fields:
rohitwaghchaure0df95fa2018-03-01 11:31:33 +0530118 if prevdoc_values[field] is not None and field not in self.exclude_fields:
Anand Doshi63d844b2013-07-10 20:55:15 +0530119 self.validate_value(field, condition, prevdoc_values[field], doc)
Anand Doshi414248b2015-08-26 17:56:40 +0530120
121
Nabin Hait28a9e352015-07-08 13:10:52 +0530122 def validate_rate_with_reference_doc(self, ref_details):
123 for ref_dt, ref_dn_field, ref_link_field in ref_details:
124 for d in self.get("items"):
125 if d.get(ref_link_field):
126 ref_rate = frappe.db.get_value(ref_dt + " Item", d.get(ref_link_field), "rate")
Anand Doshi414248b2015-08-26 17:56:40 +0530127
Nabin Hait28a9e352015-07-08 13:10:52 +0530128 if abs(flt(d.rate - ref_rate, d.precision("rate"))) >= .01:
Anupam K95e35f92020-03-24 11:52:34 +0530129 frappe.msgprint(_("Row #{0}: Rate must be same as {1}: {2} ({3} / {4}) ")
Nabin Hait28a9e352015-07-08 13:10:52 +0530130 .format(d.idx, ref_dt, d.get(ref_dn_field), d.rate, ref_rate))
Anupam K95e35f92020-03-24 11:52:34 +0530131 frappe.throw(_("To allow different rates, disable the {0} checkbox in {1}.")
Marica9ea1ad42020-04-21 12:52:29 +0530132 .format(frappe.bold(_("Maintain Same Rate Throughout Sales Cycle")),
Deepesh Garg9062ce52020-03-26 11:56:03 +0530133 get_link_to_form("Selling Settings", "Selling Settings", frappe.bold("Selling Settings"))))
Rushabh Mehta2c458992014-04-15 14:36:12 +0530134
Saurabh8f24ecb2016-06-16 18:01:58 +0530135 def get_link_filters(self, for_doctype):
Saurabhb6d6b842016-06-27 14:48:26 +0530136 if hasattr(self, "prev_link_mapper") and self.prev_link_mapper.get(for_doctype):
Saurabh8f24ecb2016-06-16 18:01:58 +0530137 fieldname = self.prev_link_mapper[for_doctype]["fieldname"]
Rushabh Mehta6b537922017-03-14 16:59:11 +0530138
Saurabh8f24ecb2016-06-16 18:01:58 +0530139 values = filter(None, tuple([item.as_dict()[fieldname] for item in self.items]))
140
141 if values:
142 ret = {
143 for_doctype : {
144 "filters": [[for_doctype, "name", "in", values]]
145 }
146 }
147 else:
148 ret = None
149 else:
150 ret = None
Rushabh Mehta6b537922017-03-14 16:59:11 +0530151
Saurabh8f24ecb2016-06-16 18:01:58 +0530152 return ret
Anand Doshif9fc04c2015-02-23 22:14:12 +0530153
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530154 def validate_with_last_transaction_posting_time(self):
155
156 if self.doctype not in ["Sales Invoice", "Purchase Invoice", "Stock Entry", "Stock Reconciliation",
157 "Delivery Note", "Purchase Receipt", "Fees"]:
158 return
159
160 if self.doctype in ["Sales Invoice", "Purchase Invoice"]:
161 if not (self.get("update_stock") or self.get("is_pos")):
162 return
163
Deepesh Garg5dc175f2020-06-22 19:05:39 +0530164 for item in self.get('items'):
165 last_transaction_time = frappe.db.sql("""
166 select MAX(timestamp(posting_date, posting_time)) as posting_time
167 from `tabStock Ledger Entry`
168 where docstatus = 1 and item_code = %s """, (item.item_code))[0][0]
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530169
Deepesh Garg5dc175f2020-06-22 19:05:39 +0530170 cur_doc_posting_datetime = "%s %s" % (self.posting_date, self.get("posting_time") or "00:00:00")
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530171
Deepesh Garg5dc175f2020-06-22 19:05:39 +0530172 if last_transaction_time and get_datetime(cur_doc_posting_datetime) < get_datetime(last_transaction_time):
173 msg = _("Last Stock Transaction for item {0} was on {1}.").format(frappe.bold(item.item_code), frappe.bold(last_transaction_time))
174 msg += "<br><br>" + _("Stock Transactions for Item {0} cannot be posted before this time.").format(frappe.bold(item.item_code))
175 msg += "<br><br>" + _("Please remove this item and try to submit again or update the posting time.")
176 frappe.throw(msg, title=_("Backdated Stock Entry"))
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530177
Anand Doshi11d31132013-06-17 12:51:36 +0530178def delete_events(ref_type, ref_name):
Rohit Waghchaure8f62aec2019-01-01 13:54:54 +0530179 events = frappe.db.sql_list(""" SELECT
180 distinct `tabEvent`.name
181 from
182 `tabEvent`, `tabEvent Participants`
183 where
184 `tabEvent`.name = `tabEvent Participants`.parent
185 and `tabEvent Participants`.reference_doctype = %s
186 and `tabEvent Participants`.reference_docname = %s
187 """, (ref_type, ref_name)) or []
188
189 if events:
190 frappe.delete_doc("Event", events, for_reload=True)
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530191
Nabin Haitc5fb88c2015-02-09 16:46:46 +0530192def validate_uom_is_integer(doc, uom_field, qty_fields, child_dt=None):
Achilles Rasquinha1697a7a2018-02-15 11:39:45 +0530193 if isinstance(qty_fields, string_types):
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530194 qty_fields = [qty_fields]
Rushabh Mehta2c458992014-04-15 14:36:12 +0530195
Rushabh Mehtaf191f852014-04-02 18:09:34 +0530196 distinct_uoms = list(set([d.get(uom_field) for d in doc.get_all_children()]))
Rohan7c8aaba2020-01-07 11:23:53 +0530197 integer_uoms = list(filter(lambda uom: frappe.db.get_value("UOM", uom,
198 "must_be_whole_number", cache=True) or None, distinct_uoms))
Rushabh Mehta2c458992014-04-15 14:36:12 +0530199
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530200 if not integer_uoms:
201 return
202
Nabin Haitc5fb88c2015-02-09 16:46:46 +0530203 for d in doc.get_all_children(parenttype=child_dt):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530204 if d.get(uom_field) in integer_uoms:
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530205 for f in qty_fields:
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530206 qty = d.get(f)
207 if qty:
Rushabh Mehtab7b49f62017-06-19 09:58:48 +0530208 if abs(cint(qty) - flt(qty)) > 0.0000001:
Marica9ea1ad42020-04-21 12:52:29 +0530209 frappe.throw(_("Row {1}: Quantity ({0}) cannot be a fraction. To allow this, disable '{2}' in UOM {3}.") \
210 .format(qty, d.idx, frappe.bold(_("Must be Whole Number")), frappe.bold(d.get(uom_field))),
211 UOMMustBeIntegerError)