diff --git a/erpnext/accounts/doctype/budget/budget.py b/erpnext/accounts/doctype/budget/budget.py index 39528da99db..45ec209e348 100644 --- a/erpnext/accounts/doctype/budget/budget.py +++ b/erpnext/accounts/doctype/budget/budget.py @@ -707,18 +707,20 @@ def get_ordered_amount(params): def get_other_condition(params, for_doc): - condition = f"expense_account = '{params.expense_account}'" + condition = f"expense_account = {frappe.db.escape(params.expense_account)}" budget_against_field = params.get("budget_against_field") if budget_against_field and params.get(budget_against_field): - condition += f" and child.{budget_against_field} = '{params.get(budget_against_field)}'" + condition += ( + f" and child.{budget_against_field} = {frappe.db.escape(params.get(budget_against_field))}" + ) date_field = "schedule_date" if for_doc == "Material Request" else "transaction_date" start_date = frappe.get_cached_value("Fiscal Year", params.from_fiscal_year, "year_start_date") end_date = frappe.get_cached_value("Fiscal Year", params.to_fiscal_year, "year_end_date") - condition += f" and parent.{date_field} between '{start_date}' and '{end_date}'" + condition += f" and parent.{date_field} between {frappe.db.escape(str(start_date))} and {frappe.db.escape(str(end_date))}" return condition diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.py b/erpnext/accounts/doctype/journal_entry/journal_entry.py index 7a30139796a..089da1fdb2c 100644 --- a/erpnext/accounts/doctype/journal_entry/journal_entry.py +++ b/erpnext/accounts/doctype/journal_entry/journal_entry.py @@ -1291,7 +1291,11 @@ class JournalEntry(AccountsController): self.validate_total_debit_and_credit() def get_values(self): - cond = f" and outstanding_amount <= {self.write_off_amount}" if flt(self.write_off_amount) > 0 else "" + cond = ( + f" and outstanding_amount <= {flt(self.write_off_amount)}" + if flt(self.write_off_amount) > 0 + else "" + ) if self.write_off_based_on == "Accounts Receivable": return frappe.db.sql( diff --git a/erpnext/accounts/report/inactive_sales_items/inactive_sales_items.py b/erpnext/accounts/report/inactive_sales_items/inactive_sales_items.py index df3fc48f9e1..a9b02ddf09a 100644 --- a/erpnext/accounts/report/inactive_sales_items/inactive_sales_items.py +++ b/erpnext/accounts/report/inactive_sales_items/inactive_sales_items.py @@ -94,6 +94,9 @@ def get_data(filters): def get_sales_details(filters): item_details_map = {} + if filters["based_on"] not in ("Sales Order", "Sales Invoice"): + frappe.throw(_("Invalid value {0} for 'Based On'").format(filters["based_on"])) + date_field = "s.transaction_date" if filters["based_on"] == "Sales Order" else "s.posting_date" sales_data = frappe.db.sql( diff --git a/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.py b/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.py index 2733d07a476..fbe9d7fcf7d 100644 --- a/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.py +++ b/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.py @@ -31,7 +31,8 @@ class BulkTransactionLog(Document): log_detail = qb.DocType("Bulk Transaction Log Detail") has_records = frappe.db.sql( - f"select exists (select * from `tabBulk Transaction Log Detail` where date = '{self.name}');" + "select exists (select * from `tabBulk Transaction Log Detail` where date = %s);", + (self.name,), )[0][0] if not has_records: raise frappe.DoesNotExistError diff --git a/erpnext/controllers/status_updater.py b/erpnext/controllers/status_updater.py index 06cc57d6287..1b0ee5cf6b7 100644 --- a/erpnext/controllers/status_updater.py +++ b/erpnext/controllers/status_updater.py @@ -524,9 +524,9 @@ class StatusUpdater(Document): for args in self.status_updater: # condition to include current record (if submit or no if cancel) if self.docstatus == 1: - args["cond"] = " or parent='%s'" % self.name.replace('"', '"') + args["cond"] = " or parent=%s" % frappe.db.escape(self.name) else: - args["cond"] = " and parent!='%s'" % self.name.replace('"', '"') + args["cond"] = " and parent!=%s" % frappe.db.escape(self.name) self._update_children(args, update_modified) @@ -556,9 +556,10 @@ class StatusUpdater(Document): args["second_source_condition"] = frappe.db.sql( """ select ifnull((select sum({second_source_field}) from `tab{second_source_dt}` - where `{second_join_field}`='{detail_id}' + where `{second_join_field}`=%(detail_id)s and (`tab{second_source_dt}`.docstatus=1) - {second_source_extra_cond}), 0) """.format(**args) + {second_source_extra_cond}), 0) """.format(**args), + {"detail_id": args["detail_id"]}, )[0][0] if args["detail_id"]: @@ -569,9 +570,10 @@ class StatusUpdater(Document): frappe.db.sql( """ (select ifnull(sum({source_field}), 0) - from `tab{source_dt}` where `{join_field}`='{detail_id}' + from `tab{source_dt}` where `{join_field}`=%(detail_id)s and (docstatus=1 {cond}) {extra_cond}) - """.format(**args) + """.format(**args), + {"detail_id": args["detail_id"]}, )[0][0] or 0.0 ) @@ -582,7 +584,8 @@ class StatusUpdater(Document): frappe.db.sql( """update `tab{target_dt}` set {target_field} = {source_dt_value} {update_modified} - where name='{detail_id}'""".format(**args) + where name=%(detail_id)s""".format(**args), + {"detail_id": args["detail_id"]}, ) @staticmethod diff --git a/erpnext/controllers/website_list_for_contact.py b/erpnext/controllers/website_list_for_contact.py index 86da88f0072..8d8c0d19878 100644 --- a/erpnext/controllers/website_list_for_contact.py +++ b/erpnext/controllers/website_list_for_contact.py @@ -7,7 +7,7 @@ import json import frappe from frappe import _ from frappe.modules.utils import get_module_app -from frappe.utils import flt, has_common +from frappe.utils import cint, flt, has_common from frappe.utils.user import is_website_user @@ -179,10 +179,13 @@ def get_list_for_transactions( def rfq_transaction_list(parties_doctype, doctype, parties, limit_start, limit_page_length): data = frappe.db.sql( - """select distinct parent as name, supplier from `tab{doctype}` - where supplier = '{supplier}' and docstatus=1 order by creation desc limit {start}, {len}""".format( - doctype=parties_doctype, supplier=parties[0], start=limit_start, len=limit_page_length - ), + f"""select distinct parent as name, supplier from `tab{parties_doctype}` + where supplier = %(supplier)s and docstatus=1 order by creation desc limit %(start)s, %(len)s""", + { + "supplier": parties[0], + "start": cint(limit_start), + "len": cint(limit_page_length), + }, as_dict=1, ) diff --git a/erpnext/selling/report/inactive_customers/inactive_customers.py b/erpnext/selling/report/inactive_customers/inactive_customers.py index 7e4ddc128ac..d21d11b2447 100644 --- a/erpnext/selling/report/inactive_customers/inactive_customers.py +++ b/erpnext/selling/report/inactive_customers/inactive_customers.py @@ -14,6 +14,9 @@ def execute(filters=None): days_since_last_order = filters.get("days_since_last_order") doctype = filters.get("doctype") + if doctype not in ("Sales Order", "Sales Invoice"): + frappe.throw(_("Invalid value {0} for 'Doctype'").format(doctype)) + if cint(days_since_last_order) <= 0: frappe.throw(_("'Days Since Last Order' must be greater than or equal to zero")) diff --git a/erpnext/selling/report/sales_analytics/sales_analytics.py b/erpnext/selling/report/sales_analytics/sales_analytics.py index 2aac07ce3b5..e36690b4384 100644 --- a/erpnext/selling/report/sales_analytics/sales_analytics.py +++ b/erpnext/selling/report/sales_analytics/sales_analytics.py @@ -497,14 +497,16 @@ class Analytics: break def get_groups(self): - if self.filters.tree_type == "Territory": - parent = "parent_territory" - if self.filters.tree_type == "Customer Group": - parent = "parent_customer_group" - if self.filters.tree_type == "Item Group": - parent = "parent_item_group" - if self.filters.tree_type == "Supplier Group": - parent = "parent_supplier_group" + parent_field_map = { + "Territory": "parent_territory", + "Customer Group": "parent_customer_group", + "Item Group": "parent_item_group", + "Supplier Group": "parent_supplier_group", + } + if self.filters.tree_type not in parent_field_map: + frappe.throw(_("Invalid Tree Type {0}").format(self.filters.tree_type)) + + parent = parent_field_map[self.filters.tree_type] self.depth_map = frappe._dict() @@ -523,6 +525,9 @@ class Analytics: def get_teams(self): self.depth_map = frappe._dict() + if not frappe.db.exists("DocType", self.filters.doc_type): + frappe.throw(_("Invalid Document Type {0}").format(self.filters.doc_type)) + self.group_entries = frappe.db.sql( f""" select * from (select "Order Types" as name, 0 as lft, 2 as rgt, '' as parent union select distinct order_type as name, 1 as lft, 1 as rgt, "Order Types" as parent diff --git a/erpnext/setup/doctype/authorization_control/authorization_control.py b/erpnext/setup/doctype/authorization_control/authorization_control.py index ef703de698f..98bc2aa7d9f 100644 --- a/erpnext/setup/doctype/authorization_control/authorization_control.py +++ b/erpnext/setup/doctype/authorization_control/authorization_control.py @@ -120,7 +120,9 @@ class AuthorizationControl(TransactionBase): if val == 1: add_cond += " and system_user = {}".format(frappe.db.escape(session["user"])) elif val == 2: - add_cond += " and system_role IN %s" % ("('" + "','".join(frappe.get_roles()) + "')") + add_cond += " and system_role IN (%s)" % ", ".join( + frappe.db.escape(r) for r in frappe.get_roles() + ) else: add_cond += " and ifnull(system_user,'') = '' and ifnull(system_role,'') = ''" @@ -206,8 +208,8 @@ class AuthorizationControl(TransactionBase): and docstatus != 2 """.format( "%s", - "'" + "','".join(frappe.get_roles()) + "'", - "'" + "','".join(final_based_on) + "'", + ", ".join(frappe.db.escape(r) for r in frappe.get_roles()), + ", ".join(frappe.db.escape(b) for b in final_based_on), "%s", ), (doctype_name, company), diff --git a/erpnext/stock/doctype/material_request/material_request.py b/erpnext/stock/doctype/material_request/material_request.py index 24e8ac4b1a9..f9cd772bb14 100644 --- a/erpnext/stock/doctype/material_request/material_request.py +++ b/erpnext/stock/doctype/material_request/material_request.py @@ -249,7 +249,7 @@ class MaterialRequest(BuyingController): def check_modified_date(self): mod_db = frappe.db.sql("""select modified from `tabMaterial Request` where name = %s""", self.name) - date_diff = frappe.db.sql(f"""select TIMEDIFF('{mod_db[0][0]}', '{cstr(self.modified)}')""") + date_diff = frappe.db.sql("""select TIMEDIFF(%s, %s)""", (mod_db[0][0], cstr(self.modified))) if date_diff and date_diff[0][0]: frappe.throw(_("{0} {1} has been modified. Please refresh.").format(_(self.doctype), self.name)) diff --git a/erpnext/stock/stock_balance.py b/erpnext/stock/stock_balance.py index 7f6deda9b8c..f6c3c05c6c3 100644 --- a/erpnext/stock/stock_balance.py +++ b/erpnext/stock/stock_balance.py @@ -284,7 +284,7 @@ def set_stock_balance_as_per_serial_no( if not posting_time: posting_time = nowtime() - condition = " and item.name='%s'" % item_code.replace("'", "'") if item_code else "" + condition = " and item.name=%s" % frappe.db.escape(item_code, percent=False) if item_code else "" bin = frappe.db.sql( """select bin.item_code, bin.warehouse, bin.actual_qty, item.stock_uom