brotherton-erpnext/erpnext/utilities/transaction_base.py

253 lines
7.7 KiB
Python
Raw Normal View History

# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
2012-02-23 07:05:32 +00:00
2014-02-14 10:17:51 +00:00
import frappe
import frappe.share
2014-02-21 09:14:35 +00:00
from frappe import _
from frappe.utils import cint, cstr, flt, get_time, now_datetime
from erpnext.controllers.status_updater import StatusUpdater
2018-02-15 06:09:45 +00:00
2022-03-28 13:22:46 +00:00
class UOMMustBeIntegerError(frappe.ValidationError):
pass
class TransactionBase(StatusUpdater):
2013-03-13 07:28:54 +00:00
def validate_posting_time(self):
# set Edit Posting Date and Time to 1 while data import
if frappe.flags.in_import and self.posting_date:
self.set_posting_time = 1
2022-03-28 13:22:46 +00:00
if not getattr(self, "set_posting_time", None):
now = now_datetime()
2022-03-28 13:22:46 +00:00
self.posting_date = now.strftime("%Y-%m-%d")
self.posting_time = now.strftime("%H:%M:%S.%f")
elif self.posting_time:
try:
get_time(self.posting_time)
except ValueError:
2022-03-28 13:22:46 +00:00
frappe.throw(_("Invalid Posting Time"))
2014-04-15 09:06:12 +00:00
def add_calendar_event(self, opts, force=False):
2022-03-28 13:22:46 +00:00
if (
cstr(self.contact_by) != cstr(self._prev.contact_by)
or cstr(self.contact_date) != cstr(self._prev.contact_date)
or force
or (hasattr(self, "ends_on") and cstr(self.ends_on) != cstr(self._prev.ends_on))
):
2014-04-15 09:06:12 +00:00
self.delete_events()
self._add_calendar_event(opts)
2014-04-15 09:06:12 +00:00
def delete_events(self):
2022-03-28 13:22:46 +00:00
participations = frappe.get_all(
"Event Participants",
filters={
"reference_doctype": self.doctype,
"reference_docname": self.name,
"parenttype": "Event",
},
fields=["name", "parent"],
)
if participations:
for participation in participations:
2022-03-28 13:22:46 +00:00
total_participants = frappe.get_all(
"Event Participants", filters={"parenttype": "Event", "parent": participation.parent}
)
if len(total_participants) <= 1:
frappe.db.sql("delete from `tabEvent` where name='%s'" % participation.parent)
frappe.db.sql("delete from `tabEvent Participants` where name='%s'" % participation.name)
def _add_calendar_event(self, opts):
2014-02-14 10:17:51 +00:00
opts = frappe._dict(opts)
2014-04-15 09:06:12 +00:00
if self.contact_date:
2022-03-28 13:22:46 +00:00
event = frappe.get_doc(
{
"doctype": "Event",
"owner": opts.owner or self.owner,
"subject": opts.subject,
"description": opts.description,
"starts_on": self.contact_date,
"ends_on": opts.ends_on,
"event_type": "Private",
}
)
2022-03-28 13:22:46 +00:00
event.append(
"event_participants", {"reference_doctype": self.doctype, "reference_docname": self.name}
)
2015-02-20 10:52:24 +00:00
event.insert(ignore_permissions=True)
2014-04-15 09:06:12 +00:00
if frappe.db.exists("User", self.contact_by):
2022-03-28 13:22:46 +00:00
frappe.share.add("Event", event.name, self.contact_by, flags={"ignore_share_permission": True})
2014-04-15 09:06:12 +00:00
def validate_uom_is_integer(self, uom_field, qty_fields):
2014-04-03 06:16:52 +00:00
validate_uom_is_integer(self, uom_field, qty_fields)
2014-04-15 09:06:12 +00:00
2014-12-26 07:45:21 +00:00
def validate_with_previous_doc(self, ref):
2022-03-28 13:22:46 +00:00
self.exclude_fields = ["conversion_factor", "uom"] if self.get("is_return") else []
2013-07-08 13:30:29 +00:00
for key, val in ref.items():
2013-07-10 10:03:29 +00:00
is_child = val.get("is_child_table")
2013-07-08 13:30:29 +00:00
ref_doc = {}
item_ref_dn = []
2014-12-26 07:45:21 +00:00
for d in self.get_all_children(self.doctype + " Item"):
ref_dn = d.get(val["ref_dn_field"])
2013-07-10 10:03:29 +00:00
if ref_dn:
if is_child:
self.compare_values({key: [ref_dn]}, val["compare_fields"], d)
if ref_dn not in item_ref_dn:
item_ref_dn.append(ref_dn)
elif not val.get("allow_duplicate_prev_row_id"):
2014-04-15 09:06:12 +00:00
frappe.throw(_("Duplicate row {0} with same {1}").format(d.idx, key))
elif ref_dn:
2013-07-10 10:03:29 +00:00
ref_doc.setdefault(key, [])
if ref_dn not in ref_doc[key]:
ref_doc[key].append(ref_dn)
if ref_doc:
2013-07-08 13:30:29 +00:00
self.compare_values(ref_doc, val["compare_fields"])
2014-04-15 09:06:12 +00:00
2013-07-08 13:30:29 +00:00
def compare_values(self, ref_doc, fields, doc=None):
2015-03-19 11:45:45 +00:00
for reference_doctype, ref_dn_list in ref_doc.items():
for reference_name in ref_dn_list:
2022-03-28 13:22:46 +00:00
prevdoc_values = frappe.db.get_value(
reference_doctype, reference_name, [d[0] for d in fields], as_dict=1
)
2013-07-10 10:03:29 +00:00
if not prevdoc_values:
frappe.throw(_("Invalid reference {0} {1}").format(reference_doctype, reference_name))
2013-07-10 10:03:29 +00:00
for field, condition in fields:
if prevdoc_values[field] is not None and field not in self.exclude_fields:
self.validate_value(field, condition, prevdoc_values[field], doc)
2015-08-26 12:26:40 +00:00
def validate_rate_with_reference_doc(self, ref_details):
buying_doctypes = ["Purchase Order", "Purchase Invoice", "Purchase Receipt"]
if self.doctype in buying_doctypes:
action = frappe.db.get_single_value("Buying Settings", "maintain_same_rate_action")
settings_doc = "Buying Settings"
else:
action = frappe.db.get_single_value("Selling Settings", "maintain_same_rate_action")
settings_doc = "Selling Settings"
for ref_dt, ref_dn_field, ref_link_field in ref_details:
for d in self.get("items"):
if d.get(ref_link_field):
ref_rate = frappe.db.get_value(ref_dt + " Item", d.get(ref_link_field), "rate")
2015-08-26 12:26:40 +00:00
2022-03-28 13:22:46 +00:00
if abs(flt(d.rate - ref_rate, d.precision("rate"))) >= 0.01:
if action == "Stop":
2022-03-28 13:22:46 +00:00
role_allowed_to_override = frappe.db.get_single_value(
settings_doc, "role_to_override_stop_action"
)
if role_allowed_to_override not in frappe.get_roles():
2022-03-28 13:22:46 +00:00
frappe.throw(
_("Row #{0}: Rate must be same as {1}: {2} ({3} / {4})").format(
d.idx, ref_dt, d.get(ref_dn_field), d.rate, ref_rate
)
)
else:
2022-03-28 13:22:46 +00:00
frappe.msgprint(
_("Row #{0}: Rate must be same as {1}: {2} ({3} / {4})").format(
d.idx, ref_dt, d.get(ref_dn_field), d.rate, ref_rate
),
title=_("Warning"),
indicator="orange",
)
2014-04-15 09:06:12 +00:00
def get_link_filters(self, for_doctype):
if hasattr(self, "prev_link_mapper") and self.prev_link_mapper.get(for_doctype):
fieldname = self.prev_link_mapper[for_doctype]["fieldname"]
values = filter(None, tuple(item.as_dict()[fieldname] for item in self.items))
if values:
2022-03-28 13:22:46 +00:00
ret = {for_doctype: {"filters": [[for_doctype, "name", "in", values]]}}
else:
ret = None
else:
ret = None
return ret
2015-02-23 16:44:12 +00:00
def reset_default_field_value(self, default_field: str, child_table: str, child_table_field: str):
2022-03-28 13:22:46 +00:00
"""Reset "Set default X" fields on forms to avoid confusion.
2022-03-28 13:22:46 +00:00
example:
doc = {
"set_from_warehouse": "Warehouse A",
"items": [{"from_warehouse": "warehouse B"}, {"from_warehouse": "warehouse A"}],
}
Since this has dissimilar values in child table, the default field will be erased.
2022-03-28 13:22:46 +00:00
doc.reset_default_field_value("set_from_warehouse", "items", "from_warehouse")
"""
child_table_values = set()
for row in self.get(child_table):
child_table_values.add(row.get(child_table_field))
if len(child_table_values) > 1:
self.set(default_field, None)
2022-03-28 13:22:46 +00:00
def delete_events(ref_type, ref_name):
2022-03-28 13:22:46 +00:00
events = (
frappe.db.sql_list(
""" SELECT
2019-01-01 08:24:54 +00:00
distinct `tabEvent`.name
from
`tabEvent`, `tabEvent Participants`
where
`tabEvent`.name = `tabEvent Participants`.parent
and `tabEvent Participants`.reference_doctype = %s
and `tabEvent Participants`.reference_docname = %s
2022-03-28 13:22:46 +00:00
""",
(ref_type, ref_name),
)
or []
)
2019-01-01 08:24:54 +00:00
if events:
frappe.delete_doc("Event", events, for_reload=True)
2022-03-28 13:22:46 +00:00
2015-02-09 11:16:46 +00:00
def validate_uom_is_integer(doc, uom_field, qty_fields, child_dt=None):
2021-11-04 14:18:32 +00:00
if isinstance(qty_fields, str):
qty_fields = [qty_fields]
2014-04-15 09:06:12 +00:00
distinct_uoms = list(set(d.get(uom_field) for d in doc.get_all_children()))
2022-03-28 13:22:46 +00:00
integer_uoms = list(
filter(
lambda uom: frappe.db.get_value("UOM", uom, "must_be_whole_number", cache=True) or None,
distinct_uoms,
)
)
2014-04-15 09:06:12 +00:00
if not integer_uoms:
return
2015-02-09 11:16:46 +00:00
for d in doc.get_all_children(parenttype=child_dt):
if d.get(uom_field) in integer_uoms:
for f in qty_fields:
qty = d.get(f)
if qty:
if abs(cint(qty) - flt(qty)) > 0.0000001:
2022-03-28 13:22:46 +00:00
frappe.throw(
_(
"Row {1}: Quantity ({0}) cannot be a fraction. To allow this, disable '{2}' in UOM {3}."
).format(
qty, d.idx, frappe.bold(_("Must be Whole Number")), frappe.bold(d.get(uom_field))
),
UOMMustBeIntegerError,
)