diff --git a/erpnext/__init__.py b/erpnext/__init__.py index 497416b12ab..2940c9f4c0e 100644 --- a/erpnext/__init__.py +++ b/erpnext/__init__.py @@ -36,10 +36,8 @@ def get_default_cost_center(company): if not frappe.flags.company_cost_center: frappe.flags.company_cost_center = {} - if not company in frappe.flags.company_cost_center: - frappe.flags.company_cost_center[company] = frappe.get_cached_value( - "Company", company, "cost_center" - ) + if company not in frappe.flags.company_cost_center: + frappe.flags.company_cost_center[company] = frappe.get_cached_value("Company", company, "cost_center") return frappe.flags.company_cost_center[company] @@ -47,7 +45,7 @@ def get_company_currency(company): """Returns the default company currency""" if not frappe.flags.company_currency: frappe.flags.company_currency = {} - if not company in frappe.flags.company_currency: + if company not in frappe.flags.company_currency: frappe.flags.company_currency[company] = frappe.db.get_value( "Company", company, "default_currency", cache=True ) @@ -81,7 +79,7 @@ def is_perpetual_inventory_enabled(company): if not hasattr(frappe.local, "enable_perpetual_inventory"): frappe.local.enable_perpetual_inventory = {} - if not company in frappe.local.enable_perpetual_inventory: + if company not in frappe.local.enable_perpetual_inventory: frappe.local.enable_perpetual_inventory[company] = ( frappe.get_cached_value("Company", company, "enable_perpetual_inventory") or 0 ) @@ -96,7 +94,7 @@ def get_default_finance_book(company=None): if not hasattr(frappe.local, "default_finance_book"): frappe.local.default_finance_book = {} - if not company in frappe.local.default_finance_book: + if company not in frappe.local.default_finance_book: frappe.local.default_finance_book[company] = frappe.get_cached_value( "Company", company, "default_finance_book" ) @@ -108,7 +106,7 @@ def get_party_account_type(party_type): if not hasattr(frappe.local, "party_account_types"): frappe.local.party_account_types = {} - if not party_type in frappe.local.party_account_types: + if party_type not in frappe.local.party_account_types: frappe.local.party_account_types[party_type] = ( frappe.db.get_value("Party Type", party_type, "account_type") or "" ) diff --git a/erpnext/accounts/custom/address.py b/erpnext/accounts/custom/address.py index 775a81fd25f..ef57a632506 100644 --- a/erpnext/accounts/custom/address.py +++ b/erpnext/accounts/custom/address.py @@ -11,14 +11,14 @@ class ERPNextAddress(Address): def validate(self): self.validate_reference() self.update_compnay_address() - super(ERPNextAddress, self).validate() + super().validate() def link_address(self): """Link address based on owner""" if self.is_your_company_address: return - return super(ERPNextAddress, self).link_address() + return super().link_address() def update_compnay_address(self): for link in self.get("links"): @@ -26,11 +26,11 @@ class ERPNextAddress(Address): self.is_your_company_address = 1 def validate_reference(self): - if self.is_your_company_address and not [ - row for row in self.links if row.link_doctype == "Company" - ]: + if self.is_your_company_address and not [row for row in self.links if row.link_doctype == "Company"]: frappe.throw( - _("Address needs to be linked to a Company. Please add a row for Company in the Links table."), + _( + "Address needs to be linked to a Company. Please add a row for Company in the Links table." + ), title=_("Company Not Linked"), ) diff --git a/erpnext/accounts/dashboard_chart_source/account_balance_timeline/account_balance_timeline.py b/erpnext/accounts/dashboard_chart_source/account_balance_timeline/account_balance_timeline.py index fefec0ee7b4..7e06c5b8c83 100644 --- a/erpnext/accounts/dashboard_chart_source/account_balance_timeline/account_balance_timeline.py +++ b/erpnext/accounts/dashboard_chart_source/account_balance_timeline/account_balance_timeline.py @@ -37,7 +37,7 @@ def get( filters = frappe.parse_json(filters) or frappe.parse_json(chart.filters_json) account = filters.get("account") - company = filters.get("company") + filters.get("company") if not account and chart_name: frappe.throw( @@ -83,7 +83,6 @@ def build_result(account, dates, gl_entries): # get balances in debit for entry in gl_entries: - # entry date is after the current pointer, so move the pointer forward while getdate(entry.posting_date) > result[date_index][0]: date_index += 1 @@ -133,8 +132,6 @@ def get_dates_from_timegrain(from_date, to_date, timegrain): dates = [get_period_ending(from_date, timegrain)] while getdate(dates[-1]) < getdate(to_date): - date = get_period_ending( - add_to_date(dates[-1], years=years, months=months, days=days), timegrain - ) + date = get_period_ending(add_to_date(dates[-1], years=years, months=months, days=days), timegrain) dates.append(date) return dates diff --git a/erpnext/accounts/deferred_revenue.py b/erpnext/accounts/deferred_revenue.py index d0940c7df21..9ffdf186f02 100644 --- a/erpnext/accounts/deferred_revenue.py +++ b/erpnext/accounts/deferred_revenue.py @@ -24,14 +24,10 @@ from erpnext.accounts.utils import get_account_currency def validate_service_stop_date(doc): """Validates service_stop_date for Purchase Invoice and Sales Invoice""" - enable_check = ( - "enable_deferred_revenue" if doc.doctype == "Sales Invoice" else "enable_deferred_expense" - ) + enable_check = "enable_deferred_revenue" if doc.doctype == "Sales Invoice" else "enable_deferred_expense" old_stop_dates = {} - old_doc = frappe.db.get_all( - "{0} Item".format(doc.doctype), {"parent": doc.name}, ["name", "service_stop_date"] - ) + old_doc = frappe.db.get_all(f"{doc.doctype} Item", {"parent": doc.name}, ["name", "service_stop_date"]) for d in old_doc: old_stop_dates[d.name] = d.service_stop_date or "" @@ -62,16 +58,14 @@ def build_conditions(process_type, account, company): ) if account: - conditions += "AND %s='%s'" % (deferred_account, account) + conditions += f"AND {deferred_account}='{account}'" elif company: conditions += f"AND p.company = {frappe.db.escape(company)}" return conditions -def convert_deferred_expense_to_expense( - deferred_process, start_date=None, end_date=None, conditions="" -): +def convert_deferred_expense_to_expense(deferred_process, start_date=None, end_date=None, conditions=""): # book the expense/income on the last day, but it will be trigger on the 1st of month at 12:00 AM if not start_date: @@ -81,16 +75,14 @@ def convert_deferred_expense_to_expense( # check for the purchase invoice for which GL entries has to be done invoices = frappe.db.sql_list( - """ + f""" select distinct item.parent from `tabPurchase Invoice Item` item, `tabPurchase Invoice` p where item.service_start_date<=%s and item.service_end_date>=%s and item.enable_deferred_expense = 1 and item.parent=p.name and item.docstatus = 1 and ifnull(item.amount, 0) > 0 - {0} - """.format( - conditions - ), + {conditions} + """, (end_date, start_date), ) # nosec @@ -103,9 +95,7 @@ def convert_deferred_expense_to_expense( send_mail(deferred_process) -def convert_deferred_revenue_to_income( - deferred_process, start_date=None, end_date=None, conditions="" -): +def convert_deferred_revenue_to_income(deferred_process, start_date=None, end_date=None, conditions=""): # book the expense/income on the last day, but it will be trigger on the 1st of month at 12:00 AM if not start_date: @@ -115,16 +105,14 @@ def convert_deferred_revenue_to_income( # check for the sales invoice for which GL entries has to be done invoices = frappe.db.sql_list( - """ + f""" select distinct item.parent from `tabSales Invoice Item` item, `tabSales Invoice` p where item.service_start_date<=%s and item.service_end_date>=%s and item.enable_deferred_revenue = 1 and item.parent=p.name and item.docstatus = 1 and ifnull(item.amount, 0) > 0 - {0} - """.format( - conditions - ), + {conditions} + """, (end_date, start_date), ) # nosec @@ -243,9 +231,7 @@ def calculate_monthly_amount( already_booked_amount, already_booked_amount_in_account_currency = get_already_booked_amount( doc, item ) - base_amount = flt( - item.base_net_amount - already_booked_amount, item.precision("base_net_amount") - ) + base_amount = flt(item.base_net_amount - already_booked_amount, item.precision("base_net_amount")) if account_currency == doc.company_currency: amount = base_amount else: @@ -265,17 +251,13 @@ def calculate_amount(doc, item, last_gl_entry, total_days, total_booking_days, a if account_currency == doc.company_currency: amount = base_amount else: - amount = flt( - item.net_amount * total_booking_days / flt(total_days), item.precision("net_amount") - ) + amount = flt(item.net_amount * total_booking_days / flt(total_days), item.precision("net_amount")) else: already_booked_amount, already_booked_amount_in_account_currency = get_already_booked_amount( doc, item ) - base_amount = flt( - item.base_net_amount - already_booked_amount, item.precision("base_net_amount") - ) + base_amount = flt(item.base_net_amount - already_booked_amount, item.precision("base_net_amount")) if account_currency == doc.company_currency: amount = base_amount else: @@ -296,26 +278,22 @@ def get_already_booked_amount(doc, item): gl_entries_details = frappe.db.sql( """ - select sum({0}) as total_credit, sum({1}) as total_credit_in_account_currency, voucher_detail_no + select sum({}) as total_credit, sum({}) as total_credit_in_account_currency, voucher_detail_no from `tabGL Entry` where company=%s and account=%s and voucher_type=%s and voucher_no=%s and voucher_detail_no=%s and is_cancelled = 0 group by voucher_detail_no - """.format( - total_credit_debit, total_credit_debit_currency - ), + """.format(total_credit_debit, total_credit_debit_currency), (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name), as_dict=True, ) journal_entry_details = frappe.db.sql( """ - SELECT sum(c.{0}) as total_credit, sum(c.{1}) as total_credit_in_account_currency, reference_detail_no + SELECT sum(c.{}) as total_credit, sum(c.{}) as total_credit_in_account_currency, reference_detail_no FROM `tabJournal Entry` p , `tabJournal Entry Account` c WHERE p.name = c.parent and p.company = %s and c.account=%s and c.reference_type=%s and c.reference_name=%s and c.reference_detail_no=%s and p.docstatus < 2 group by reference_detail_no - """.format( - total_credit_debit, total_credit_debit_currency - ), + """.format(total_credit_debit, total_credit_debit_currency), (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name), as_dict=True, ) @@ -337,9 +315,7 @@ def get_already_booked_amount(doc, item): def book_deferred_income_or_expense(doc, deferred_process, posting_date=None): - enable_check = ( - "enable_deferred_revenue" if doc.doctype == "Sales Invoice" else "enable_deferred_expense" - ) + enable_check = "enable_deferred_revenue" if doc.doctype == "Sales Invoice" else "enable_deferred_expense" accounts_frozen_upto = frappe.db.get_single_value("Accounts Settings", "acc_frozen_upto") @@ -440,9 +416,7 @@ def book_deferred_income_or_expense(doc, deferred_process, posting_date=None): via_journal_entry = cint( frappe.db.get_singles_value("Accounts Settings", "book_deferred_entries_via_journal_entry") ) - submit_journal_entry = cint( - frappe.db.get_singles_value("Accounts Settings", "submit_journal_entries") - ) + submit_journal_entry = cint(frappe.db.get_singles_value("Accounts Settings", "submit_journal_entries")) book_deferred_entries_based_on = frappe.db.get_singles_value( "Accounts Settings", "book_deferred_entries_based_on" ) @@ -462,9 +436,7 @@ def process_deferred_accounting(posting_date=None): posting_date = today() if not cint( - frappe.db.get_singles_value( - "Accounts Settings", "automatically_process_deferred_accounting_entry" - ) + frappe.db.get_singles_value("Accounts Settings", "automatically_process_deferred_accounting_entry") ): return @@ -587,16 +559,13 @@ def book_revenue_via_journal_entry( deferred_process=None, submit="No", ): - if amount == 0: return journal_entry = frappe.new_doc("Journal Entry") journal_entry.posting_date = posting_date journal_entry.company = doc.company - journal_entry.voucher_type = ( - "Deferred Revenue" if doc.doctype == "Sales Invoice" else "Deferred Expense" - ) + journal_entry.voucher_type = "Deferred Revenue" if doc.doctype == "Sales Invoice" else "Deferred Expense" journal_entry.process_deferred_accounting = deferred_process debit_entry = { @@ -645,7 +614,6 @@ def book_revenue_via_journal_entry( def get_deferred_booking_accounts(doctype, voucher_detail_no, dr_or_cr): - if doctype == "Sales Invoice": credit_account, debit_account = frappe.db.get_value( "Sales Invoice Item", diff --git a/erpnext/accounts/doctype/account/account.py b/erpnext/accounts/doctype/account/account.py index 283e9d2f4ef..8cbaef43180 100644 --- a/erpnext/accounts/doctype/account/account.py +++ b/erpnext/accounts/doctype/account/account.py @@ -29,7 +29,7 @@ class Account(NestedSet): if frappe.local.flags.ignore_update_nsm: return else: - super(Account, self).on_update() + super().on_update() def onload(self): frozen_accounts_modifier = frappe.db.get_value( @@ -87,9 +87,7 @@ class Account(NestedSet): def set_root_and_report_type(self): if self.parent_account: - par = frappe.db.get_value( - "Account", self.parent_account, ["report_type", "root_type"], as_dict=1 - ) + par = frappe.db.get_value("Account", self.parent_account, ["report_type", "root_type"], as_dict=1) if par.report_type: self.report_type = par.report_type @@ -144,9 +142,7 @@ class Account(NestedSet): def validate_root_company_and_sync_account_to_children(self): # ignore validation while creating new compnay or while syncing to child companies - if ( - frappe.local.flags.ignore_root_company_validation or self.flags.ignore_root_company_validation - ): + if frappe.local.flags.ignore_root_company_validation or self.flags.ignore_root_company_validation: return ancestors = get_root_company(self.company) if ancestors: @@ -341,7 +337,7 @@ class Account(NestedSet): if self.check_gle_exists(): throw(_("Account with existing transaction can not be deleted")) - super(Account, self).on_trash(True) + super().on_trash(True) @frappe.whitelist() @@ -349,9 +345,8 @@ class Account(NestedSet): def get_parent_account(doctype, txt, searchfield, start, page_len, filters): return frappe.db.sql( """select name from tabAccount - where is_group = 1 and docstatus != 2 and company = %s - and %s like %s order by name limit %s offset %s""" - % ("%s", searchfield, "%s", "%s", "%s"), + where is_group = 1 and docstatus != 2 and company = {} + and {} like {} order by name limit {} offset {}""".format("%s", searchfield, "%s", "%s", "%s"), (filters["company"], "%%%s%%" % txt, page_len, start), as_list=1, ) @@ -409,9 +404,7 @@ def update_account_number(name, account_name, account_number=None, from_descenda if not account: return - old_acc_name, old_acc_number = frappe.db.get_value( - "Account", name, ["account_name", "account_number"] - ) + old_acc_name, old_acc_number = frappe.db.get_value("Account", name, ["account_name", "account_number"]) # check if account exists in parent company ancestors = get_ancestors_of("Company", account.company) @@ -519,7 +512,5 @@ def sync_update_account_number_in_child( if old_acc_number: filters["account_number"] = old_acc_number - for d in frappe.db.get_values( - "Account", filters=filters, fieldname=["company", "name"], as_dict=True - ): + for d in frappe.db.get_values("Account", filters=filters, fieldname=["company", "name"], as_dict=True): update_account_number(d["name"], account_name, account_number, from_descendant=True) diff --git a/erpnext/accounts/doctype/account/chart_of_accounts/chart_of_accounts.py b/erpnext/accounts/doctype/account/chart_of_accounts/chart_of_accounts.py index 216135a3975..ea5db9dccb7 100644 --- a/erpnext/accounts/doctype/account/chart_of_accounts/chart_of_accounts.py +++ b/erpnext/accounts/doctype/account/chart_of_accounts/chart_of_accounts.py @@ -31,7 +31,6 @@ def create_charts( "tax_rate", "account_currency", ]: - account_number = cstr(child.get("account_number")).strip() account_name, account_name_in_db = add_suffix_if_duplicate( account_name, account_number, accounts @@ -39,7 +38,9 @@ def create_charts( is_group = identify_is_group(child) report_type = ( - "Balance Sheet" if root_type in ["Asset", "Liability", "Equity"] else "Profit and Loss" + "Balance Sheet" + if root_type in ["Asset", "Liability", "Equity"] + else "Profit and Loss" ) account = frappe.get_doc( @@ -141,7 +142,7 @@ def get_chart(chart_template, existing_company=None): for fname in os.listdir(path): fname = frappe.as_unicode(fname) if fname.endswith(".json"): - with open(os.path.join(path, fname), "r") as f: + with open(os.path.join(path, fname)) as f: chart = f.read() if chart and json.loads(chart).get("name") == chart_template: return json.loads(chart).get("tree") @@ -173,7 +174,7 @@ def get_charts_for_country(country, with_standard=False): for fname in os.listdir(path): fname = frappe.as_unicode(fname) if (fname.startswith(country_code) or fname.startswith(country)) and fname.endswith(".json"): - with open(os.path.join(path, fname), "r") as f: + with open(os.path.join(path, fname)) as f: _get_chart_name(f.read()) # if more than one charts, returned then add the standard @@ -247,7 +248,13 @@ def validate_bank_account(coa, bank_account): def _get_account_names(account_master): for account_name, child in account_master.items(): - if account_name not in ["account_number", "account_type", "root_type", "is_group", "tax_rate"]: + if account_name not in [ + "account_number", + "account_type", + "root_type", + "is_group", + "tax_rate", + ]: accounts.append(account_name) _get_account_names(child) diff --git a/erpnext/accounts/doctype/account/chart_of_accounts/import_from_openerp.py b/erpnext/accounts/doctype/account/chart_of_accounts/import_from_openerp.py index 3f25ada8b35..928d51d9898 100644 --- a/erpnext/accounts/doctype/account/chart_of_accounts/import_from_openerp.py +++ b/erpnext/accounts/doctype/account/chart_of_accounts/import_from_openerp.py @@ -26,7 +26,7 @@ def go(): default_account_types = get_default_account_types() country_dirs = [] - for basepath, folders, files in os.walk(path): + for basepath, _folders, _files in os.walk(path): basename = os.path.basename(basepath) if basename.startswith("l10n_"): country_dirs.append(basename) @@ -35,9 +35,7 @@ def go(): accounts, charts = {}, {} country_path = os.path.join(path, country_dir) manifest = ast.literal_eval(open(os.path.join(country_path, "__openerp__.py")).read()) - data_files = ( - manifest.get("data", []) + manifest.get("init_xml", []) + manifest.get("update_xml", []) - ) + data_files = manifest.get("data", []) + manifest.get("init_xml", []) + manifest.get("update_xml", []) files_path = [os.path.join(country_path, d) for d in data_files] xml_roots = get_xml_roots(files_path) csv_content = get_csv_contents(files_path) @@ -90,10 +88,10 @@ def get_csv_contents(files_path): fname = os.path.basename(filepath) for file_type in ["account.account.template", "account.account.type", "account.chart.template"]: if fname.startswith(file_type) and fname.endswith(".csv"): - with open(filepath, "r") as csvfile: + with open(filepath) as csvfile: try: csv_content.setdefault(file_type, []).append(read_csv_content(csvfile.read())) - except Exception as e: + except Exception: continue return csv_content @@ -138,7 +136,7 @@ def get_account_types(root_list, csv_content, prefix=None): if csv_content and csv_content[0][0] == "id": for row in csv_content[1:]: - row_dict = dict(zip(csv_content[0], row)) + row_dict = dict(zip(csv_content[0], row, strict=False)) data = {} if row_dict.get("code") and account_type_map.get(row_dict["code"]): data["account_type"] = account_type_map[row_dict["code"]] @@ -150,7 +148,7 @@ def get_account_types(root_list, csv_content, prefix=None): def make_maps_for_xml(xml_roots, account_types, country_dir): """make maps for `charts` and `accounts`""" - for model, root_list in xml_roots.items(): + for _model, root_list in xml_roots.items(): for root in root_list: for node in root[0].findall("record"): if node.get("model") == "account.account.template": @@ -186,7 +184,7 @@ def make_maps_for_xml(xml_roots, account_types, country_dir): def make_maps_for_csv(csv_content, account_types, country_dir): for content in csv_content.get("account.account.template", []): for row in content[1:]: - data = dict(zip(content[0], row)) + data = dict(zip(content[0], row, strict=False)) account = { "name": data.get("name"), "parent_id": data.get("parent_id:id") or data.get("parent_id/id"), @@ -206,7 +204,7 @@ def make_maps_for_csv(csv_content, account_types, country_dir): for content in csv_content.get("account.chart.template", []): for row in content[1:]: if row: - data = dict(zip(content[0], row)) + data = dict(zip(content[0], row, strict=False)) charts.setdefault(data.get("id"), {}).update( { "account_root_id": data.get("account_root_id:id") or data.get("account_root_id/id"), @@ -241,7 +239,7 @@ def make_charts(): if not src.get("name") or not src.get("account_root_id"): continue - if not src["account_root_id"] in accounts: + if src["account_root_id"] not in accounts: continue filename = src["id"][5:] + "_" + chart_id @@ -259,10 +257,16 @@ def make_charts(): val["root_type"] = "" if chart: fpath = os.path.join( - "erpnext", "erpnext", "accounts", "doctype", "account", "chart_of_accounts", filename + ".json" + "erpnext", + "erpnext", + "accounts", + "doctype", + "account", + "chart_of_accounts", + filename + ".json", ) - with open(fpath, "r") as chartfile: + with open(fpath) as chartfile: old_content = chartfile.read() if not old_content or ( json.loads(old_content).get("is_active", "No") == "No" diff --git a/erpnext/accounts/doctype/account/test_account.py b/erpnext/accounts/doctype/account/test_account.py index 30eebef7fba..49d3f66e912 100644 --- a/erpnext/accounts/doctype/account/test_account.py +++ b/erpnext/accounts/doctype/account/test_account.py @@ -260,28 +260,20 @@ class TestAccount(unittest.TestCase): acc.insert() self.assertTrue( - frappe.db.exists( - "Account", {"account_name": "Test Group Account", "company": "_Test Company 4"} - ) + frappe.db.exists("Account", {"account_name": "Test Group Account", "company": "_Test Company 4"}) ) self.assertTrue( - frappe.db.exists( - "Account", {"account_name": "Test Group Account", "company": "_Test Company 5"} - ) + frappe.db.exists("Account", {"account_name": "Test Group Account", "company": "_Test Company 5"}) ) # Try renaming child company account acc_tc_5 = frappe.db.get_value( "Account", {"account_name": "Test Group Account", "company": "_Test Company 5"} ) - self.assertRaises( - frappe.ValidationError, update_account_number, acc_tc_5, "Test Modified Account" - ) + self.assertRaises(frappe.ValidationError, update_account_number, acc_tc_5, "Test Modified Account") # Rename child company account with allow_account_creation_against_child_company enabled - frappe.db.set_value( - "Company", "_Test Company 5", "allow_account_creation_against_child_company", 1 - ) + frappe.db.set_value("Company", "_Test Company 5", "allow_account_creation_against_child_company", 1) update_account_number(acc_tc_5, "Test Modified Account") self.assertTrue( @@ -290,9 +282,7 @@ class TestAccount(unittest.TestCase): ) ) - frappe.db.set_value( - "Company", "_Test Company 5", "allow_account_creation_against_child_company", 0 - ) + frappe.db.set_value("Company", "_Test Company 5", "allow_account_creation_against_child_company", 0) to_delete = [ "Test Group Account - _TC3", @@ -317,9 +307,7 @@ class TestAccount(unittest.TestCase): self.assertEqual(acc.account_currency, "INR") # Make a JV against this account - make_journal_entry( - "Test Currency Account - _TC", "Miscellaneous Expenses - _TC", 100, submit=True - ) + make_journal_entry("Test Currency Account - _TC", "Miscellaneous Expenses - _TC", 100, submit=True) acc.account_currency = "USD" self.assertRaises(frappe.ValidationError, acc.save) diff --git a/erpnext/accounts/doctype/account_closing_balance/account_closing_balance.py b/erpnext/accounts/doctype/account_closing_balance/account_closing_balance.py index d06bd833c8b..f6f5506efc0 100644 --- a/erpnext/accounts/doctype/account_closing_balance/account_closing_balance.py +++ b/erpnext/accounts/doctype/account_closing_balance/account_closing_balance.py @@ -17,16 +17,12 @@ class AccountClosingBalance(Document): def make_closing_entries(closing_entries, voucher_name, company, closing_date): accounting_dimensions = get_accounting_dimensions() - previous_closing_entries = get_previous_closing_entries( - company, closing_date, accounting_dimensions - ) + previous_closing_entries = get_previous_closing_entries(company, closing_date, accounting_dimensions) combined_entries = closing_entries + previous_closing_entries - merged_entries = aggregate_with_last_account_closing_balance( - combined_entries, accounting_dimensions - ) + merged_entries = aggregate_with_last_account_closing_balance(combined_entries, accounting_dimensions) - for key, value in merged_entries.items(): + for _key, value in merged_entries.items(): cle = frappe.new_doc("Account Closing Balance") cle.update(value) cle.update(value["dimensions"]) diff --git a/erpnext/accounts/doctype/accounting_dimension/accounting_dimension.py b/erpnext/accounts/doctype/accounting_dimension/accounting_dimension.py index c6c5f207a6a..edddcb54df0 100644 --- a/erpnext/accounts/doctype/accounting_dimension/accounting_dimension.py +++ b/erpnext/accounts/doctype/accounting_dimension/accounting_dimension.py @@ -17,7 +17,8 @@ class AccountingDimension(Document): self.set_fieldname_and_label() def validate(self): - if self.document_type in core_doctypes_list + ( + if self.document_type in ( + *core_doctypes_list, "Accounting Dimension", "Project", "Cost Center", @@ -25,13 +26,10 @@ class AccountingDimension(Document): "Company", "Account", ): - msg = _("Not allowed to create accounting dimension for {0}").format(self.document_type) frappe.throw(msg) - exists = frappe.db.get_value( - "Accounting Dimension", {"document_type": self.document_type}, ["name"] - ) + exists = frappe.db.get_value("Accounting Dimension", {"document_type": self.document_type}, ["name"]) if exists and self.is_new(): frappe.throw(_("Document Type already used as a dimension")) @@ -89,7 +87,6 @@ def make_dimension_in_accounting_doctypes(doc, doclist=None): count = 0 for doctype in doclist: - if (doc_count + 1) % 2 == 0: insert_after_field = "dimension_col_break" else: @@ -123,7 +120,7 @@ def add_dimension_to_budget_doctype(df, doc): df.update( { "insert_after": "cost_center", - "depends_on": "eval:doc.budget_against == '{0}'".format(doc.document_type), + "depends_on": f"eval:doc.budget_against == '{doc.document_type}'", } ) @@ -157,19 +154,17 @@ def delete_accounting_dimension(doc): frappe.db.sql( """ DELETE FROM `tabCustom Field` - WHERE fieldname = %s - AND dt IN (%s)""" - % ("%s", ", ".join(["%s"] * len(doclist))), # nosec - tuple([doc.fieldname] + doclist), + WHERE fieldname = {} + AND dt IN ({})""".format("%s", ", ".join(["%s"] * len(doclist))), # nosec + tuple([doc.fieldname, *doclist]), ) frappe.db.sql( """ DELETE FROM `tabProperty Setter` - WHERE field_name = %s - AND doc_type IN (%s)""" - % ("%s", ", ".join(["%s"] * len(doclist))), # nosec - tuple([doc.fieldname] + doclist), + WHERE field_name = {} + AND doc_type IN ({})""".format("%s", ", ".join(["%s"] * len(doclist))), # nosec + tuple([doc.fieldname, *doclist]), ) budget_against_property = frappe.get_doc("Property Setter", "Budget-budget_against-options") @@ -218,7 +213,6 @@ def get_doctypes_with_dimensions(): def get_accounting_dimensions(as_list=True, filters=None): - if not filters: filters = {"disabled": 0} @@ -249,7 +243,6 @@ def get_checks_for_pl_and_bs_accounts(): def get_dimension_with_children(doctype, dimensions): - if isinstance(dimensions, str): dimensions = [dimensions] @@ -257,9 +250,7 @@ def get_dimension_with_children(doctype, dimensions): for dimension in dimensions: lft, rgt = frappe.db.get_value(doctype, dimension, ["lft", "rgt"]) - children = frappe.get_all( - doctype, filters={"lft": [">=", lft], "rgt": ["<=", rgt]}, order_by="lft" - ) + children = frappe.get_all(doctype, filters={"lft": [">=", lft], "rgt": ["<=", rgt]}, order_by="lft") all_dimensions += [c.name for c in children] return all_dimensions diff --git a/erpnext/accounts/doctype/accounting_dimension_filter/test_accounting_dimension_filter.py b/erpnext/accounts/doctype/accounting_dimension_filter/test_accounting_dimension_filter.py index 3dc87bb4e38..50ca0626783 100644 --- a/erpnext/accounts/doctype/accounting_dimension_filter/test_accounting_dimension_filter.py +++ b/erpnext/accounts/doctype/accounting_dimension_filter/test_accounting_dimension_filter.py @@ -57,9 +57,7 @@ class TestAccountingDimensionFilter(unittest.TestCase): def create_accounting_dimension_filter(): - if not frappe.db.get_value( - "Accounting Dimension Filter", {"accounting_dimension": "Cost Center"} - ): + if not frappe.db.get_value("Accounting Dimension Filter", {"accounting_dimension": "Cost Center"}): frappe.get_doc( { "doctype": "Accounting Dimension Filter", diff --git a/erpnext/accounts/doctype/accounting_period/accounting_period.py b/erpnext/accounts/doctype/accounting_period/accounting_period.py index d5f37a68067..7bb36df3bea 100644 --- a/erpnext/accounts/doctype/accounting_period/accounting_period.py +++ b/erpnext/accounts/doctype/accounting_period/accounting_period.py @@ -67,7 +67,10 @@ class AccountingPeriod(Document): for doctype_for_closing in self.get_doctypes_for_closing(): self.append( "closed_documents", - {"document_type": doctype_for_closing.document_type, "closed": doctype_for_closing.closed}, + { + "document_type": doctype_for_closing.document_type, + "closed": doctype_for_closing.closed, + }, ) diff --git a/erpnext/accounts/doctype/accounting_period/test_accounting_period.py b/erpnext/accounts/doctype/accounting_period/test_accounting_period.py index 41d94797ad6..16cae9683f9 100644 --- a/erpnext/accounts/doctype/accounting_period/test_accounting_period.py +++ b/erpnext/accounts/doctype/accounting_period/test_accounting_period.py @@ -34,9 +34,7 @@ class TestAccountingPeriod(unittest.TestCase): ap1 = create_accounting_period(period_name="Test Accounting Period 2") ap1.save() - doc = create_sales_invoice( - do_not_save=1, cost_center="_Test Company - _TC", warehouse="Stores - _TC" - ) + doc = create_sales_invoice(do_not_save=1, cost_center="_Test Company - _TC", warehouse="Stores - _TC") self.assertRaises(ClosedAccountingPeriod, doc.save) def tearDown(self): diff --git a/erpnext/accounts/doctype/bank_account/test_bank_account.py b/erpnext/accounts/doctype/bank_account/test_bank_account.py index 8949524a561..0ec388d9e5c 100644 --- a/erpnext/accounts/doctype/bank_account/test_bank_account.py +++ b/erpnext/accounts/doctype/bank_account/test_bank_account.py @@ -37,11 +37,11 @@ class TestBankAccount(unittest.TestCase): try: bank_account.validate_iban() except ValidationError: - msg = "BankAccount.validate_iban() failed for valid IBAN {}".format(iban) + msg = f"BankAccount.validate_iban() failed for valid IBAN {iban}" self.fail(msg=msg) for not_iban in invalid_ibans: bank_account.iban = not_iban - msg = "BankAccount.validate_iban() accepted invalid IBAN {}".format(not_iban) + msg = f"BankAccount.validate_iban() accepted invalid IBAN {not_iban}" with self.assertRaises(ValidationError, msg=msg): bank_account.validate_iban() diff --git a/erpnext/accounts/doctype/bank_clearance/bank_clearance.py b/erpnext/accounts/doctype/bank_clearance/bank_clearance.py index 8ad0bd17b48..6445deba6c3 100644 --- a/erpnext/accounts/doctype/bank_clearance/bank_clearance.py +++ b/erpnext/accounts/doctype/bank_clearance/bank_clearance.py @@ -27,7 +27,7 @@ class BankClearance(Document): condition = "and (clearance_date IS NULL or clearance_date='0000-00-00')" journal_entries = frappe.db.sql( - """ + f""" select "Journal Entry" as payment_document, t1.name as payment_entry, t1.cheque_no as cheque_number, t1.cheque_date, @@ -41,9 +41,7 @@ class BankClearance(Document): and ifnull(t1.is_opening, 'No') = 'No' {condition} group by t2.account, t1.name order by t1.posting_date ASC, t1.name DESC - """.format( - condition=condition - ), + """, {"account": self.account, "from": self.from_date, "to": self.to_date}, as_dict=1, ) @@ -52,7 +50,7 @@ class BankClearance(Document): condition += "and bank_account = %(bank_account)s" payment_entries = frappe.db.sql( - """ + f""" select "Payment Entry" as payment_document, name as payment_entry, reference_no as cheque_number, reference_date as cheque_date, @@ -67,9 +65,7 @@ class BankClearance(Document): {condition} order by posting_date ASC, name DESC - """.format( - condition=condition - ), + """, { "account": self.account, "from": self.from_date, @@ -132,11 +128,9 @@ class BankClearance(Document): query = query.where(loan_repayment.clearance_date.isnull()) if frappe.db.has_column("Loan Repayment", "repay_from_salary"): - query = query.where((loan_repayment.repay_from_salary == 0)) + query = query.where(loan_repayment.repay_from_salary == 0) - query = query.orderby(loan_repayment.posting_date).orderby( - loan_repayment.name, order=frappe.qb.desc - ) + query = query.orderby(loan_repayment.posting_date).orderby(loan_repayment.name, order=frappe.qb.desc) loan_repayments = query.run(as_dict=True) diff --git a/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py b/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py index 6017c5a491d..2987bac677c 100644 --- a/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py +++ b/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py @@ -61,9 +61,7 @@ def get_bank_transactions(bank_account, from_date=None, to_date=None): def get_account_balance(bank_account, till_date): # returns account balance till the specified date account = frappe.db.get_value("Bank Account", bank_account, "account") - filters = frappe._dict( - {"account": account, "report_date": till_date, "include_pos_transactions": 1} - ) + filters = frappe._dict({"account": account, "report_date": till_date, "include_pos_transactions": 1}) data = get_entries(filters) balance_as_per_system = get_balance_on(filters["account"], filters["report_date"]) @@ -76,10 +74,7 @@ def get_account_balance(bank_account, till_date): amounts_not_reflected_in_system = get_amounts_not_reflected_in_system(filters) bank_bal = ( - flt(balance_as_per_system) - - flt(total_debit) - + flt(total_credit) - + amounts_not_reflected_in_system + flt(balance_as_per_system) - flt(total_debit) + flt(total_credit) + amounts_not_reflected_in_system ) return bank_bal @@ -377,12 +372,13 @@ def auto_reconcile_vouchers( ) transaction = frappe.get_doc("Bank Transaction", transaction.name) account = frappe.db.get_value("Bank Account", transaction.bank_account, "account") - matched_trans = 0 for voucher in vouchers: gl_entry = frappe.db.get_value( "GL Entry", dict( - account=account, voucher_type=voucher["payment_doctype"], voucher_no=voucher["payment_name"] + account=account, + voucher_type=voucher["payment_doctype"], + voucher_no=voucher["payment_name"], ), ["credit", "debit"], as_dict=1, @@ -731,7 +727,7 @@ def get_lr_matching_query(bank_account, exact_match, filters): ) if frappe.db.has_column("Loan Repayment", "repay_from_salary"): - query = query.where((loan_repayment.repay_from_salary == 0)) + query = query.where(loan_repayment.repay_from_salary == 0) if exact_match: query.where(loan_repayment.amount_paid == filters.get("amount")) @@ -764,7 +760,7 @@ def get_pe_matching_query( if cint(filter_by_reference_date): filter_by_date = f"AND reference_date between '{from_reference_date}' and '{to_reference_date}'" order_by = " reference_date" - if frappe.flags.auto_reconcile_vouchers == True: + if frappe.flags.auto_reconcile_vouchers is True: filter_by_reference_no = f"AND reference_no = '{transaction.reference_number}'" return f""" SELECT @@ -815,7 +811,7 @@ def get_je_matching_query( if cint(filter_by_reference_date): filter_by_date = f"AND je.cheque_date between '{from_reference_date}' and '{to_reference_date}'" order_by = " je.cheque_date" - if frappe.flags.auto_reconcile_vouchers == True: + if frappe.flags.auto_reconcile_vouchers is True: filter_by_reference_no = f"AND je.cheque_no = '{transaction.reference_number}'" return f""" SELECT diff --git a/erpnext/accounts/doctype/bank_statement_import/bank_statement_import.py b/erpnext/accounts/doctype/bank_statement_import/bank_statement_import.py index 3f5c064f4b9..78a27c3b96d 100644 --- a/erpnext/accounts/doctype/bank_statement_import/bank_statement_import.py +++ b/erpnext/accounts/doctype/bank_statement_import/bank_statement_import.py @@ -21,7 +21,7 @@ INVALID_VALUES = ("", None) class BankStatementImport(DataImport): def __init__(self, *args, **kwargs): - super(BankStatementImport, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def validate(self): doc_before_save = self.get_doc_before_save() @@ -30,7 +30,6 @@ class BankStatementImport(DataImport): or (doc_before_save and doc_before_save.import_file != self.import_file) or (doc_before_save and doc_before_save.google_sheets_url != self.google_sheets_url) ): - template_options_dict = {} column_to_field_map = {} bank = frappe.get_doc("Bank", self.bank) @@ -45,7 +44,6 @@ class BankStatementImport(DataImport): self.validate_google_sheets_url() def start_import(self): - preview = frappe.get_doc("Bank Statement Import", self.name).get_preview_from_template( self.import_file, self.google_sheets_url ) @@ -102,7 +100,7 @@ def download_errored_template(data_import_name): def parse_data_from_template(raw_data): data = [] - for i, row in enumerate(raw_data): + for _i, row in enumerate(raw_data): if all(v in INVALID_VALUES for v in row): # empty row continue @@ -112,9 +110,7 @@ def parse_data_from_template(raw_data): return data -def start_import( - data_import, bank_account, import_file_path, google_sheets_url, bank, template_options -): +def start_import(data_import, bank_account, import_file_path, google_sheets_url, bank, template_options): """This method runs in background job""" update_mapping_db(bank, template_options) diff --git a/erpnext/accounts/doctype/bank_transaction/auto_match_party.py b/erpnext/accounts/doctype/bank_transaction/auto_match_party.py index 04dab4c28a0..230407ba5a4 100644 --- a/erpnext/accounts/doctype/bank_transaction/auto_match_party.py +++ b/erpnext/accounts/doctype/bank_transaction/auto_match_party.py @@ -1,5 +1,3 @@ -from typing import Tuple, Union - import frappe from frappe.utils import flt from rapidfuzz import fuzz, process @@ -19,7 +17,7 @@ class AutoMatchParty: def get(self, key): return self.__dict__.get(key, None) - def match(self) -> Union[Tuple, None]: + def match(self) -> tuple | None: result = None result = AutoMatchbyAccountIBAN( bank_party_account_number=self.bank_party_account_number, @@ -50,7 +48,7 @@ class AutoMatchbyAccountIBAN: result = self.match_account_in_party() return result - def match_account_in_party(self) -> Union[Tuple, None]: + def match_account_in_party(self) -> tuple | None: """Check if there is a IBAN/Account No. match in Customer/Supplier/Employee""" result = None parties = get_parties_in_order(self.deposit) @@ -97,7 +95,7 @@ class AutoMatchbyPartyNameDescription: def get(self, key): return self.__dict__.get(key, None) - def match(self) -> Union[Tuple, None]: + def match(self) -> tuple | None: # fuzzy search by customer/supplier & employee if not (self.bank_party_name or self.description): return None @@ -105,7 +103,7 @@ class AutoMatchbyPartyNameDescription: result = self.match_party_name_desc_in_party() return result - def match_party_name_desc_in_party(self) -> Union[Tuple, None]: + def match_party_name_desc_in_party(self) -> tuple | None: """Fuzzy search party name and/or description against parties in the system""" result = None parties = get_parties_in_order(self.deposit) @@ -130,7 +128,7 @@ class AutoMatchbyPartyNameDescription: return result - def fuzzy_search_and_return_result(self, party, names, field) -> Union[Tuple, None]: + def fuzzy_search_and_return_result(self, party, names, field) -> tuple | None: skip = False result = process.extract( query=self.get(field), @@ -147,7 +145,7 @@ class AutoMatchbyPartyNameDescription: party_name, ), skip - def process_fuzzy_result(self, result: Union[list, None]): + def process_fuzzy_result(self, result: list | None): """ If there are multiple valid close matches return None as result may be faulty. Return the result only if one accurate match stands out. diff --git a/erpnext/accounts/doctype/bank_transaction/bank_transaction.py b/erpnext/accounts/doctype/bank_transaction/bank_transaction.py index c0a65ed0d4c..49c5a9fe4ee 100644 --- a/erpnext/accounts/doctype/bank_transaction/bank_transaction.py +++ b/erpnext/accounts/doctype/bank_transaction/bank_transaction.py @@ -186,9 +186,7 @@ def get_clearance_details(transaction, payment_entry): """ gl_bank_account = frappe.db.get_value("Bank Account", transaction.bank_account, "account") gles = get_related_bank_gl_entries(payment_entry.payment_document, payment_entry.payment_entry) - bt_allocations = get_total_allocated_amount( - payment_entry.payment_document, payment_entry.payment_entry - ) + bt_allocations = get_total_allocated_amount(payment_entry.payment_document, payment_entry.payment_entry) unallocated_amount = min( transaction.unallocated_amount, @@ -286,7 +284,6 @@ def get_total_allocated_amount(doctype, docname): def get_paid_amount(payment_entry, currency, gl_bank_account): if payment_entry.payment_document in ["Payment Entry", "Sales Invoice", "Purchase Invoice"]: - paid_amount_field = "paid_amount" if payment_entry.payment_document == "Payment Entry": doc = frappe.get_doc("Payment Entry", payment_entry.payment_entry) @@ -325,9 +322,7 @@ def get_paid_amount(payment_entry, currency, gl_bank_account): ) elif payment_entry.payment_document == "Loan Repayment": - return frappe.db.get_value( - payment_entry.payment_document, payment_entry.payment_entry, "amount_paid" - ) + return frappe.db.get_value(payment_entry.payment_document, payment_entry.payment_entry, "amount_paid") elif payment_entry.payment_document == "Bank Transaction": dep, wth = frappe.db.get_value( @@ -337,9 +332,7 @@ def get_paid_amount(payment_entry, currency, gl_bank_account): else: frappe.throw( - "Please reconcile {0}: {1} manually".format( - payment_entry.payment_document, payment_entry.payment_entry - ) + f"Please reconcile {payment_entry.payment_document}: {payment_entry.payment_entry} manually" ) diff --git a/erpnext/accounts/doctype/bank_transaction/bank_transaction_upload.py b/erpnext/accounts/doctype/bank_transaction/bank_transaction_upload.py index 372c53d4992..2fec01ad397 100644 --- a/erpnext/accounts/doctype/bank_transaction/bank_transaction_upload.py +++ b/erpnext/accounts/doctype/bank_transaction/bank_transaction_upload.py @@ -18,12 +18,12 @@ def upload_bank_statement(): fcontent = frappe.local.uploaded_file fname = frappe.local.uploaded_filename - if frappe.safe_encode(fname).lower().endswith("csv".encode("utf-8")): + if frappe.safe_encode(fname).lower().endswith(b"csv"): from frappe.utils.csvutils import read_csv_content rows = read_csv_content(fcontent, False) - elif frappe.safe_encode(fname).lower().endswith("xlsx".encode("utf-8")): + elif frappe.safe_encode(fname).lower().endswith(b"xlsx"): from frappe.utils.xlsxutils import read_xlsx_file_from_attached_file rows = read_xlsx_file_from_attached_file(fcontent=fcontent) diff --git a/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py b/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py index b35ed01cd9a..71b901327d7 100644 --- a/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py +++ b/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py @@ -430,9 +430,7 @@ def add_vouchers(gl_account="_Test Bank - _TC"): mode_of_payment = frappe.get_doc({"doctype": "Mode of Payment", "name": "Cash"}) - if not frappe.db.get_value( - "Mode of Payment Account", {"company": "_Test Company", "parent": "Cash"} - ): + if not frappe.db.get_value("Mode of Payment Account", {"company": "_Test Company", "parent": "Cash"}): mode_of_payment.append("accounts", {"company": "_Test Company", "default_account": gl_account}) mode_of_payment.save() diff --git a/erpnext/accounts/doctype/budget/budget.py b/erpnext/accounts/doctype/budget/budget.py index 42b6b44690b..bdff463a869 100644 --- a/erpnext/accounts/doctype/budget/budget.py +++ b/erpnext/accounts/doctype/budget/budget.py @@ -40,10 +40,11 @@ class Budget(Document): select b.name, ba.account from `tabBudget` b, `tabBudget Account` ba where - ba.parent = b.name and b.docstatus < 2 and b.company = %s and %s=%s and - b.fiscal_year=%s and b.name != %s and ba.account in (%s) """ - % ("%s", budget_against_field, "%s", "%s", "%s", ",".join(["%s"] * len(accounts))), - (self.company, budget_against, self.fiscal_year, self.name) + tuple(accounts), + ba.parent = b.name and b.docstatus < 2 and b.company = {} and {}={} and + b.fiscal_year={} and b.name != {} and ba.account in ({}) """.format( + "%s", budget_against_field, "%s", "%s", "%s", ",".join(["%s"] * len(accounts)) + ), + (self.company, budget_against, self.fiscal_year, self.name, *tuple(accounts)), as_dict=1, ) @@ -66,12 +67,14 @@ class Budget(Document): if account_details.is_group: frappe.throw(_("Budget cannot be assigned against Group Account {0}").format(d.account)) elif account_details.company != self.company: - frappe.throw(_("Account {0} does not belongs to company {1}").format(d.account, self.company)) + frappe.throw( + _("Account {0} does not belongs to company {1}").format(d.account, self.company) + ) elif account_details.report_type != "Profit and Loss": frappe.throw( - _("Budget cannot be assigned against {0}, as it's not an Income or Expense account").format( - d.account - ) + _( + "Budget cannot be assigned against {0}, as it's not an Income or Expense account" + ).format(d.account) ) if d.account in account_list: @@ -118,9 +121,7 @@ def validate_expense_against_budget(args, expense_amount=0): "Company", args.get("company"), "exception_budget_approver_role" ) - if not frappe.get_cached_value( - "Budget", {"fiscal_year": args.fiscal_year, "company": args.company} - ): # nosec + if not frappe.get_cached_value("Budget", {"fiscal_year": args.fiscal_year, "company": args.company}): # nosec return if not args.account: @@ -151,30 +152,24 @@ def validate_expense_against_budget(args, expense_amount=0): and args.account and (frappe.get_cached_value("Account", args.account, "root_type") == "Expense") ): - doctype = dimension.get("document_type") if frappe.get_cached_value("DocType", doctype, "is_tree"): lft, rgt = frappe.get_cached_value(doctype, args.get(budget_against), ["lft", "rgt"]) - condition = """and exists(select name from `tab%s` - where lft<=%s and rgt>=%s and name=b.%s)""" % ( - doctype, - lft, - rgt, - budget_against, - ) # nosec + condition = f"""and exists(select name from `tab{doctype}` + where lft<={lft} and rgt>={rgt} and name=b.{budget_against})""" # nosec args.is_tree = True else: - condition = "and b.%s=%s" % (budget_against, frappe.db.escape(args.get(budget_against))) + condition = f"and b.{budget_against}={frappe.db.escape(args.get(budget_against))}" args.is_tree = False args.budget_against_field = budget_against args.budget_against_doctype = doctype budget_records = frappe.db.sql( - """ + f""" select - b.{budget_against_field} as budget_against, ba.budget_amount, b.monthly_distribution, + b.{budget_against} as budget_against, ba.budget_amount, b.monthly_distribution, ifnull(b.applicable_on_material_request, 0) as for_material_request, ifnull(applicable_on_purchase_order, 0) as for_purchase_order, ifnull(applicable_on_booking_actual_expenses,0) as for_actual_expenses, @@ -187,9 +182,7 @@ def validate_expense_against_budget(args, expense_amount=0): b.name=ba.parent and b.fiscal_year=%s and ba.account=%s and b.docstatus=1 {condition} - """.format( - condition=condition, budget_against_field=budget_against - ), + """, (args.fiscal_year, args.account), as_dict=True, ) # nosec @@ -217,7 +210,12 @@ def validate_budget_records(args, budget_records, expense_amount): args["month_end_date"] = get_last_day(args.posting_date) compare_expense_with_budget( - args, budget_amount, _("Accumulated Monthly"), monthly_action, budget.budget_against, amount + args, + budget_amount, + _("Accumulated Monthly"), + monthly_action, + budget.budget_against, + amount, ) @@ -245,9 +243,8 @@ def compare_expense_with_budget(args, budget_amount, action_for, action, budget_ frappe.bold(fmt_money(diff, currency=currency)), ) - if ( - frappe.flags.exception_approver_role - and frappe.flags.exception_approver_role in frappe.get_roles(frappe.session.user) + if frappe.flags.exception_approver_role and frappe.flags.exception_approver_role in frappe.get_roles( + frappe.session.user ): action = "Warn" @@ -293,10 +290,8 @@ def get_requested_amount(args, budget): data = frappe.db.sql( """ select ifnull((sum(child.stock_qty - child.ordered_qty) * rate), 0) as amount from `tabMaterial Request Item` child, `tabMaterial Request` parent where parent.name = child.parent and - child.item_code = %s and parent.docstatus = 1 and child.stock_qty > child.ordered_qty and {0} and - parent.material_request_type = 'Purchase' and parent.status != 'Stopped'""".format( - condition - ), + child.item_code = %s and parent.docstatus = 1 and child.stock_qty > child.ordered_qty and {} and + parent.material_request_type = 'Purchase' and parent.status != 'Stopped'""".format(condition), item_code, as_list=1, ) @@ -309,12 +304,10 @@ def get_ordered_amount(args, budget): condition = get_other_condition(args, budget, "Purchase Order") data = frappe.db.sql( - """ select ifnull(sum(child.amount - child.billed_amt), 0) as amount + f""" select ifnull(sum(child.amount - child.billed_amt), 0) as amount from `tabPurchase Order Item` child, `tabPurchase Order` parent where parent.name = child.parent and child.item_code = %s and parent.docstatus = 1 and child.amount > child.billed_amt - and parent.status != 'Closed' and {0}""".format( - condition - ), + and parent.status != 'Closed' and {condition}""", item_code, as_list=1, ) @@ -327,7 +320,7 @@ def get_other_condition(args, budget, for_doc): budget_against_field = args.get("budget_against_field") if budget_against_field and args.get(budget_against_field): - condition += " and child.%s = '%s'" % (budget_against_field, args.get(budget_against_field)) + condition += f" and child.{budget_against_field} = '{args.get(budget_against_field)}'" if args.get("fiscal_year"): date_field = "schedule_date" if for_doc == "Material Request" else "transaction_date" @@ -335,12 +328,8 @@ def get_other_condition(args, budget, for_doc): "Fiscal Year", args.get("fiscal_year"), ["year_start_date", "year_end_date"] ) - condition += """ and parent.%s - between '%s' and '%s' """ % ( - date_field, - start_date, - end_date, - ) + condition += f""" and parent.{date_field} + between '{start_date}' and '{end_date}' """ return condition @@ -362,18 +351,17 @@ def get_actual_expense(args): condition2 = """and exists(select name from `tab{doctype}` where lft>=%(lft)s and rgt<=%(rgt)s and name=gle.{budget_against_field})""".format( - doctype=args.budget_against_doctype, budget_against_field=budget_against_field # nosec + doctype=args.budget_against_doctype, + budget_against_field=budget_against_field, # nosec ) else: - condition2 = """and exists(select name from `tab{doctype}` - where name=gle.{budget_against} and - gle.{budget_against} = %({budget_against})s)""".format( - doctype=args.budget_against_doctype, budget_against=budget_against_field - ) + condition2 = f"""and exists(select name from `tab{args.budget_against_doctype}` + where name=gle.{budget_against_field} and + gle.{budget_against_field} = %({budget_against_field})s)""" amount = flt( frappe.db.sql( - """ + f""" select sum(gle.debit) - sum(gle.credit) from `tabGL Entry` gle where @@ -384,9 +372,7 @@ def get_actual_expense(args): and gle.company=%(company)s and gle.docstatus=1 {condition2} - """.format( - condition1=condition1, condition2=condition2 - ), + """, (args), )[0][0] ) # nosec diff --git a/erpnext/accounts/doctype/budget/test_budget.py b/erpnext/accounts/doctype/budget/test_budget.py index 11af9a29f6f..6d9a6f51468 100644 --- a/erpnext/accounts/doctype/budget/test_budget.py +++ b/erpnext/accounts/doctype/budget/test_budget.py @@ -41,9 +41,7 @@ class TestBudget(unittest.TestCase): budget = make_budget(budget_against="Cost Center") - frappe.db.set_value( - "Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop" - ) + frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop") jv = make_journal_entry( "_Test Account Cost for Goods Sold - _TC", @@ -63,9 +61,7 @@ class TestBudget(unittest.TestCase): budget = make_budget(budget_against="Cost Center") - frappe.db.set_value( - "Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop" - ) + frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop") jv = make_journal_entry( "_Test Account Cost for Goods Sold - _TC", @@ -97,9 +93,7 @@ class TestBudget(unittest.TestCase): ) fiscal_year = get_fiscal_year(nowdate())[0] - frappe.db.set_value( - "Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop" - ) + frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop") frappe.db.set_value("Budget", budget.name, "fiscal_year", fiscal_year) mr = frappe.get_doc( @@ -138,9 +132,7 @@ class TestBudget(unittest.TestCase): ) fiscal_year = get_fiscal_year(nowdate())[0] - frappe.db.set_value( - "Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop" - ) + frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop") frappe.db.set_value("Budget", budget.name, "fiscal_year", fiscal_year) po = create_purchase_order(transaction_date=nowdate(), do_not_submit=True) @@ -158,9 +150,7 @@ class TestBudget(unittest.TestCase): budget = make_budget(budget_against="Project") - frappe.db.set_value( - "Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop" - ) + frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop") project = frappe.get_value("Project", {"project_name": "_Test Project"}) @@ -223,7 +213,7 @@ class TestBudget(unittest.TestCase): if month > 9: month = 9 - for i in range(month + 1): + for _i in range(month + 1): jv = make_journal_entry( "_Test Account Cost for Goods Sold - _TC", "_Test Bank - _TC", @@ -237,9 +227,7 @@ class TestBudget(unittest.TestCase): frappe.db.get_value("GL Entry", {"voucher_type": "Journal Entry", "voucher_no": jv.name}) ) - frappe.db.set_value( - "Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop" - ) + frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop") self.assertRaises(BudgetError, jv.cancel) @@ -255,7 +243,7 @@ class TestBudget(unittest.TestCase): month = 9 project = frappe.get_value("Project", {"project_name": "_Test Project"}) - for i in range(month + 1): + for _i in range(month + 1): jv = make_journal_entry( "_Test Account Cost for Goods Sold - _TC", "_Test Bank - _TC", @@ -270,9 +258,7 @@ class TestBudget(unittest.TestCase): frappe.db.get_value("GL Entry", {"voucher_type": "Journal Entry", "voucher_no": jv.name}) ) - frappe.db.set_value( - "Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop" - ) + frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop") self.assertRaises(BudgetError, jv.cancel) @@ -284,9 +270,7 @@ class TestBudget(unittest.TestCase): set_total_expense_zero(nowdate(), "cost_center", "_Test Cost Center 2 - _TC") budget = make_budget(budget_against="Cost Center", cost_center="_Test Company - _TC") - frappe.db.set_value( - "Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop" - ) + frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop") jv = make_journal_entry( "_Test Account Cost for Goods Sold - _TC", @@ -316,9 +300,7 @@ class TestBudget(unittest.TestCase): ).insert(ignore_permissions=True) budget = make_budget(budget_against="Cost Center", cost_center=cost_center) - frappe.db.set_value( - "Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop" - ) + frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop") jv = make_journal_entry( "_Test Account Cost for Goods Sold - _TC", @@ -423,13 +405,11 @@ def make_budget(**args): fiscal_year = get_fiscal_year(nowdate())[0] if budget_against == "Project": - project_name = "{0}%".format("_Test Project/" + fiscal_year) + project_name = "{}%".format("_Test Project/" + fiscal_year) budget_list = frappe.get_all("Budget", fields=["name"], filters={"name": ("like", project_name)}) else: - cost_center_name = "{0}%".format(cost_center or "_Test Cost Center - _TC/" + fiscal_year) - budget_list = frappe.get_all( - "Budget", fields=["name"], filters={"name": ("like", cost_center_name)} - ) + cost_center_name = "{}%".format(cost_center or "_Test Cost Center - _TC/" + fiscal_year) + budget_list = frappe.get_all("Budget", fields=["name"], filters={"name": ("like", cost_center_name)}) for d in budget_list: frappe.db.sql("delete from `tabBudget` where name = %(name)s", d) frappe.db.sql("delete from `tabBudget Account` where parent = %(name)s", d) @@ -451,24 +431,18 @@ def make_budget(**args): budget.action_if_annual_budget_exceeded = "Stop" budget.action_if_accumulated_monthly_budget_exceeded = "Ignore" budget.budget_against = budget_against - budget.append( - "accounts", {"account": "_Test Account Cost for Goods Sold - _TC", "budget_amount": 200000} - ) + budget.append("accounts", {"account": "_Test Account Cost for Goods Sold - _TC", "budget_amount": 200000}) if args.applicable_on_material_request: budget.applicable_on_material_request = 1 - budget.action_if_annual_budget_exceeded_on_mr = ( - args.action_if_annual_budget_exceeded_on_mr or "Warn" - ) + budget.action_if_annual_budget_exceeded_on_mr = args.action_if_annual_budget_exceeded_on_mr or "Warn" budget.action_if_accumulated_monthly_budget_exceeded_on_mr = ( args.action_if_accumulated_monthly_budget_exceeded_on_mr or "Warn" ) if args.applicable_on_purchase_order: budget.applicable_on_purchase_order = 1 - budget.action_if_annual_budget_exceeded_on_po = ( - args.action_if_annual_budget_exceeded_on_po or "Warn" - ) + budget.action_if_annual_budget_exceeded_on_po = args.action_if_annual_budget_exceeded_on_po or "Warn" budget.action_if_accumulated_monthly_budget_exceeded_on_po = ( args.action_if_accumulated_monthly_budget_exceeded_on_po or "Warn" ) diff --git a/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py b/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py index ea73847555d..0846841e84c 100644 --- a/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py +++ b/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py @@ -26,9 +26,7 @@ from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import class ChartofAccountsImporter(Document): def validate(self): if self.import_file: - get_coa( - "Chart of Accounts Importer", "All Accounts", file_name=self.import_file, for_validate=1 - ) + get_coa("Chart of Accounts Importer", "All Accounts", file_name=self.import_file, for_validate=1) def validate_columns(data): @@ -104,7 +102,7 @@ def generate_data_from_csv(file_doc, as_dict=False): file_path = file_doc.get_full_path() data = [] - with open(file_path, "r") as in_file: + with open(file_path) as in_file: csv_reader = list(csv.reader(in_file)) headers = csv_reader[0] del csv_reader[0] # delete top row and headers row @@ -203,10 +201,10 @@ def build_forest(data): for row in data: account_name, parent_account, account_number, parent_account_number = row[0:4] if account_number: - account_name = "{} - {}".format(account_number, account_name) + account_name = f"{account_number} - {account_name}" if parent_account_number: parent_account_number = cstr(parent_account_number).strip() - parent_account = "{} - {}".format(parent_account_number, parent_account) + parent_account = f"{parent_account_number} - {parent_account}" if parent_account == account_name == child: return [parent_account] @@ -218,7 +216,7 @@ def build_forest(data): frappe.bold(parent_account) ) ) - return [child] + parent_account_list + return [child, *parent_account_list] charts_map, paths = {}, [] @@ -238,12 +236,12 @@ def build_forest(data): ) = i if not account_name: - error_messages.append("Row {0}: Please enter Account Name".format(line_no)) + error_messages.append(f"Row {line_no}: Please enter Account Name") name = account_name if account_number: account_number = cstr(account_number).strip() - account_name = "{} - {}".format(account_number, account_name) + account_name = f"{account_number} - {account_name}" charts_map[account_name] = {} charts_map[account_name]["account_name"] = name @@ -340,9 +338,9 @@ def get_template(template_type, company): def get_sample_template(writer, company): currency = frappe.db.get_value("Company", company, "default_currency") - with open(os.path.join(os.path.dirname(__file__), "coa_sample_template.csv"), "r") as f: + with open(os.path.join(os.path.dirname(__file__), "coa_sample_template.csv")) as f: for row in f: - row = row.strip().split(",") + [currency] + row = [*row.strip().split(","), currency] writer.writerow(row) return writer @@ -451,7 +449,7 @@ def unset_existing_data(company): "Purchase Taxes and Charges Template", ]: frappe.db.sql( - '''delete from `tab{0}` where `company`="%s"'''.format(doctype) % (company) # nosec + f'''delete from `tab{doctype}` where `company`="%s"''' % (company) # nosec ) diff --git a/erpnext/accounts/doctype/cheque_print_template/cheque_print_template.py b/erpnext/accounts/doctype/cheque_print_template/cheque_print_template.py index f8ac66444b4..9851c4c5a85 100644 --- a/erpnext/accounts/doctype/cheque_print_template/cheque_print_template.py +++ b/erpnext/accounts/doctype/cheque_print_template/cheque_print_template.py @@ -31,71 +31,71 @@ def create_or_update_cheque_print_format(template_name): cheque_print.html = """ -
-
- +
+ - %(message_to_show)s + {message_to_show} - - {{ frappe.utils.formatdate(doc.reference_date) or '' }} + {{{{ frappe.utils.formatdate(doc.reference_date) or '' }}}} - - {{ doc.account_no or '' }} + {{{{ doc.account_no or '' }}}} - - {{doc.party_name}} + {{{{doc.party_name}}}} - - {{frappe.utils.money_in_words(doc.base_paid_amount or doc.base_received_amount)}} + + {{{{frappe.utils.money_in_words(doc.base_paid_amount or doc.base_received_amount)}}}} - - {{doc.get_formatted("base_paid_amount") or doc.get_formatted("base_received_amount")}} + {{{{doc.get_formatted("base_paid_amount") or doc.get_formatted("base_received_amount")}}}} - - {{doc.company}} + {{{{doc.company}}}}
-
""" % { - "starting_position_from_top_edge": doc.starting_position_from_top_edge +
""".format( + starting_position_from_top_edge=doc.starting_position_from_top_edge if doc.cheque_size == "A4" else 0.0, - "cheque_width": doc.cheque_width, - "cheque_height": doc.cheque_height, - "acc_pay_dist_from_top_edge": doc.acc_pay_dist_from_top_edge, - "acc_pay_dist_from_left_edge": doc.acc_pay_dist_from_left_edge, - "message_to_show": doc.message_to_show if doc.message_to_show else _("Account Pay Only"), - "date_dist_from_top_edge": doc.date_dist_from_top_edge, - "date_dist_from_left_edge": doc.date_dist_from_left_edge, - "acc_no_dist_from_top_edge": doc.acc_no_dist_from_top_edge, - "acc_no_dist_from_left_edge": doc.acc_no_dist_from_left_edge, - "payer_name_from_top_edge": doc.payer_name_from_top_edge, - "payer_name_from_left_edge": doc.payer_name_from_left_edge, - "amt_in_words_from_top_edge": doc.amt_in_words_from_top_edge, - "amt_in_words_from_left_edge": doc.amt_in_words_from_left_edge, - "amt_in_word_width": doc.amt_in_word_width, - "amt_in_words_line_spacing": doc.amt_in_words_line_spacing, - "amt_in_figures_from_top_edge": doc.amt_in_figures_from_top_edge, - "amt_in_figures_from_left_edge": doc.amt_in_figures_from_left_edge, - "signatory_from_top_edge": doc.signatory_from_top_edge, - "signatory_from_left_edge": doc.signatory_from_left_edge, - } + cheque_width=doc.cheque_width, + cheque_height=doc.cheque_height, + acc_pay_dist_from_top_edge=doc.acc_pay_dist_from_top_edge, + acc_pay_dist_from_left_edge=doc.acc_pay_dist_from_left_edge, + message_to_show=doc.message_to_show if doc.message_to_show else _("Account Pay Only"), + date_dist_from_top_edge=doc.date_dist_from_top_edge, + date_dist_from_left_edge=doc.date_dist_from_left_edge, + acc_no_dist_from_top_edge=doc.acc_no_dist_from_top_edge, + acc_no_dist_from_left_edge=doc.acc_no_dist_from_left_edge, + payer_name_from_top_edge=doc.payer_name_from_top_edge, + payer_name_from_left_edge=doc.payer_name_from_left_edge, + amt_in_words_from_top_edge=doc.amt_in_words_from_top_edge, + amt_in_words_from_left_edge=doc.amt_in_words_from_left_edge, + amt_in_word_width=doc.amt_in_word_width, + amt_in_words_line_spacing=doc.amt_in_words_line_spacing, + amt_in_figures_from_top_edge=doc.amt_in_figures_from_top_edge, + amt_in_figures_from_left_edge=doc.amt_in_figures_from_left_edge, + signatory_from_top_edge=doc.signatory_from_top_edge, + signatory_from_left_edge=doc.signatory_from_left_edge, + ) cheque_print.save(ignore_permissions=True) diff --git a/erpnext/accounts/doctype/cost_center/cost_center.py b/erpnext/accounts/doctype/cost_center/cost_center.py index e8b34bbf034..ec6c17ad639 100644 --- a/erpnext/accounts/doctype/cost_center/cost_center.py +++ b/erpnext/accounts/doctype/cost_center/cost_center.py @@ -15,9 +15,7 @@ class CostCenter(NestedSet): def autoname(self): from erpnext.accounts.utils import get_autoname_with_number - self.name = get_autoname_with_number( - self.cost_center_number, self.cost_center_name, self.company - ) + self.name = get_autoname_with_number(self.cost_center_number, self.cost_center_name, self.company) def validate(self): self.validate_mandatory() @@ -90,14 +88,14 @@ class CostCenter(NestedSet): new_cost_center = get_name_with_abbr(newdn, self.company) # Validate properties before merging - super(CostCenter, self).before_rename(olddn, new_cost_center, merge, "is_group") + super().before_rename(olddn, new_cost_center, merge, "is_group") if not merge: new_cost_center = get_name_with_number(new_cost_center, self.cost_center_number) return new_cost_center def after_rename(self, olddn, newdn, merge=False): - super(CostCenter, self).after_rename(olddn, newdn, merge) + super().after_rename(olddn, newdn, merge) if not merge: new_cost_center = frappe.db.get_value( diff --git a/erpnext/accounts/doctype/cost_center/test_cost_center.py b/erpnext/accounts/doctype/cost_center/test_cost_center.py index 2ec16092d4d..7d01918fb54 100644 --- a/erpnext/accounts/doctype/cost_center/test_cost_center.py +++ b/erpnext/accounts/doctype/cost_center/test_cost_center.py @@ -10,7 +10,6 @@ test_records = frappe.get_test_records("Cost Center") class TestCostCenter(unittest.TestCase): def test_cost_center_creation_against_child_node(self): - if not frappe.db.get_value("Cost Center", {"name": "_Test Cost Center 2 - _TC"}): frappe.get_doc(test_records[1]).insert() diff --git a/erpnext/accounts/doctype/cost_center_allocation/cost_center_allocation.py b/erpnext/accounts/doctype/cost_center_allocation/cost_center_allocation.py index 54ffe21a152..c6cf232ceb8 100644 --- a/erpnext/accounts/doctype/cost_center_allocation/cost_center_allocation.py +++ b/erpnext/accounts/doctype/cost_center_allocation/cost_center_allocation.py @@ -29,7 +29,7 @@ class InvalidDateError(frappe.ValidationError): class CostCenterAllocation(Document): def __init__(self, *args, **kwargs): - super(CostCenterAllocation, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._skip_from_date_validation = False def validate(self): @@ -44,9 +44,7 @@ class CostCenterAllocation(Document): total_percentage = sum([d.percentage for d in self.get("allocation_percentages", [])]) if total_percentage != 100: - frappe.throw( - _("Total percentage against cost centers should be 100"), WrongPercentageAllocation - ) + frappe.throw(_("Total percentage against cost centers should be 100"), WrongPercentageAllocation) def validate_from_date_based_on_existing_gle(self): # Check if GLE exists against the main cost center diff --git a/erpnext/accounts/doctype/currency_exchange_settings/currency_exchange_settings.py b/erpnext/accounts/doctype/currency_exchange_settings/currency_exchange_settings.py index 7a420f984ad..39aff032b3d 100644 --- a/erpnext/accounts/doctype/currency_exchange_settings/currency_exchange_settings.py +++ b/erpnext/accounts/doctype/currency_exchange_settings/currency_exchange_settings.py @@ -18,7 +18,6 @@ class CurrencyExchangeSettings(Document): def set_parameters_and_result(self): if self.service_provider == "exchangerate.host": - if not self.access_key: frappe.throw( _("Access Key is required for Service Provider: {0}").format( @@ -53,9 +52,7 @@ class CurrencyExchangeSettings(Document): transaction_date=nowdate(), to_currency="INR", from_currency="USD" ) - api_url = self.api_endpoint.format( - transaction_date=nowdate(), to_currency="INR", from_currency="USD" - ) + api_url = self.api_endpoint.format(transaction_date=nowdate(), to_currency="INR", from_currency="USD") try: response = requests.get(api_url, params=params) @@ -75,14 +72,14 @@ class CurrencyExchangeSettings(Document): ] except Exception: frappe.throw(_("Invalid result key. Response:") + " " + response.text) - if not isinstance(value, (int, float)): + if not isinstance(value, int | float): frappe.throw(_("Returned exchange rate is neither integer not float.")) self.url = response.url @frappe.whitelist() -def get_api_endpoint(service_provider: str = None, use_http: bool = False): +def get_api_endpoint(service_provider: str | None = None, use_http: bool = False): if service_provider and service_provider in ["exchangerate.host", "frankfurter.app"]: if service_provider == "exchangerate.host": api = "api.exchangerate.host/convert" diff --git a/erpnext/accounts/doctype/exchange_rate_revaluation/exchange_rate_revaluation.py b/erpnext/accounts/doctype/exchange_rate_revaluation/exchange_rate_revaluation.py index 00d62f3f601..24a325b9164 100644 --- a/erpnext/accounts/doctype/exchange_rate_revaluation/exchange_rate_revaluation.py +++ b/erpnext/accounts/doctype/exchange_rate_revaluation/exchange_rate_revaluation.py @@ -246,7 +246,6 @@ class ExchangeRateRevaluation(Document): # Handle Accounts with '0' balance in Account/Base Currency for d in [x for x in account_details if x.zero_balance]: - if d.balance != 0: current_exchange_rate = new_exchange_rate = 0 @@ -259,7 +258,8 @@ class ExchangeRateRevaluation(Document): new_balance_in_account_currency = 0 current_exchange_rate = ( - calculate_exchange_rate_using_last_gle(company, d.account, d.party_type, d.party) or 0.0 + calculate_exchange_rate_using_last_gle(company, d.account, d.party_type, d.party) + or 0.0 ) gain_loss = new_balance_in_account_currency - ( @@ -313,9 +313,7 @@ class ExchangeRateRevaluation(Document): revaluation_jv = self.make_jv_for_revaluation() if revaluation_jv: - frappe.msgprint( - f"Revaluation Journal: {get_link_to_form('Journal Entry', revaluation_jv.name)}" - ) + frappe.msgprint(f"Revaluation Journal: {get_link_to_form('Journal Entry', revaluation_jv.name)}") return { "revaluation_jv": revaluation_jv.name if revaluation_jv else None, @@ -372,7 +370,8 @@ class ExchangeRateRevaluation(Document): journal_account.update( { dr_or_cr: flt( - abs(d.get("balance_in_account_currency")), d.precision("balance_in_account_currency") + abs(d.get("balance_in_account_currency")), + d.precision("balance_in_account_currency"), ), reverse_dr_or_cr: 0, "debit": 0, @@ -498,7 +497,9 @@ class ExchangeRateRevaluation(Document): abs(d.get("balance_in_account_currency")), d.precision("balance_in_account_currency") ), "cost_center": erpnext.get_default_cost_center(self.company), - "exchange_rate": flt(d.get("current_exchange_rate"), d.precision("current_exchange_rate")), + "exchange_rate": flt( + d.get("current_exchange_rate"), d.precision("current_exchange_rate") + ), "reference_type": "Exchange Rate Revaluation", "reference_name": self.name, } @@ -576,7 +577,7 @@ def calculate_exchange_rate_using_last_gle(company, account, party_type, party): @frappe.whitelist() def get_account_details( - company, posting_date, account, party_type=None, party=None, rounding_loss_allowance: float = None + company, posting_date, account, party_type=None, party=None, rounding_loss_allowance: float | None = None ): if not (company and posting_date): frappe.throw(_("Company and Posting Date is mandatory")) @@ -589,7 +590,7 @@ def get_account_details( frappe.throw(_("Party Type and Party is mandatory for {0} account").format(account_type)) account_details = {} - company_currency = erpnext.get_company_currency(company) + erpnext.get_company_currency(company) account_details = { "account_currency": account_currency, @@ -603,9 +604,7 @@ def get_account_details( rounding_loss_allowance=rounding_loss_allowance, ) - if account_balance and ( - account_balance[0].balance or account_balance[0].balance_in_account_currency - ): + if account_balance and (account_balance[0].balance or account_balance[0].balance_in_account_currency): if account_with_new_balance := ExchangeRateRevaluation.calculate_new_account_balance( company, posting_date, account_balance ): diff --git a/erpnext/accounts/doctype/exchange_rate_revaluation/test_exchange_rate_revaluation.py b/erpnext/accounts/doctype/exchange_rate_revaluation/test_exchange_rate_revaluation.py index ced04ced3fd..709be43e699 100644 --- a/erpnext/accounts/doctype/exchange_rate_revaluation/test_exchange_rate_revaluation.py +++ b/erpnext/accounts/doctype/exchange_rate_revaluation/test_exchange_rate_revaluation.py @@ -1,21 +1,14 @@ # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt -import unittest import frappe -from frappe import qb from frappe.tests.utils import FrappeTestCase, change_settings from frappe.utils import add_days, flt, today -from erpnext import get_default_cost_center from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry -from erpnext.accounts.doctype.payment_entry.test_payment_entry import create_payment_entry -from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import make_purchase_invoice from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice -from erpnext.accounts.party import get_party_account from erpnext.accounts.test.accounts_mixin import AccountsTestMixin -from erpnext.stock.doctype.item.test_item import create_item class TestExchangeRateRevaluation(AccountsTestMixin, FrappeTestCase): @@ -73,9 +66,7 @@ class TestExchangeRateRevaluation(AccountsTestMixin, FrappeTestCase): err.extend("accounts", accounts) row = err.accounts[0] row.new_exchange_rate = 85 - row.new_balance_in_base_currency = flt( - row.new_exchange_rate * flt(row.balance_in_account_currency) - ) + row.new_balance_in_base_currency = flt(row.new_exchange_rate * flt(row.balance_in_account_currency)) row.gain_loss = row.new_balance_in_base_currency - flt(row.balance_in_base_currency) err.set_total_gain_loss() err = err.save().submit() @@ -127,9 +118,9 @@ class TestExchangeRateRevaluation(AccountsTestMixin, FrappeTestCase): pe.save().submit() # Cancel the auto created gain/loss JE to simulate balance only in base currency - je = frappe.db.get_all( - "Journal Entry Account", filters={"reference_name": si.name}, pluck="parent" - )[0] + je = frappe.db.get_all("Journal Entry Account", filters={"reference_name": si.name}, pluck="parent")[ + 0 + ] frappe.get_doc("Journal Entry", je).cancel() err = frappe.new_doc("Exchange Rate Revaluation") @@ -235,9 +226,9 @@ class TestExchangeRateRevaluation(AccountsTestMixin, FrappeTestCase): self.assertEqual(flt(acc.debit, precision), 0.0) self.assertEqual(flt(acc.credit, precision), 0.0) - row = [x for x in je.accounts if x.account == self.debtors_usd][0] + row = next(x for x in je.accounts if x.account == self.debtors_usd) self.assertEqual(flt(row.credit_in_account_currency, precision), 5.0) # in USD - row = [x for x in je.accounts if x.account != self.debtors_usd][0] + row = next(x for x in je.accounts if x.account != self.debtors_usd) self.assertEqual(flt(row.debit_in_account_currency, precision), 421.06) # in INR # total_debit and total_credit will be 0.0, as JV is posting only to account currency fields @@ -294,5 +285,5 @@ class TestExchangeRateRevaluation(AccountsTestMixin, FrappeTestCase): "new_balance_in_account_currency": 100.0, } - for key, val in expected_data.items(): + for key, _val in expected_data.items(): self.assertEqual(expected_data.get(key), account_details.get(key)) diff --git a/erpnext/accounts/doctype/fiscal_year/fiscal_year.py b/erpnext/accounts/doctype/fiscal_year/fiscal_year.py index a945860a711..4acdd9a7e8e 100644 --- a/erpnext/accounts/doctype/fiscal_year/fiscal_year.py +++ b/erpnext/accounts/doctype/fiscal_year/fiscal_year.py @@ -98,9 +98,9 @@ class FiscalYear(Document): if overlap: frappe.throw( - _("Year start date or end date is overlapping with {0}. To avoid please set company").format( - existing.name - ), + _( + "Year start date or end date is overlapping with {0}. To avoid please set company" + ).format(existing.name), frappe.NameError, ) @@ -116,9 +116,9 @@ def check_duplicate_fiscal_year(doc): not frappe.flags.in_test ): frappe.throw( - _("Fiscal Year Start Date and Fiscal Year End Date are already set in Fiscal Year {0}").format( - fiscal_year - ) + _( + "Fiscal Year Start Date and Fiscal Year End Date are already set in Fiscal Year {0}" + ).format(fiscal_year) ) diff --git a/erpnext/accounts/doctype/gl_entry/gl_entry.py b/erpnext/accounts/doctype/gl_entry/gl_entry.py index 346fee81812..6ca5e6377c5 100644 --- a/erpnext/accounts/doctype/gl_entry/gl_entry.py +++ b/erpnext/accounts/doctype/gl_entry/gl_entry.py @@ -63,13 +63,18 @@ class GLEntry(Document): ]: # Update outstanding amt on against voucher if ( - self.against_voucher_type in ["Journal Entry", "Sales Invoice", "Purchase Invoice", "Fees"] + self.against_voucher_type + in ["Journal Entry", "Sales Invoice", "Purchase Invoice", "Fees"] and self.against_voucher and self.flags.update_outstanding == "Yes" and not frappe.flags.is_reverse_depr_entry ): update_outstanding_amt( - self.account, self.party_type, self.party, self.against_voucher_type, self.against_voucher + self.account, + self.party_type, + self.party, + self.against_voucher_type, + self.against_voucher, ) def check_mandatory(self): @@ -139,9 +144,9 @@ class GLEntry(Document): ): if not self.get(dimension.fieldname): frappe.throw( - _("Accounting Dimension {0} is required for 'Profit and Loss' account {1}.").format( - dimension.label, self.account - ) + _( + "Accounting Dimension {0} is required for 'Profit and Loss' account {1}." + ).format(dimension.label, self.account) ) if ( @@ -153,9 +158,9 @@ class GLEntry(Document): ): if not self.get(dimension.fieldname): frappe.throw( - _("Accounting Dimension {0} is required for 'Balance Sheet' account {1}.").format( - dimension.label, self.account - ) + _( + "Accounting Dimension {0} is required for 'Balance Sheet' account {1}." + ).format(dimension.label, self.account) ) def check_pl_account(self): @@ -203,9 +208,7 @@ class GLEntry(Document): if not self.cost_center: return - is_group, company = frappe.get_cached_value( - "Cost Center", self.cost_center, ["is_group", "company"] - ) + is_group, company = frappe.get_cached_value("Cost Center", self.cost_center, ["is_group", "company"]) if company != self.company: frappe.throw( @@ -274,7 +277,7 @@ def update_outstanding_amt( account, party_type, party, against_voucher_type, against_voucher, on_cancel=False ): if party_type and party: - party_condition = " and party_type={0} and party={1}".format( + party_condition = " and party_type={} and party={}".format( frappe.db.escape(party_type), frappe.db.escape(party) ) else: @@ -282,23 +285,19 @@ def update_outstanding_amt( if against_voucher_type == "Sales Invoice": party_account = frappe.get_cached_value(against_voucher_type, against_voucher, "debit_to") - account_condition = "and account in ({0}, {1})".format( - frappe.db.escape(account), frappe.db.escape(party_account) - ) + account_condition = f"and account in ({frappe.db.escape(account)}, {frappe.db.escape(party_account)})" else: - account_condition = " and account = {0}".format(frappe.db.escape(account)) + account_condition = f" and account = {frappe.db.escape(account)}" # get final outstanding amt bal = flt( frappe.db.sql( - """ + f""" select sum(debit_in_account_currency) - sum(credit_in_account_currency) from `tabGL Entry` where against_voucher_type=%s and against_voucher=%s and voucher_type != 'Invoice Discounting' - {0} {1}""".format( - party_condition, account_condition - ), + {party_condition} {account_condition}""", (against_voucher_type, against_voucher), )[0][0] or 0.0 @@ -309,12 +308,10 @@ def update_outstanding_amt( elif against_voucher_type == "Journal Entry": against_voucher_amount = flt( frappe.db.sql( - """ + f""" select sum(debit_in_account_currency) - sum(credit_in_account_currency) from `tabGL Entry` where voucher_type = 'Journal Entry' and voucher_no = %s - and account = %s and (against_voucher is null or against_voucher='') {0}""".format( - party_condition - ), + and account = %s and (against_voucher is null or against_voucher='') {party_condition}""", (against_voucher, account), )[0][0] ) @@ -333,7 +330,9 @@ def update_outstanding_amt( # Validation : Outstanding can not be negative for JV if bal < 0 and not on_cancel: frappe.throw( - _("Outstanding for {0} cannot be less than zero ({1})").format(against_voucher, fmt_money(bal)) + _("Outstanding for {0} cannot be less than zero ({1})").format( + against_voucher, fmt_money(bal) + ) ) if against_voucher_type in ["Sales Invoice", "Purchase Invoice", "Fees"]: @@ -406,7 +405,7 @@ def rename_temporarily_named_docs(doctype): set_name_from_naming_options(frappe.get_meta(doctype).autoname, doc) newname = doc.name frappe.db.sql( - "UPDATE `tab{}` SET name = %s, to_rename = 0 where name = %s".format(doctype), + f"UPDATE `tab{doctype}` SET name = %s, to_rename = 0 where name = %s", (newname, oldname), auto_commit=True, ) diff --git a/erpnext/accounts/doctype/gl_entry/test_gl_entry.py b/erpnext/accounts/doctype/gl_entry/test_gl_entry.py index b188b09843a..3edfd67b005 100644 --- a/erpnext/accounts/doctype/gl_entry/test_gl_entry.py +++ b/erpnext/accounts/doctype/gl_entry/test_gl_entry.py @@ -14,9 +14,7 @@ from erpnext.accounts.doctype.journal_entry.test_journal_entry import make_journ class TestGLEntry(unittest.TestCase): def test_round_off_entry(self): frappe.db.set_value("Company", "_Test Company", "round_off_account", "_Test Write Off - _TC") - frappe.db.set_value( - "Company", "_Test Company", "round_off_cost_center", "_Test Cost Center - _TC" - ) + frappe.db.set_value("Company", "_Test Company", "round_off_cost_center", "_Test Cost Center - _TC") jv = make_journal_entry( "_Test Account Cost for Goods Sold - _TC", @@ -73,7 +71,9 @@ class TestGLEntry(unittest.TestCase): ) self.assertTrue(all(entry.to_rename == 0 for entry in new_gl_entries)) - self.assertTrue(all(new.name != old.name for new, old in zip(gl_entries, new_gl_entries))) + self.assertTrue( + all(new.name != old.name for new, old in zip(gl_entries, new_gl_entries, strict=False)) + ) new_naming_series_current_value = frappe.db.sql( "SELECT current from tabSeries where name = %s", naming_series diff --git a/erpnext/accounts/doctype/invoice_discounting/invoice_discounting.py b/erpnext/accounts/doctype/invoice_discounting/invoice_discounting.py index 5bd4585a9a8..2322d68c000 100644 --- a/erpnext/accounts/doctype/invoice_discounting/invoice_discounting.py +++ b/erpnext/accounts/doctype/invoice_discounting/invoice_discounting.py @@ -55,9 +55,7 @@ class InvoiceDiscounting(AccountsController): frappe.throw( _( "Row({0}): Outstanding Amount cannot be greater than actual Outstanding Amount {1} in {2}" - ).format( - record.idx, frappe.bold(actual_outstanding), frappe.bold(record.sales_invoice) - ) + ).format(record.idx, frappe.bold(actual_outstanding), frappe.bold(record.sales_invoice)) ) def calculate_total_amount(self): @@ -77,7 +75,9 @@ class InvoiceDiscounting(AccountsController): self.status = status self.db_set("status", status) for d in self.invoices: - frappe.get_doc("Sales Invoice", d.sales_invoice).set_status(update=True, update_modified=False) + frappe.get_doc("Sales Invoice", d.sales_invoice).set_status( + update=True, update_modified=False + ) else: self.status = "Draft" if self.docstatus == 1: diff --git a/erpnext/accounts/doctype/invoice_discounting/test_invoice_discounting.py b/erpnext/accounts/doctype/invoice_discounting/test_invoice_discounting.py index a85fdfcad7f..65e3c3dcd6a 100644 --- a/erpnext/accounts/doctype/invoice_discounting/test_invoice_discounting.py +++ b/erpnext/accounts/doctype/invoice_discounting/test_invoice_discounting.py @@ -75,7 +75,7 @@ class TestInvoiceDiscounting(unittest.TestCase): gle = get_gl_entries("Invoice Discounting", inv_disc.name) expected_gle = {inv.debit_to: [0.0, 200], self.ar_credit: [200, 0.0]} - for i, gle in enumerate(gle): + for _i, gle in enumerate(gle): self.assertEqual([gle.debit, gle.credit], expected_gle.get(gle.account)) def test_loan_on_submit(self): @@ -92,9 +92,7 @@ class TestInvoiceDiscounting(unittest.TestCase): period=60, ) self.assertEqual(inv_disc.status, "Sanctioned") - self.assertEqual( - inv_disc.loan_end_date, add_days(inv_disc.loan_start_date, inv_disc.loan_period) - ) + self.assertEqual(inv_disc.loan_end_date, add_days(inv_disc.loan_start_date, inv_disc.loan_period)) def test_on_disbursed(self): inv = create_sales_invoice(rate=500) @@ -262,13 +260,9 @@ class TestInvoiceDiscounting(unittest.TestCase): je_on_payment.submit() self.assertEqual(je_on_payment.accounts[0].account, self.ar_discounted) - self.assertEqual( - je_on_payment.accounts[0].credit_in_account_currency, flt(inv.outstanding_amount) - ) + self.assertEqual(je_on_payment.accounts[0].credit_in_account_currency, flt(inv.outstanding_amount)) self.assertEqual(je_on_payment.accounts[1].account, self.bank_account) - self.assertEqual( - je_on_payment.accounts[1].debit_in_account_currency, flt(inv.outstanding_amount) - ) + self.assertEqual(je_on_payment.accounts[1].debit_in_account_currency, flt(inv.outstanding_amount)) inv.reload() self.assertEqual(inv.outstanding_amount, 0) @@ -304,13 +298,9 @@ class TestInvoiceDiscounting(unittest.TestCase): je_on_payment.submit() self.assertEqual(je_on_payment.accounts[0].account, self.ar_unpaid) - self.assertEqual( - je_on_payment.accounts[0].credit_in_account_currency, flt(inv.outstanding_amount) - ) + self.assertEqual(je_on_payment.accounts[0].credit_in_account_currency, flt(inv.outstanding_amount)) self.assertEqual(je_on_payment.accounts[1].account, self.bank_account) - self.assertEqual( - je_on_payment.accounts[1].debit_in_account_currency, flt(inv.outstanding_amount) - ) + self.assertEqual(je_on_payment.accounts[1].debit_in_account_currency, flt(inv.outstanding_amount)) inv.reload() self.assertEqual(inv.outstanding_amount, 0) diff --git a/erpnext/accounts/doctype/item_tax_template/item_tax_template.py b/erpnext/accounts/doctype/item_tax_template/item_tax_template.py index 23f36ec6d8d..755ff490885 100644 --- a/erpnext/accounts/doctype/item_tax_template/item_tax_template.py +++ b/erpnext/accounts/doctype/item_tax_template/item_tax_template.py @@ -14,7 +14,7 @@ class ItemTaxTemplate(Document): def autoname(self): if self.company and self.title: abbr = frappe.get_cached_value("Company", self.company, "abbr") - self.name = "{0} - {1}".format(self.title, abbr) + self.name = f"{self.title} - {abbr}" def validate_tax_accounts(self): """Check whether Tax Rate is not entered twice for same Tax Type""" diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.py b/erpnext/accounts/doctype/journal_entry/journal_entry.py index 88388128653..b4fb13e42c3 100644 --- a/erpnext/accounts/doctype/journal_entry/journal_entry.py +++ b/erpnext/accounts/doctype/journal_entry/journal_entry.py @@ -33,7 +33,7 @@ class StockAccountInvalidTransaction(frappe.ValidationError): class JournalEntry(AccountsController): def __init__(self, *args, **kwargs): - super(JournalEntry, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def get_feed(self): return self.voucher_type @@ -102,7 +102,7 @@ class JournalEntry(AccountsController): def on_cancel(self): # References for this Journal are removed on the `on_cancel` event in accounts_controller - super(JournalEntry, self).on_cancel() + super().on_cancel() self.ignore_linked_doctypes = ( "GL Entry", "Stock Ledger Entry", @@ -137,10 +137,7 @@ class JournalEntry(AccountsController): frappe.get_doc(voucher_type, voucher_no).set_total_advance_paid() def validate_inter_company_accounts(self): - if ( - self.voucher_type == "Inter Company Journal Entry" - and self.inter_company_journal_entry_reference - ): + if self.voucher_type == "Inter Company Journal Entry" and self.inter_company_journal_entry_reference: doc = frappe.get_doc("Journal Entry", self.inter_company_journal_entry_reference) account_currency = frappe.get_cached_value("Company", self.company, "default_currency") previous_account_currency = frappe.get_cached_value("Company", doc.company, "default_currency") @@ -286,10 +283,7 @@ class JournalEntry(AccountsController): asset.set_status() def update_inter_company_jv(self): - if ( - self.voucher_type == "Inter Company Journal Entry" - and self.inter_company_journal_entry_reference - ): + if self.voucher_type == "Inter Company Journal Entry" and self.inter_company_journal_entry_reference: frappe.db.set_value( "Journal Entry", self.inter_company_journal_entry_reference, @@ -317,17 +311,25 @@ class JournalEntry(AccountsController): if d.account == inv_disc_doc.short_term_loan and d.reference_name == inv_disc: if self.docstatus == 1: if d.credit > 0: - _validate_invoice_discounting_status(inv_disc, inv_disc_doc.status, "Sanctioned", d.idx) + _validate_invoice_discounting_status( + inv_disc, inv_disc_doc.status, "Sanctioned", d.idx + ) status = "Disbursed" elif d.debit > 0: - _validate_invoice_discounting_status(inv_disc, inv_disc_doc.status, "Disbursed", d.idx) + _validate_invoice_discounting_status( + inv_disc, inv_disc_doc.status, "Disbursed", d.idx + ) status = "Settled" else: if d.credit > 0: - _validate_invoice_discounting_status(inv_disc, inv_disc_doc.status, "Disbursed", d.idx) + _validate_invoice_discounting_status( + inv_disc, inv_disc_doc.status, "Disbursed", d.idx + ) status = "Sanctioned" elif d.debit > 0: - _validate_invoice_discounting_status(inv_disc, inv_disc_doc.status, "Settled", d.idx) + _validate_invoice_discounting_status( + inv_disc, inv_disc_doc.status, "Settled", d.idx + ) status = "Disbursed" break if status: @@ -384,10 +386,7 @@ class JournalEntry(AccountsController): ) def unlink_inter_company_jv(self): - if ( - self.voucher_type == "Inter Company Journal Entry" - and self.inter_company_journal_entry_reference - ): + if self.voucher_type == "Inter Company Journal Entry" and self.inter_company_journal_entry_reference: frappe.db.set_value( "Journal Entry", self.inter_company_journal_entry_reference, @@ -409,9 +408,9 @@ class JournalEntry(AccountsController): if account_type in ["Receivable", "Payable"]: if not (d.party_type and d.party): frappe.throw( - _("Row {0}: Party Type and Party is required for Receivable / Payable account {1}").format( - d.idx, d.account - ) + _( + "Row {0}: Party Type and Party is required for Receivable / Payable account {1}" + ).format(d.idx, d.account) ) elif ( d.party_type @@ -476,16 +475,18 @@ class JournalEntry(AccountsController): def system_generated_gain_loss(self): return ( - self.voucher_type == "Exchange Gain Or Loss" - and self.multi_currency - and self.is_system_generated + self.voucher_type == "Exchange Gain Or Loss" and self.multi_currency and self.is_system_generated ) def validate_against_jv(self): for d in self.get("accounts"): if d.reference_type == "Journal Entry": account_root_type = frappe.get_cached_value("Account", d.account, "root_type") - if account_root_type == "Asset" and flt(d.debit) > 0 and not self.system_generated_gain_loss(): + if ( + account_root_type == "Asset" + and flt(d.debit) > 0 + and not self.system_generated_gain_loss() + ): frappe.throw( _( "Row #{0}: For {1}, you can select reference document only if account gets credited" @@ -567,11 +568,13 @@ class JournalEntry(AccountsController): if d.reference_type == "Purchase Order" and flt(d.credit) > 0: frappe.throw( - _("Row {0}: Credit entry can not be linked with a {1}").format(d.idx, d.reference_type) + _("Row {0}: Credit entry can not be linked with a {1}").format( + d.idx, d.reference_type + ) ) # set totals - if not d.reference_name in self.reference_totals: + if d.reference_name not in self.reference_totals: self.reference_totals[d.reference_name] = 0.0 if self.voucher_type not in ("Deferred Revenue", "Deferred Expense"): @@ -589,7 +592,10 @@ class JournalEntry(AccountsController): # check if party and account match if d.reference_type in ("Sales Invoice", "Purchase Invoice"): - if self.voucher_type in ("Deferred Revenue", "Deferred Expense") and d.reference_detail_no: + if ( + self.voucher_type in ("Deferred Revenue", "Deferred Expense") + and d.reference_detail_no + ): debit_or_credit = "Debit" if d.debit else "Credit" party_account = get_deferred_booking_accounts( d.reference_type, d.reference_detail_no, debit_or_credit @@ -598,7 +604,8 @@ class JournalEntry(AccountsController): else: if d.reference_type == "Sales Invoice": party_account = ( - get_party_account_based_on_invoice_discounting(d.reference_name) or against_voucher[1] + get_party_account_based_on_invoice_discounting(d.reference_name) + or against_voucher[1] ) else: party_account = against_voucher[1] @@ -722,7 +729,9 @@ class JournalEntry(AccountsController): if not (self.voucher_type == "Exchange Gain Or Loss" and self.multi_currency): if self.difference: frappe.throw( - _("Total Debit must be equal to Total Credit. The difference is {0}").format(self.difference) + _("Total Debit must be equal to Total Credit. The difference is {0}").format( + self.difference + ) ) def set_total_debit_credit(self): @@ -786,7 +795,6 @@ class JournalEntry(AccountsController): and self.posting_date ) ): - ignore_exchange_rate = False if self.get("flags") and self.flags.get("ignore_exchange_rate"): ignore_exchange_rate = True @@ -1032,27 +1040,21 @@ class JournalEntry(AccountsController): self.validate_total_debit_and_credit() def get_values(self): - cond = ( - " and outstanding_amount <= {0}".format(self.write_off_amount) - if flt(self.write_off_amount) > 0 - else "" - ) + cond = f" and outstanding_amount <= {self.write_off_amount}" if flt(self.write_off_amount) > 0 else "" if self.write_off_based_on == "Accounts Receivable": return frappe.db.sql( """select name, debit_to as account, customer as party, outstanding_amount - from `tabSales Invoice` where docstatus = 1 and company = %s - and outstanding_amount > 0 %s""" - % ("%s", cond), + from `tabSales Invoice` where docstatus = 1 and company = {} + and outstanding_amount > 0 {}""".format("%s", cond), self.company, as_dict=True, ) elif self.write_off_based_on == "Accounts Payable": return frappe.db.sql( """select name, credit_to as account, supplier as party, outstanding_amount - from `tabPurchase Invoice` where docstatus = 1 and company = %s - and outstanding_amount > 0 %s""" - % ("%s", cond), + from `tabPurchase Invoice` where docstatus = 1 and company = {} + and outstanding_amount > 0 {}""".format("%s", cond), self.company, as_dict=True, ) @@ -1161,7 +1163,7 @@ def get_payment_entry_against_order( "amount_field_bank": amount_field_bank, "amount": amount, "debit_in_account_currency": debit_in_account_currency, - "remarks": "Advance Payment received against {0} {1}".format(dt, dn), + "remarks": f"Advance Payment received against {dt} {dn}", "is_advance": "Yes", "bank_account": bank_account, "journal_entry": journal_entry, @@ -1200,7 +1202,7 @@ def get_payment_entry_against_invoice( "amount_field_bank": amount_field_bank, "amount": amount if amount else abs(ref_doc.outstanding_amount), "debit_in_account_currency": debit_in_account_currency, - "remarks": "Payment received against {0} {1}. {2}".format(dt, dn, ref_doc.remarks), + "remarks": f"Payment received against {dt} {dn}. {ref_doc.remarks}", "is_advance": "No", "bank_account": bank_account, "journal_entry": journal_entry, @@ -1226,9 +1228,7 @@ def get_payment_entry(ref_doc, args): ) je = frappe.new_doc("Journal Entry") - je.update( - {"voucher_type": "Bank Entry", "company": ref_doc.company, "remark": args.get("remarks")} - ) + je.update({"voucher_type": "Bank Entry", "company": ref_doc.company, "remark": args.get("remarks")}) party_row = je.append( "accounts", @@ -1251,9 +1251,7 @@ def get_payment_entry(ref_doc, args): bank_row = je.append("accounts") # Make it bank_details - bank_account = get_default_bank_cash_account( - ref_doc.company, "Bank", account=args.get("bank_account") - ) + bank_account = get_default_bank_cash_account(ref_doc.company, "Bank", account=args.get("bank_account")) if bank_account: bank_row.update(bank_account) # Modified to include the posting date for which the exchange rate is required. @@ -1293,7 +1291,7 @@ def get_against_jv(doctype, txt, searchfield, start, page_len, filters): return [] return frappe.db.sql( - """ + f""" SELECT jv.name, jv.posting_date, jv.user_remark FROM `tabJournal Entry` jv, `tabJournal Entry Account` jv_detail WHERE jv_detail.parent = jv.name @@ -1304,16 +1302,14 @@ def get_against_jv(doctype, txt, searchfield, start, page_len, filters): OR jv_detail.reference_type = '' ) AND jv.docstatus = 1 - AND jv.`{0}` LIKE %(txt)s + AND jv.`{searchfield}` LIKE %(txt)s ORDER BY jv.name DESC LIMIT %(limit)s offset %(offset)s - """.format( - searchfield - ), + """, dict( account=filters.get("account"), party=cstr(filters.get("party")), - txt="%{0}%".format(txt), + txt=f"%{txt}%", offset=start, limit=page_len, ), @@ -1335,19 +1331,15 @@ def get_outstanding(args): condition = " and party=%(party)s" if args.get("party") else "" against_jv_amount = frappe.db.sql( - """ + f""" select sum(debit_in_account_currency) - sum(credit_in_account_currency) - from `tabJournal Entry Account` where parent=%(docname)s and account=%(account)s {0} - and (reference_type is null or reference_type = '')""".format( - condition - ), + from `tabJournal Entry Account` where parent=%(docname)s and account=%(account)s {condition} + and (reference_type is null or reference_type = '')""", args, ) against_jv_amount = flt(against_jv_amount[0][0]) if against_jv_amount else 0 - amount_field = ( - "credit_in_account_currency" if against_jv_amount > 0 else "debit_in_account_currency" - ) + amount_field = "credit_in_account_currency" if against_jv_amount > 0 else "debit_in_account_currency" return {amount_field: abs(against_jv_amount)} elif args.get("doctype") in ("Sales Invoice", "Purchase Invoice"): party_type = "Customer" if args.get("doctype") == "Sales Invoice" else "Supplier" @@ -1360,9 +1352,7 @@ def get_outstanding(args): due_date = invoice.get("due_date") - exchange_rate = ( - invoice.conversion_rate if (args.get("account_currency") != company_currency) else 1 - ) + exchange_rate = invoice.conversion_rate if (args.get("account_currency") != company_currency) else 1 if args["doctype"] == "Sales Invoice": amount_field = ( @@ -1400,17 +1390,13 @@ def get_party_account_and_currency(company, party_type, party): @frappe.whitelist() -def get_account_details_and_party_type( - account, date, company, debit=None, credit=None, exchange_rate=None -): +def get_account_details_and_party_type(account, date, company, debit=None, credit=None, exchange_rate=None): """Returns dict of account details and party type to be set in Journal Entry on selection of account.""" if not frappe.has_permission("Account"): frappe.msgprint(_("No Permission"), raise_exception=1) company_currency = erpnext.get_company_currency(company) - account_details = frappe.db.get_value( - "Account", account, ["account_type", "account_currency"], as_dict=1 - ) + account_details = frappe.db.get_value("Account", account, ["account_type", "account_currency"], as_dict=1) if not account_details: return diff --git a/erpnext/accounts/doctype/journal_entry/test_journal_entry.py b/erpnext/accounts/doctype/journal_entry/test_journal_entry.py index e44ebc6afce..979f964b62a 100644 --- a/erpnext/accounts/doctype/journal_entry/test_journal_entry.py +++ b/erpnext/accounts/doctype/journal_entry/test_journal_entry.py @@ -69,10 +69,8 @@ class TestJournalEntry(unittest.TestCase): self.assertTrue( frappe.db.sql( - """select name from `tabJournal Entry Account` - where reference_type = %s and reference_name = %s and {0}=400""".format( - dr_or_cr - ), + f"""select name from `tabJournal Entry Account` + where reference_type = %s and reference_name = %s and {dr_or_cr}=400""", (submitted_voucher.doctype, submitted_voucher.name), ) ) @@ -84,9 +82,8 @@ class TestJournalEntry(unittest.TestCase): def advance_paid_testcase(self, base_jv, test_voucher, dr_or_cr): # Test advance paid field advance_paid = frappe.db.sql( - """select advance_paid from `tab%s` - where name=%s""" - % (test_voucher.doctype, "%s"), + """select advance_paid from `tab{}` + where name={}""".format(test_voucher.doctype, "%s"), (test_voucher.name), ) payment_against_order = base_jv.get("accounts")[0].get(dr_or_cr) @@ -159,9 +156,7 @@ class TestJournalEntry(unittest.TestCase): jv.cancel() def test_multi_currency(self): - jv = make_journal_entry( - "_Test Bank USD - _TC", "_Test Bank - _TC", 100, exchange_rate=50, save=False - ) + jv = make_journal_entry("_Test Bank USD - _TC", "_Test Bank - _TC", 100, exchange_rate=50, save=False) jv.get("accounts")[1].credit_in_account_currency = 5000 jv.submit() @@ -201,7 +196,7 @@ class TestJournalEntry(unittest.TestCase): "credit", "credit_in_account_currency", ): - for i, gle in enumerate(gl_entries): + for _i, gle in enumerate(gl_entries): self.assertEqual(expected_values[gle.account][field], gle[field]) # cancel @@ -263,7 +258,7 @@ class TestJournalEntry(unittest.TestCase): "credit", "credit_in_account_currency", ): - for i, gle in enumerate(gl_entries): + for _i, gle in enumerate(gl_entries): self.assertEqual(expected_values[gle.account][field], gle[field]) def test_disallow_change_in_account_currency_for_a_party(self): diff --git a/erpnext/accounts/doctype/ledger_merge/test_ledger_merge.py b/erpnext/accounts/doctype/ledger_merge/test_ledger_merge.py index 992ce9ede5d..dccd73c62a9 100644 --- a/erpnext/accounts/doctype/ledger_merge/test_ledger_merge.py +++ b/erpnext/accounts/doctype/ledger_merge/test_ledger_merge.py @@ -83,7 +83,10 @@ class TestLedgerMerge(unittest.TestCase): "account": "Indirect Income - _TC", "merge_accounts": [ {"account": "Indirect Test Income - _TC", "account_name": "Indirect Test Income"}, - {"account": "Administrative Test Income - _TC", "account_name": "Administrative Test Income"}, + { + "account": "Administrative Test Income - _TC", + "account_name": "Administrative Test Income", + }, ], } ).insert(ignore_permissions=True) diff --git a/erpnext/accounts/doctype/loyalty_program/loyalty_program.py b/erpnext/accounts/doctype/loyalty_program/loyalty_program.py index a134f746635..8da5a3f909f 100644 --- a/erpnext/accounts/doctype/loyalty_program/loyalty_program.py +++ b/erpnext/accounts/doctype/loyalty_program/loyalty_program.py @@ -25,13 +25,11 @@ def get_loyalty_details( condition += " and expiry_date>='%s' " % expiry_date loyalty_point_details = frappe.db.sql( - """select sum(loyalty_points) as loyalty_points, + f"""select sum(loyalty_points) as loyalty_points, sum(purchase_amount) as total_spent from `tabLoyalty Point Entry` where customer=%s and loyalty_program=%s and posting_date <= %s {condition} - group by customer""".format( - condition=condition - ), + group by customer""", (customer, loyalty_program, expiry_date), as_dict=1, ) @@ -52,9 +50,7 @@ def get_loyalty_program_details_with_points( include_expired_entry=False, current_transaction_amount=0, ): - lp_details = get_loyalty_program_details( - customer, loyalty_program, company=company, silent=silent - ) + lp_details = get_loyalty_program_details(customer, loyalty_program, company=company, silent=silent) loyalty_program = frappe.get_doc("Loyalty Program", loyalty_program) lp_details.update( get_loyalty_details(customer, loyalty_program.name, expiry_date, company, include_expired_entry) diff --git a/erpnext/accounts/doctype/loyalty_program/test_loyalty_program.py b/erpnext/accounts/doctype/loyalty_program/test_loyalty_program.py index 3641ac4428f..4d21fb69806 100644 --- a/erpnext/accounts/doctype/loyalty_program/test_loyalty_program.py +++ b/erpnext/accounts/doctype/loyalty_program/test_loyalty_program.py @@ -19,9 +19,7 @@ class TestLoyaltyProgram(unittest.TestCase): create_records() def test_loyalty_points_earned_single_tier(self): - frappe.db.set_value( - "Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty" - ) + frappe.db.set_value("Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty") # create a new sales invoice si_original = create_sales_invoice_record() si_original.insert() @@ -69,9 +67,7 @@ class TestLoyaltyProgram(unittest.TestCase): d.cancel() def test_loyalty_points_earned_multiple_tier(self): - frappe.db.set_value( - "Customer", "Test Loyalty Customer", "loyalty_program", "Test Multiple Loyalty" - ) + frappe.db.set_value("Customer", "Test Loyalty Customer", "loyalty_program", "Test Multiple Loyalty") # assign multiple tier program to the customer customer = frappe.get_doc("Customer", {"customer_name": "Test Loyalty Customer"}) customer.loyalty_program = frappe.get_doc( @@ -128,9 +124,7 @@ class TestLoyaltyProgram(unittest.TestCase): def test_cancel_sales_invoice(self): """cancelling the sales invoice should cancel the earned points""" - frappe.db.set_value( - "Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty" - ) + frappe.db.set_value("Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty") # create a new sales invoice si = create_sales_invoice_record() si.insert() @@ -140,7 +134,7 @@ class TestLoyaltyProgram(unittest.TestCase): "Loyalty Point Entry", {"invoice_type": "Sales Invoice", "invoice": si.name, "customer": si.customer}, ) - self.assertEqual(True, not (lpe is None)) + self.assertEqual(True, lpe is not None) # cancelling sales invoice si.cancel() @@ -148,9 +142,7 @@ class TestLoyaltyProgram(unittest.TestCase): self.assertEqual(True, (lpe is None)) def test_sales_invoice_return(self): - frappe.db.set_value( - "Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty" - ) + frappe.db.set_value("Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty") # create a new sales invoice si_original = create_sales_invoice_record(2) si_original.conversion_rate = flt(1) @@ -346,9 +338,7 @@ def create_records(): ).insert() # create item price - if not frappe.db.exists( - "Item Price", {"price_list": "Standard Selling", "item_code": "Loyal Item"} - ): + if not frappe.db.exists("Item Price", {"price_list": "Standard Selling", "item_code": "Loyal Item"}): frappe.get_doc( { "doctype": "Item Price", diff --git a/erpnext/accounts/doctype/monthly_distribution/monthly_distribution.py b/erpnext/accounts/doctype/monthly_distribution/monthly_distribution.py index 1d19708eddf..e5b2e74b4a4 100644 --- a/erpnext/accounts/doctype/monthly_distribution/monthly_distribution.py +++ b/erpnext/accounts/doctype/monthly_distribution/monthly_distribution.py @@ -37,9 +37,7 @@ class MonthlyDistribution(Document): total = sum(flt(d.percentage_allocation) for d in self.get("percentages")) if flt(total, 2) != 100.0: - frappe.throw( - _("Percentage Allocation should be equal to 100%") + " ({0}%)".format(str(flt(total, 2))) - ) + frappe.throw(_("Percentage Allocation should be equal to 100%") + f" ({flt(total, 2)!s}%)") def get_periodwise_distribution_data(distribution_id, period_list, periodicity): diff --git a/erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py b/erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py index 1e22c64c8f2..d365959c2cd 100644 --- a/erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py +++ b/erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py @@ -83,9 +83,7 @@ class TestOpeningInvoiceCreationTool(FrappeTestCase): company = "_Test Opening Invoice Company" party_1, party_2 = make_customer("Customer A"), make_customer("Customer B") - old_default_receivable_account = frappe.db.get_value( - "Company", company, "default_receivable_account" - ) + old_default_receivable_account = frappe.db.get_value("Company", company, "default_receivable_account") frappe.db.set_value("Company", company, "default_receivable_account", "") if not frappe.db.exists("Cost Center", "_Test Opening Invoice Company - _TOIC"): @@ -121,9 +119,7 @@ class TestOpeningInvoiceCreationTool(FrappeTestCase): self.assertTrue(error_log) # teardown - frappe.db.set_value( - "Company", company, "default_receivable_account", old_default_receivable_account - ) + frappe.db.set_value("Company", company, "default_receivable_account", old_default_receivable_account) def test_renaming_of_invoice_using_invoice_number_field(self): company = "_Test Opening Invoice Company" @@ -169,7 +165,7 @@ def get_opening_invoice_creation_dict(**args): { "qty": 1.0, "outstanding_amount": 300, - "party": args.get("party_1") or "_Test {0}".format(party), + "party": args.get("party_1") or f"_Test {party}", "item_name": "Opening Item", "due_date": "2016-09-10", "posting_date": "2016-09-05", @@ -179,7 +175,7 @@ def get_opening_invoice_creation_dict(**args): { "qty": 2.0, "outstanding_amount": 250, - "party": args.get("party_2") or "_Test {0} 1".format(party), + "party": args.get("party_2") or f"_Test {party} 1", "item_name": "Opening Item", "due_date": "2016-09-10", "posting_date": "2016-09-05", diff --git a/erpnext/accounts/doctype/party_link/party_link.py b/erpnext/accounts/doctype/party_link/party_link.py index 312cfd2c0a1..d3148c3c455 100644 --- a/erpnext/accounts/doctype/party_link/party_link.py +++ b/erpnext/accounts/doctype/party_link/party_link.py @@ -24,7 +24,10 @@ class PartyLink(Document): if existing_party_link: frappe.throw( _("{} {} is already linked with {} {}").format( - self.primary_role, bold(self.primary_party), self.secondary_role, bold(self.secondary_party) + self.primary_role, + bold(self.primary_party), + self.secondary_role, + bold(self.secondary_party), ) ) diff --git a/erpnext/accounts/doctype/payment_entry/payment_entry.py b/erpnext/accounts/doctype/payment_entry/payment_entry.py index fefb331ff27..370e1deaa40 100644 --- a/erpnext/accounts/doctype/payment_entry/payment_entry.py +++ b/erpnext/accounts/doctype/payment_entry/payment_entry.py @@ -47,7 +47,7 @@ class InvalidPaymentEntry(ValidationError): class PaymentEntry(AccountsController): def __init__(self, *args, **kwargs): - super(PaymentEntry, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if not self.is_new(): self.setup_party_account_field() @@ -113,7 +113,7 @@ class PaymentEntry(AccountsController): "Unreconcile Payment", "Unreconcile Payment Entries", ) - super(PaymentEntry, self).on_cancel() + super().on_cancel() self.make_gl_entries(cancel=1) self.update_outstanding_amounts() self.update_advance_paid() @@ -221,9 +221,7 @@ class PaymentEntry(AccountsController): # If term based allocation is enabled, throw if ( d.payment_term is None or d.payment_term == "" - ) and self.term_based_allocation_enabled_for_reference( - d.reference_doctype, d.reference_name - ): + ) and self.term_based_allocation_enabled_for_reference(d.reference_doctype, d.reference_name): frappe.throw( _( "{0} has Payment Term based allocation enabled. Select a Payment Term for Row #{1} in Payment References section" @@ -235,7 +233,9 @@ class PaymentEntry(AccountsController): # The reference has already been fully paid if not latest: frappe.throw( - _("{0} {1} has already been fully paid.").format(_(d.reference_doctype), d.reference_name) + _("{0} {1} has already been fully paid.").format( + _(d.reference_doctype), d.reference_name + ) ) # The reference has already been partly paid elif ( @@ -259,14 +259,14 @@ class PaymentEntry(AccountsController): and latest.payment_term_outstanding and (flt(d.allocated_amount) > flt(latest.payment_term_outstanding)) ) - and self.term_based_allocation_enabled_for_reference(d.reference_doctype, d.reference_name) + and self.term_based_allocation_enabled_for_reference( + d.reference_doctype, d.reference_name + ) ): frappe.throw( _( "Row #{0}: Allocated amount:{1} is greater than outstanding amount:{2} for Payment Term {3}" - ).format( - d.idx, d.allocated_amount, latest.payment_term_outstanding, d.payment_term - ) + ).format(d.idx, d.allocated_amount, latest.payment_term_outstanding, d.payment_term) ) if (flt(d.allocated_amount)) > 0 and flt(d.allocated_amount) > flt(latest.outstanding_amount): @@ -343,7 +343,7 @@ class PaymentEntry(AccountsController): for d in self.get("references"): if d.allocated_amount: if update_ref_details_only_for and ( - not (d.reference_doctype, d.reference_name) in update_ref_details_only_for + (d.reference_doctype, d.reference_name) not in update_ref_details_only_for ): continue @@ -390,7 +390,9 @@ class PaymentEntry(AccountsController): else: if ref_doc: if self.paid_from_account_currency == ref_doc.currency: - self.source_exchange_rate = ref_doc.get("exchange_rate") or ref_doc.get("conversion_rate") + self.source_exchange_rate = ref_doc.get("exchange_rate") or ref_doc.get( + "conversion_rate" + ) if not self.source_exchange_rate: self.source_exchange_rate = get_exchange_rate( @@ -427,7 +429,7 @@ class PaymentEntry(AccountsController): if d.reference_doctype not in valid_reference_doctypes: frappe.throw( _("Reference Doctype must be one of {0}").format( - comma_or((_(d) for d in valid_reference_doctypes)) + comma_or(_(d) for d in valid_reference_doctypes) ) ) @@ -450,7 +452,8 @@ class PaymentEntry(AccountsController): if d.reference_doctype in frappe.get_hooks("invoice_doctypes"): if self.party_type == "Customer": ref_party_account = ( - get_party_account_based_on_invoice_discounting(d.reference_name) or ref_doc.debit_to + get_party_account_based_on_invoice_discounting(d.reference_name) + or ref_doc.debit_to ) elif self.party_type == "Supplier": ref_party_account = ref_doc.credit_to @@ -460,7 +463,10 @@ class PaymentEntry(AccountsController): if ref_party_account != self.party_account: frappe.throw( _("{0} {1} is associated with {2}, but Party Account is {3}").format( - _(d.reference_doctype), d.reference_name, ref_party_account, self.party_account + _(d.reference_doctype), + d.reference_name, + ref_party_account, + self.party_account, ) ) @@ -471,7 +477,9 @@ class PaymentEntry(AccountsController): ) if ref_doc.docstatus != 1: - frappe.throw(_("{0} {1} must be submitted").format(_(d.reference_doctype), d.reference_name)) + frappe.throw( + _("{0} {1} must be submitted").format(_(d.reference_doctype), d.reference_name) + ) def get_valid_reference_doctypes(self): if self.party_type == "Customer": @@ -642,9 +650,7 @@ class PaymentEntry(AccountsController): if not (is_single_currency and reference_is_multi_currency): return allocated_amount - allocated_amount = flt( - allocated_amount / ref_exchange_rate, self.precision("total_allocated_amount") - ) + allocated_amount = flt(allocated_amount / ref_exchange_rate, self.precision("total_allocated_amount")) return allocated_amount @@ -692,7 +698,6 @@ class PaymentEntry(AccountsController): accounts = [] for d in self.taxes: if d.account_head == tax_withholding_details.get("account_head"): - # Preserve user updated included in paid amount if d.included_in_paid_amount: tax_withholding_details.update({"included_in_paid_amount": d.included_in_paid_amount}) @@ -812,7 +817,6 @@ class PaymentEntry(AccountsController): flt(d.allocated_amount) * flt(exchange_rate), self.precision("base_paid_amount") ) else: - # Use source/target exchange rate, so no difference amount is calculated. # then update exchange gain/loss amount in reference table # if there is an exchange gain/loss amount in reference table, submit a JE for that @@ -929,7 +933,9 @@ class PaymentEntry(AccountsController): total_negative_outstanding = flt( sum( - abs(flt(d.outstanding_amount)) for d in self.get("references") if flt(d.outstanding_amount) < 0 + abs(flt(d.outstanding_amount)) + for d in self.get("references") + if flt(d.outstanding_amount) < 0 ), self.references[0].precision("outstanding_amount") if self.references else None, ) @@ -982,7 +988,6 @@ class PaymentEntry(AccountsController): ) ] else: - remarks = [ _("Amount {0} {1} {2} {3}").format( self.party_account_currency, @@ -1002,14 +1007,19 @@ class PaymentEntry(AccountsController): if d.allocated_amount: remarks.append( _("Amount {0} {1} against {2} {3}").format( - self.party_account_currency, d.allocated_amount, d.reference_doctype, d.reference_name + self.party_account_currency, + d.allocated_amount, + d.reference_doctype, + d.reference_name, ) ) for d in self.get("deductions"): if d.amount: remarks.append( - _("Amount {0} {1} deducted against {2}").format(self.company_currency, d.amount, d.account) + _("Amount {0} {1} deducted against {2}").format( + self.company_currency, d.amount, d.account + ) ) self.set("remarks", "\n".join(remarks)) @@ -1444,7 +1454,8 @@ def get_outstanding_reference_documents(args): return [] elif supplier_status["hold_type"] == "Payments": if ( - not supplier_status["release_date"] or getdate(nowdate()) <= supplier_status["release_date"] + not supplier_status["release_date"] + or getdate(nowdate()) <= supplier_status["release_date"] ): return [] @@ -1454,7 +1465,7 @@ def get_outstanding_reference_documents(args): # Get positive outstanding sales /purchase invoices condition = "" if args.get("voucher_type") and args.get("voucher_no"): - condition = " and voucher_type={0} and voucher_no={1}".format( + condition = " and voucher_type={} and voucher_no={}".format( frappe.db.escape(args["voucher_type"]), frappe.db.escape(args["voucher_no"]) ) common_filter.append(ple.voucher_type == args["voucher_type"]) @@ -1469,7 +1480,7 @@ def get_outstanding_reference_documents(args): active_dimensions = get_dimensions()[0] for dim in active_dimensions: if args.get(dim.fieldname): - condition += " and {0}='{1}'".format(dim.fieldname, args.get(dim.fieldname)) + condition += f" and {dim.fieldname}='{args.get(dim.fieldname)}'" accounting_dimensions_filter.append(ple[dim.fieldname] == args.get(dim.fieldname)) date_fields_dict = { @@ -1479,21 +1490,21 @@ def get_outstanding_reference_documents(args): for fieldname, date_fields in date_fields_dict.items(): if args.get(date_fields[0]) and args.get(date_fields[1]): - condition += " and {0} between '{1}' and '{2}'".format( + condition += " and {} between '{}' and '{}'".format( fieldname, args.get(date_fields[0]), args.get(date_fields[1]) ) posting_and_due_date.append(ple[fieldname][args.get(date_fields[0]) : args.get(date_fields[1])]) elif args.get(date_fields[0]): # if only from date is supplied - condition += " and {0} >= '{1}'".format(fieldname, args.get(date_fields[0])) + condition += f" and {fieldname} >= '{args.get(date_fields[0])}'" posting_and_due_date.append(ple[fieldname].gte(args.get(date_fields[0]))) elif args.get(date_fields[1]): # if only to date is supplied - condition += " and {0} <= '{1}'".format(fieldname, args.get(date_fields[1])) + condition += f" and {fieldname} <= '{args.get(date_fields[1])}'" posting_and_due_date.append(ple[fieldname].lte(args.get(date_fields[1]))) if args.get("company"): - condition += " and company = {0}".format(frappe.db.escape(args.get("company"))) + condition += " and company = {}".format(frappe.db.escape(args.get("company"))) common_filter.append(ple.company == args.get("company")) outstanding_invoices = [] @@ -1565,9 +1576,7 @@ def get_outstanding_reference_documents(args): frappe.msgprint( _( "No outstanding {0} found for the {1} {2} which qualify the filters you have specified." - ).format( - _(ref_document_type), _(args.get("party_type")).lower(), frappe.bold(args.get("party")) - ) + ).format(_(ref_document_type), _(args.get("party_type")).lower(), frappe.bold(args.get("party"))) ) return data @@ -1603,12 +1612,10 @@ def split_invoices_based_on_payment_terms(outstanding_invoices, company) -> list return outstanding_invoices_after_split -def get_currency_data(outstanding_invoices: list, company: str = None) -> dict: +def get_currency_data(outstanding_invoices: list, company: str | None = None) -> dict: """Get currency and conversion data for a list of invoices.""" exc_rates = frappe._dict() - company_currency = ( - frappe.db.get_value("Company", company, "default_currency") if company else None - ) + company_currency = frappe.db.get_value("Company", company, "default_currency") if company else None for doctype in ["Sales Invoice", "Purchase Invoice"]: invoices = [x.voucher_no for x in outstanding_invoices if x.voucher_type == doctype] @@ -1703,7 +1710,7 @@ def get_orders_to_be_billed( active_dimensions = get_dimensions()[0] for dim in active_dimensions: if filters.get(dim.fieldname): - condition += " and {0}='{1}'".format(dim.fieldname, filters.get(dim.fieldname)) + condition += f" and {dim.fieldname}='{filters.get(dim.fieldname)}'" if party_account_currency == company_currency: grand_total_field = "base_grand_total" @@ -1852,18 +1859,14 @@ def get_account_details(account, date, cost_center=None): frappe.has_permission("Payment Entry", throw=True) # to check if the passed account is accessible under reference doctype Payment Entry - account_list = frappe.get_list( - "Account", {"name": account}, reference_doctype="Payment Entry", limit=1 - ) + account_list = frappe.get_list("Account", {"name": account}, reference_doctype="Payment Entry", limit=1) # There might be some user permissions which will allow account under certain doctypes # except for Payment Entry, only in such case we should throw permission error if not account_list: frappe.throw(_("Account: {0} is not permitted under Payment Entry").format(account)) - account_balance = get_balance_on( - account, date, cost_center=cost_center, ignore_account_permission=True - ) + account_balance = get_balance_on(account, date, cost_center=cost_center, ignore_account_permission=True) return frappe._dict( { @@ -1910,9 +1913,7 @@ def get_reference_details(reference_doctype, reference_name, party_account_curre total_amount = outstanding_amount = exchange_rate = None ref_doc = frappe.get_doc(reference_doctype, reference_name) - company_currency = ref_doc.get("company_currency") or erpnext.get_company_currency( - ref_doc.company - ) + company_currency = ref_doc.get("company_currency") or erpnext.get_company_currency(ref_doc.company) if reference_doctype == "Dunning": total_amount = outstanding_amount = ref_doc.get("dunning_amount") @@ -1921,9 +1922,7 @@ def get_reference_details(reference_doctype, reference_name, party_account_curre elif reference_doctype == "Journal Entry" and ref_doc.docstatus == 1: total_amount = ref_doc.get("total_amount") if ref_doc.multi_currency: - exchange_rate = get_exchange_rate( - party_account_currency, company_currency, ref_doc.posting_date - ) + exchange_rate = get_exchange_rate(party_account_currency, company_currency, ref_doc.posting_date) else: exchange_rate = 1 outstanding_amount = get_outstanding_on_journal_entry(reference_name) @@ -1981,9 +1980,7 @@ def get_payment_entry( ): doc = frappe.get_doc(dt, dn) over_billing_allowance = frappe.db.get_single_value("Accounts Settings", "over_billing_allowance") - if dt in ("Sales Order", "Purchase Order") and flt(doc.per_billed, 2) >= ( - 100.0 + over_billing_allowance - ): + if dt in ("Sales Order", "Purchase Order") and flt(doc.per_billed, 2) >= (100.0 + over_billing_allowance): frappe.throw(_("Can only make payment against unbilled {0}").format(_(dt))) if not party_type: @@ -2036,9 +2033,7 @@ def get_payment_entry( pe.paid_from_account_currency = ( party_account_currency if payment_type == "Receive" else bank.account_currency ) - pe.paid_to_account_currency = ( - party_account_currency if payment_type == "Pay" else bank.account_currency - ) + pe.paid_to_account_currency = party_account_currency if payment_type == "Pay" else bank.account_currency pe.paid_amount = paid_amount pe.received_amount = received_amount pe.letter_head = doc.get("letter_head") @@ -2067,7 +2062,6 @@ def get_payment_entry( {"name": doc.payment_terms_template}, "allocate_payment_based_on_payment_terms", ): - for reference in get_reference_as_per_payment_terms( doc.payment_schedule, dt, dn, doc, grand_total, outstanding_amount, party_account_currency ): @@ -2188,9 +2182,9 @@ def set_party_account_currency(dt, party_account, doc): def set_payment_type(dt, doc): - if ( - dt == "Sales Order" or (dt in ("Sales Invoice", "Dunning") and doc.outstanding_amount > 0) - ) or (dt == "Purchase Invoice" and doc.outstanding_amount < 0): + if (dt == "Sales Order" or (dt in ("Sales Invoice", "Dunning") and doc.outstanding_amount > 0)) or ( + dt == "Purchase Invoice" and doc.outstanding_amount < 0 + ): payment_type = "Receive" else: payment_type = "Pay" @@ -2250,9 +2244,7 @@ def set_paid_amount_and_received_amount( return paid_amount, received_amount -def apply_early_payment_discount( - paid_amount, received_amount, doc, party_account_currency, reference_date -): +def apply_early_payment_discount(paid_amount, received_amount, doc, party_account_currency, reference_date): total_discount = 0 valid_discounts = [] eligible_for_payments = ["Sales Order", "Sales Invoice", "Purchase Order", "Purchase Invoice"] @@ -2262,7 +2254,6 @@ def apply_early_payment_discount( if doc.doctype in eligible_for_payments and has_payment_schedule: for term in doc.payment_schedule: if not term.discounted_amount and term.discount and reference_date <= term.discount_date: - if term.discount_type == "Percentage": grand_total = doc.get("grand_total") if is_multi_currency else doc.get("base_grand_total") discount_amount = flt(grand_total) * (term.discount / 100) @@ -2291,9 +2282,7 @@ def apply_early_payment_discount( return paid_amount, received_amount, total_discount, valid_discounts -def set_pending_discount_loss( - pe, doc, discount_amount, base_total_discount_loss, party_account_currency -): +def set_pending_discount_loss(pe, doc, discount_amount, base_total_discount_loss, party_account_currency): # If multi-currency, get base discount amount to adjust with base currency deductions/losses if party_account_currency != doc.company_currency: discount_amount = discount_amount * doc.get("conversion_rate", 1) @@ -2313,7 +2302,8 @@ def set_pending_discount_loss( pe.set_gain_or_loss( account_details={ "account": frappe.get_cached_value("Company", pe.company, account_type), - "cost_center": pe.cost_center or frappe.get_cached_value("Company", pe.company, "cost_center"), + "cost_center": pe.cost_center + or frappe.get_cached_value("Company", pe.company, "cost_center"), "amount": discount_amount * positive_negative, } ) @@ -2336,9 +2326,7 @@ def split_early_payment_discount_loss(pe, doc, valid_discounts) -> float: def get_total_discount_percent(doc, valid_discounts) -> float: """Get total percentage and amount discount applied as a percentage.""" total_discount_percent = ( - sum( - discount.get("discount") for discount in valid_discounts if discount.get("type") == "Percentage" - ) + sum(discount.get("discount") for discount in valid_discounts if discount.get("type") == "Percentage") or 0.0 ) @@ -2381,9 +2369,7 @@ def add_tax_discount_loss(pe, doc, total_discount_percentage) -> float: # The same account head could be used more than once for tax in doc.get("taxes", []): - base_tax_loss = tax.get("base_tax_amount_after_discount_amount") * ( - total_discount_percentage / 100 - ) + base_tax_loss = tax.get("base_tax_amount_after_discount_amount") * (total_discount_percentage / 100) account = tax.get("account_head") if not tax_discount_loss.get(account): @@ -2400,7 +2386,8 @@ def add_tax_discount_loss(pe, doc, total_discount_percentage) -> float: "deductions", { "account": account, - "cost_center": pe.cost_center or frappe.get_cached_value("Company", pe.company, "cost_center"), + "cost_center": pe.cost_center + or frappe.get_cached_value("Company", pe.company, "cost_center"), "amount": flt(loss, precision), }, ) @@ -2423,7 +2410,8 @@ def get_reference_as_per_payment_terms( if not is_multi_currency_acc: # If accounting is done in company currency for multi-currency transaction payment_term_outstanding = flt( - payment_term_outstanding * doc.get("conversion_rate"), payment_term.precision("payment_amount") + payment_term_outstanding * doc.get("conversion_rate"), + payment_term.precision("payment_amount"), ) if payment_term_outstanding: @@ -2451,7 +2439,7 @@ def get_paid_amount(dt, dn, party_type, party, account, due_date): dr_or_cr = "debit_in_account_currency - credit_in_account_currency" paid_amount = frappe.db.sql( - """ + f""" select ifnull(sum({dr_or_cr}), 0) as paid_amount from `tabGL Entry` where against_voucher_type = %s @@ -2461,9 +2449,7 @@ def get_paid_amount(dt, dn, party_type, party, account, due_date): and account = %s and due_date = %s and {dr_or_cr} > 0 - """.format( - dr_or_cr=dr_or_cr - ), + """, (dt, dn, party_type, party, account, due_date), ) diff --git a/erpnext/accounts/doctype/payment_entry/test_payment_entry.py b/erpnext/accounts/doctype/payment_entry/test_payment_entry.py index d035149ff93..ec3b4196bde 100644 --- a/erpnext/accounts/doctype/payment_entry/test_payment_entry.py +++ b/erpnext/accounts/doctype/payment_entry/test_payment_entry.py @@ -2,7 +2,6 @@ # See license.txt import json -import unittest import frappe from frappe import qb @@ -470,9 +469,7 @@ class TestPaymentEntry(FrappeTestCase): si.save() si.submit() - pe = get_payment_entry( - "Sales Invoice", si.name, bank_account="_Test Bank - _TC", bank_amount=4700 - ) + pe = get_payment_entry("Sales Invoice", si.name, bank_account="_Test Bank - _TC", bank_amount=4700) pe.reference_no = si.name pe.reference_date = nowdate() @@ -639,9 +636,7 @@ class TestPaymentEntry(FrappeTestCase): pe.set_exchange_rate() pe.set_amounts() - self.assertEqual( - pe.source_exchange_rate, 65.1, "{0} is not equal to {1}".format(pe.source_exchange_rate, 65.1) - ) + self.assertEqual(pe.source_exchange_rate, 65.1, f"{pe.source_exchange_rate} is not equal to {65.1}") def test_internal_transfer_usd_to_inr(self): pe = frappe.new_doc("Payment Entry") @@ -910,9 +905,7 @@ class TestPaymentEntry(FrappeTestCase): cost_center = "_Test Cost Center for BS Account - _TC" create_cost_center(cost_center_name="_Test Cost Center for BS Account", company="_Test Company") - pi = make_purchase_invoice_against_cost_center( - cost_center=cost_center, credit_to="Creditors - _TC" - ) + pi = make_purchase_invoice_against_cost_center(cost_center=cost_center, credit_to="Creditors - _TC") pe = get_payment_entry("Purchase Invoice", pi.name, bank_account="_Test Bank - _TC") self.assertEqual(pe.cost_center, pi.cost_center) @@ -953,9 +946,7 @@ class TestPaymentEntry(FrappeTestCase): si = create_sales_invoice_against_cost_center(cost_center=cost_center, debit_to="Debtors - _TC") account_balance = get_balance_on(account="_Test Bank - _TC", cost_center=si.cost_center) - party_balance = get_balance_on( - party_type="Customer", party=si.customer, cost_center=si.cost_center - ) + party_balance = get_balance_on(party_type="Customer", party=si.customer, cost_center=si.cost_center) party_account_balance = get_balance_on(si.debit_to, cost_center=si.cost_center) pe = get_payment_entry("Sales Invoice", si.name, bank_account="_Test Bank - _TC") @@ -1214,7 +1205,7 @@ class TestPaymentEntry(FrappeTestCase): Overallocation validation shouldn't fire for Template without "Allocate Payment based on Payment Terms" enabled """ - customer = create_customer() + create_customer() create_payment_terms_template() template = frappe.get_doc("Payment Terms Template", "Test Receivable Template") @@ -1273,9 +1264,7 @@ class TestPaymentEntry(FrappeTestCase): create_payment_terms_template() # SI has an earlier due date and SI2 has a later due date - si = create_sales_invoice( - qty=1, rate=100, customer=customer, posting_date=add_days(nowdate(), -4) - ) + si = create_sales_invoice(qty=1, rate=100, customer=customer, posting_date=add_days(nowdate(), -4)) si2 = create_sales_invoice(do_not_save=1, qty=1, rate=100, customer=customer) si2.payment_terms_template = "Test Receivable Template" si2.submit() @@ -1401,12 +1390,11 @@ def create_payment_entry(**args): def create_payment_terms_template(): - create_payment_term("Basic Amount Receivable") create_payment_term("Tax Receivable") if not frappe.db.exists("Payment Terms Template", "Test Receivable Template"): - payment_term_template = frappe.get_doc( + frappe.get_doc( { "doctype": "Payment Terms Template", "template_name": "Test Receivable Template", diff --git a/erpnext/accounts/doctype/payment_ledger_entry/payment_ledger_entry.py b/erpnext/accounts/doctype/payment_ledger_entry/payment_ledger_entry.py index bd438ee7606..8be3d76474f 100644 --- a/erpnext/accounts/doctype/payment_ledger_entry/payment_ledger_entry.py +++ b/erpnext/accounts/doctype/payment_ledger_entry/payment_ledger_entry.py @@ -108,9 +108,9 @@ class PaymentLedgerEntry(Document): ): if not self.get(dimension.fieldname): frappe.throw( - _("Accounting Dimension {0} is required for 'Profit and Loss' account {1}.").format( - dimension.label, self.account - ) + _( + "Accounting Dimension {0} is required for 'Profit and Loss' account {1}." + ).format(dimension.label, self.account) ) if ( @@ -121,9 +121,9 @@ class PaymentLedgerEntry(Document): ): if not self.get(dimension.fieldname): frappe.throw( - _("Accounting Dimension {0} is required for 'Balance Sheet' account {1}.").format( - dimension.label, self.account - ) + _( + "Accounting Dimension {0} is required for 'Balance Sheet' account {1}." + ).format(dimension.label, self.account) ) def validate(self): diff --git a/erpnext/accounts/doctype/payment_ledger_entry/test_payment_ledger_entry.py b/erpnext/accounts/doctype/payment_ledger_entry/test_payment_ledger_entry.py index ce9579ed613..c867e68d1a6 100644 --- a/erpnext/accounts/doctype/payment_ledger_entry/test_payment_ledger_entry.py +++ b/erpnext/accounts/doctype/payment_ledger_entry/test_payment_ledger_entry.py @@ -159,9 +159,7 @@ class TestPaymentLedgerEntry(FrappeTestCase): for doctype in doctype_list: qb.from_(qb.DocType(doctype)).delete().where(qb.DocType(doctype).company == self.company).run() - def create_journal_entry( - self, acc1=None, acc2=None, amount=0, posting_date=None, cost_center=None - ): + def create_journal_entry(self, acc1=None, acc2=None, amount=0, posting_date=None, cost_center=None): je = frappe.new_doc("Journal Entry") je.posting_date = posting_date or nowdate() je.company = self.company @@ -319,9 +317,7 @@ class TestPaymentLedgerEntry(FrappeTestCase): ple.amount, ple.delinked, ) - .where( - (ple.against_voucher_type == cr_note1.doctype) & (ple.against_voucher_no == cr_note1.name) - ) + .where((ple.against_voucher_type == cr_note1.doctype) & (ple.against_voucher_no == cr_note1.name)) .orderby(ple.creation) .run(as_dict=True) ) @@ -362,9 +358,7 @@ class TestPaymentLedgerEntry(FrappeTestCase): ) cr_note2.is_return = 1 cr_note2 = cr_note2.save().submit() - je1 = self.create_journal_entry( - self.debit_to, self.debit_to, amount, posting_date=transaction_date - ) + je1 = self.create_journal_entry(self.debit_to, self.debit_to, amount, posting_date=transaction_date) je1.get("accounts")[0].party_type = je1.get("accounts")[1].party_type = "Customer" je1.get("accounts")[0].party = je1.get("accounts")[1].party = self.customer je1.get("accounts")[0].reference_type = cr_note2.doctype @@ -419,9 +413,7 @@ class TestPaymentLedgerEntry(FrappeTestCase): ple.amount, ple.delinked, ) - .where( - (ple.against_voucher_type == cr_note2.doctype) & (ple.against_voucher_no == cr_note2.name) - ) + .where((ple.against_voucher_type == cr_note2.doctype) & (ple.against_voucher_no == cr_note2.name)) .orderby(ple.creation) .run(as_dict=True) ) @@ -518,7 +510,7 @@ class TestPaymentLedgerEntry(FrappeTestCase): amount = 100 so = self.create_sales_order(qty=1, rate=amount, posting_date=transaction_date).save().submit() - pe = get_payment_entry(so.doctype, so.name).save().submit() + get_payment_entry(so.doctype, so.name).save().submit() so.reload() so.cancel() diff --git a/erpnext/accounts/doctype/payment_order/payment_order.py b/erpnext/accounts/doctype/payment_order/payment_order.py index ff9615d14fc..dde9b094c01 100644 --- a/erpnext/accounts/doctype/payment_order/payment_order.py +++ b/erpnext/accounts/doctype/payment_order/payment_order.py @@ -66,9 +66,7 @@ def make_journal_entry(doc, supplier, mode_of_payment=None): je = frappe.new_doc("Journal Entry") je.payment_order = doc.name je.posting_date = nowdate() - mode_of_payment_type = frappe._dict( - frappe.get_all("Mode of Payment", fields=["name", "type"], as_list=1) - ) + mode_of_payment_type = frappe._dict(frappe.get_all("Mode of Payment", fields=["name", "type"], as_list=1)) je.voucher_type = "Bank Entry" if mode_of_payment and mode_of_payment_type.get(mode_of_payment) == "Cash": diff --git a/erpnext/accounts/doctype/payment_order/test_payment_order.py b/erpnext/accounts/doctype/payment_order/test_payment_order.py index 60f288e1f07..7af096647ca 100644 --- a/erpnext/accounts/doctype/payment_order/test_payment_order.py +++ b/erpnext/accounts/doctype/payment_order/test_payment_order.py @@ -1,7 +1,6 @@ # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt -import unittest import frappe from frappe.tests.utils import FrappeTestCase @@ -41,9 +40,7 @@ class TestPaymentOrder(FrappeTestCase): payment_entry.insert() payment_entry.submit() - doc = create_payment_order_against_payment_entry( - payment_entry, "Payment Entry", self.bank_account - ) + doc = create_payment_order_against_payment_entry(payment_entry, "Payment Entry", self.bank_account) reference_doc = doc.get("references")[0] self.assertEqual(reference_doc.reference_name, payment_entry.name) self.assertEqual(reference_doc.reference_doctype, "Payment Entry") diff --git a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py index 33f736fe915..b0347514905 100644 --- a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py +++ b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py @@ -25,7 +25,7 @@ from erpnext.controllers.accounts_controller import get_advance_payment_entries_ class PaymentReconciliation(Document): def __init__(self, *args, **kwargs): - super(PaymentReconciliation, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.common_filter_conditions = [] self.accounting_dimension_filter_conditions = [] self.ple_posting_date_filter = [] @@ -219,7 +219,6 @@ class PaymentReconciliation(Document): self.return_invoices = self.return_invoices_query.run(as_dict=True) def get_dr_or_cr_notes(self): - self.build_qb_filter_conditions(get_return_invoices=True) ple = qb.DocType("Payment Ledger Entry") @@ -340,9 +339,7 @@ class PaymentReconciliation(Document): payment_entry[0].get("reference_name") ) - new_difference_amount = self.get_difference_amount( - payment_entry[0], invoice[0], allocated_amount - ) + new_difference_amount = self.get_difference_amount(payment_entry[0], invoice[0], allocated_amount) return new_difference_amount @frappe.whitelist() @@ -460,9 +457,9 @@ class PaymentReconciliation(Document): if running_doc: frappe.throw( - _("A Reconciliation Job {0} is running for the same filters. Cannot reconcile now").format( - get_link_to_form("Auto Reconcile", running_doc) - ) + _( + "A Reconciliation Job {0} is running for the same filters. Cannot reconcile now" + ).format(get_link_to_form("Auto Reconcile", running_doc)) ) return @@ -555,9 +552,7 @@ class PaymentReconciliation(Document): invoice_exchange_map.update(purchase_invoice_map) - journals = [ - d.get("invoice_number") for d in invoices if d.get("invoice_type") == "Journal Entry" - ] + journals = [d.get("invoice_number") for d in invoices if d.get("invoice_type") == "Journal Entry"] journals.extend( [d.get("reference_name") for d in payments if d.get("reference_type") == "Journal Entry"] ) @@ -677,7 +672,7 @@ class PaymentReconciliation(Document): def get_journal_filter_conditions(self): conditions = [] je = qb.DocType("Journal Entry") - jea = qb.DocType("Journal Entry Account") + qb.DocType("Journal Entry Account") conditions.append(je.company == self.company) if self.from_payment_date: @@ -797,7 +792,7 @@ def adjust_allocations_for_taxes(doc): @frappe.whitelist() -def get_queries_for_dimension_filters(company: str = None): +def get_queries_for_dimension_filters(company: str | None = None): dimensions_with_filters = [] for d in get_dimensions()[0]: filters = {} diff --git a/erpnext/accounts/doctype/payment_reconciliation/test_payment_reconciliation.py b/erpnext/accounts/doctype/payment_reconciliation/test_payment_reconciliation.py index 662077d027e..25525a483e2 100644 --- a/erpnext/accounts/doctype/payment_reconciliation/test_payment_reconciliation.py +++ b/erpnext/accounts/doctype/payment_reconciliation/test_payment_reconciliation.py @@ -1,7 +1,6 @@ # Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt -import unittest import frappe from frappe import qb @@ -250,9 +249,7 @@ class TestPaymentReconciliation(FrappeTestCase): pr.from_invoice_date = pr.to_invoice_date = pr.from_payment_date = pr.to_payment_date = nowdate() return pr - def create_journal_entry( - self, acc1=None, acc2=None, amount=0, posting_date=None, cost_center=None - ): + def create_journal_entry(self, acc1=None, acc2=None, amount=0, posting_date=None, cost_center=None): je = frappe.new_doc("Journal Entry") je.posting_date = posting_date or nowdate() je.company = self.company @@ -402,7 +399,7 @@ class TestPaymentReconciliation(FrappeTestCase): rate = 100 invoices = [] payments = [] - for i in range(5): + for _i in range(5): invoices.append(self.create_sales_invoice(qty=1, rate=rate, posting_date=transaction_date)) pe = self.create_payment_entry(amount=rate, posting_date=transaction_date).save().submit() payments.append(pe) @@ -821,9 +818,7 @@ class TestPaymentReconciliation(FrappeTestCase): cr_note.cancel() - pay = self.create_payment_entry( - amount=amount, posting_date=transaction_date, customer=self.customer3 - ) + pay = self.create_payment_entry(amount=amount, posting_date=transaction_date, customer=self.customer3) pay.paid_from = self.debtors_eur pay.paid_from_account_currency = "EUR" pay.source_exchange_rate = exchange_rate @@ -1025,9 +1020,7 @@ class TestPaymentReconciliation(FrappeTestCase): rate = 100 # 'Main - PR' Cost Center - si1 = self.create_sales_invoice( - qty=1, rate=rate, posting_date=transaction_date, do_not_submit=True - ) + si1 = self.create_sales_invoice(qty=1, rate=rate, posting_date=transaction_date, do_not_submit=True) si1.cost_center = self.main_cc.name si1.submit() @@ -1043,9 +1036,7 @@ class TestPaymentReconciliation(FrappeTestCase): je1 = je1.save().submit() # 'Sub - PR' Cost Center - si2 = self.create_sales_invoice( - qty=1, rate=rate, posting_date=transaction_date, do_not_submit=True - ) + si2 = self.create_sales_invoice(qty=1, rate=rate, posting_date=transaction_date, do_not_submit=True) si2.cost_center = self.sub_cc.name si2.submit() diff --git a/erpnext/accounts/doctype/payment_request/payment_request.py b/erpnext/accounts/doctype/payment_request/payment_request.py index f6653f87f0f..3291bcb2612 100644 --- a/erpnext/accounts/doctype/payment_request/payment_request.py +++ b/erpnext/accounts/doctype/payment_request/payment_request.py @@ -50,7 +50,7 @@ class PaymentRequest(Document): ) ref_doc = frappe.get_doc(self.reference_doctype, self.reference_name) - if not hasattr(ref_doc, "order_type") or getattr(ref_doc, "order_type") != "Shopping Cart": + if not hasattr(ref_doc, "order_type") or ref_doc.order_type != "Shopping Cart": ref_amount = get_amount(ref_doc, self.payment_account) if existing_payment_request_amount + flt(self.grand_total) > ref_amount: @@ -103,7 +103,7 @@ class PaymentRequest(Document): ref_doc = frappe.get_doc(self.reference_doctype, self.reference_name) if ( - hasattr(ref_doc, "order_type") and getattr(ref_doc, "order_type") == "Shopping Cart" + hasattr(ref_doc, "order_type") and ref_doc.order_type == "Shopping Cart" ) or self.flags.mute_email: send_mail = False @@ -155,7 +155,7 @@ class PaymentRequest(Document): def make_invoice(self): ref_doc = frappe.get_doc(self.reference_doctype, self.reference_name) - if hasattr(ref_doc, "order_type") and getattr(ref_doc, "order_type") == "Shopping Cart": + if hasattr(ref_doc, "order_type") and ref_doc.order_type == "Shopping Cart": from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice si = make_sales_invoice(self.reference_name, ignore_permissions=True) @@ -241,14 +241,10 @@ class PaymentRequest(Document): else: party_account = get_party_account("Customer", ref_doc.get("customer"), ref_doc.company) - party_account_currency = ref_doc.get("party_account_currency") or get_account_currency( - party_account - ) + party_account_currency = ref_doc.get("party_account_currency") or get_account_currency(party_account) bank_amount = self.grand_total - if ( - party_account_currency == ref_doc.company_currency and party_account_currency != self.currency - ): + if party_account_currency == ref_doc.company_currency and party_account_currency != self.currency: party_amount = ref_doc.get("base_rounded_total") or ref_doc.get("base_grand_total") else: party_amount = self.grand_total @@ -266,7 +262,7 @@ class PaymentRequest(Document): "mode_of_payment": self.mode_of_payment, "reference_no": self.name, "reference_date": nowdate(), - "remarks": "Payment Entry against {0} {1} via Payment Request {2}".format( + "remarks": "Payment Entry against {} {} via Payment Request {}".format( self.reference_doctype, self.reference_name, self.name ), } @@ -380,14 +376,13 @@ class PaymentRequest(Document): and hasattr(frappe.local, "session") and frappe.local.session.user != "Guest" ) and self.payment_channel != "Phone": - success_url = shopping_cart_settings.payment_success_url if success_url: redirect_to = ({"Orders": "/orders", "Invoices": "/invoices", "My Account": "/me"}).get( success_url, "/me" ) else: - redirect_to = get_url("/orders/{0}".format(self.reference_name)) + redirect_to = get_url(f"/orders/{self.reference_name}") return redirect_to @@ -413,15 +408,11 @@ def make_payment_request(**args): frappe.db.set_value( "Sales Order", args.dn, "loyalty_points", int(args.loyalty_points), update_modified=False ) - frappe.db.set_value( - "Sales Order", args.dn, "loyalty_amount", loyalty_amount, update_modified=False - ) + frappe.db.set_value("Sales Order", args.dn, "loyalty_amount", loyalty_amount, update_modified=False) grand_total = grand_total - loyalty_amount bank_account = ( - get_party_bank_account(args.get("party_type"), args.get("party")) - if args.get("party_type") - else "" + get_party_bank_account(args.get("party_type"), args.get("party")) if args.get("party_type") else "" ) draft_payment_request = frappe.db.get_value( diff --git a/erpnext/accounts/doctype/payment_request/test_payment_request.py b/erpnext/accounts/doctype/payment_request/test_payment_request.py index feb2fdffc95..70de886ba4d 100644 --- a/erpnext/accounts/doctype/payment_request/test_payment_request.py +++ b/erpnext/accounts/doctype/payment_request/test_payment_request.py @@ -93,7 +93,7 @@ class TestPaymentRequest(unittest.TestCase): return_doc=1, ) - pe = pr.create_payment_entry() + pr.create_payment_entry() pr.load_from_db() self.assertEqual(pr.status, "Paid") @@ -158,7 +158,7 @@ class TestPaymentRequest(unittest.TestCase): self.assertTrue(gl_entries) - for i, gle in enumerate(gl_entries): + for _i, gle in enumerate(gl_entries): self.assertEqual(expected_gle[gle.account][0], gle.account) self.assertEqual(expected_gle[gle.account][1], gle.debit) self.assertEqual(expected_gle[gle.account][2], gle.credit) diff --git a/erpnext/accounts/doctype/payment_terms_template/payment_terms_template.py b/erpnext/accounts/doctype/payment_terms_template/payment_terms_template.py index 7b04a68e89a..3cb1d87f13a 100644 --- a/erpnext/accounts/doctype/payment_terms_template/payment_terms_template.py +++ b/erpnext/accounts/doctype/payment_terms_template/payment_terms_template.py @@ -19,9 +19,7 @@ class PaymentTermsTemplate(Document): total_portion += flt(term.get("invoice_portion", 0)) if flt(total_portion, 2) != 100.00: - frappe.msgprint( - _("Combined invoice portion must equal 100%"), raise_exception=1, indicator="red" - ) + frappe.msgprint(_("Combined invoice portion must equal 100%"), raise_exception=1, indicator="red") def validate_terms(self): terms = [] diff --git a/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py b/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py index 88a2ca575ac..c6ccb52f86d 100644 --- a/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py +++ b/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py @@ -47,7 +47,8 @@ class PeriodClosingVoucher(AccountsController): enqueue_after_commit=True, ) frappe.msgprint( - _("The GL Entries will be cancelled in the background, it can take a few minutes."), alert=True + _("The GL Entries will be cancelled in the background, it can take a few minutes."), + alert=True, ) else: make_reverse_gl_entries(voucher_type="Period Closing Voucher", voucher_no=self.name) @@ -89,9 +90,7 @@ class PeriodClosingVoucher(AccountsController): self.posting_date, self.fiscal_year, self.company, label=_("Posting Date"), doc=self ) - self.year_start_date = get_fiscal_year( - self.posting_date, self.fiscal_year, company=self.company - )[1] + self.year_start_date = get_fiscal_year(self.posting_date, self.fiscal_year, company=self.company)[1] self.check_if_previous_year_closed() @@ -205,7 +204,9 @@ class PeriodClosingVoucher(AccountsController): "credit_in_account_currency": abs(flt(acc.bal_in_account_currency)) if flt(acc.bal_in_account_currency) > 0 else 0, - "credit": abs(flt(acc.bal_in_company_currency)) if flt(acc.bal_in_company_currency) > 0 else 0, + "credit": abs(flt(acc.bal_in_company_currency)) + if flt(acc.bal_in_company_currency) > 0 + else 0, "is_period_closing_voucher_entry": 1, }, item=acc, @@ -229,7 +230,9 @@ class PeriodClosingVoucher(AccountsController): "credit_in_account_currency": abs(flt(acc.bal_in_account_currency)) if flt(acc.bal_in_account_currency) < 0 else 0, - "credit": abs(flt(acc.bal_in_company_currency)) if flt(acc.bal_in_company_currency) < 0 else 0, + "credit": abs(flt(acc.bal_in_company_currency)) + if flt(acc.bal_in_company_currency) < 0 + else 0, "is_period_closing_voucher_entry": 1, }, item=acc, diff --git a/erpnext/accounts/doctype/pos_closing_entry/pos_closing_entry.py b/erpnext/accounts/doctype/pos_closing_entry/pos_closing_entry.py index 115b415eeda..f61bfdb58ab 100644 --- a/erpnext/accounts/doctype/pos_closing_entry/pos_closing_entry.py +++ b/erpnext/accounts/doctype/pos_closing_entry/pos_closing_entry.py @@ -33,7 +33,7 @@ class POSClosingEntry(StatusUpdater): for key, value in pos_occurences.items(): if len(value) > 1: error_list.append( - _("{} is added multiple times on rows: {}".format(frappe.bold(key), frappe.bold(value))) + _(f"{frappe.bold(key)} is added multiple times on rows: {frappe.bold(value)}") ) if error_list: @@ -128,9 +128,7 @@ def get_pos_invoices(start, end, pos_profile, user): as_dict=1, ) - data = list( - filter(lambda d: get_datetime(start) <= get_datetime(d.timestamp) <= get_datetime(end), data) - ) + data = list(filter(lambda d: get_datetime(start) <= get_datetime(d.timestamp) <= get_datetime(end), data)) # need to get taxes and payments so can't avoid get_doc data = [frappe.get_doc("POS Invoice", d.name).as_dict() for d in data] @@ -201,7 +199,11 @@ def make_closing_entry_from_opening(opening_entry): else: payments.append( frappe._dict( - {"mode_of_payment": p.mode_of_payment, "opening_amount": 0, "expected_amount": p.amount} + { + "mode_of_payment": p.mode_of_payment, + "opening_amount": 0, + "expected_amount": p.amount, + } ) ) diff --git a/erpnext/accounts/doctype/pos_invoice/pos_invoice.py b/erpnext/accounts/doctype/pos_invoice/pos_invoice.py index 383b9dab24a..4abe91680e8 100644 --- a/erpnext/accounts/doctype/pos_invoice/pos_invoice.py +++ b/erpnext/accounts/doctype/pos_invoice/pos_invoice.py @@ -27,7 +27,7 @@ from erpnext.stock.doctype.serial_no.serial_no import ( class POSInvoice(SalesInvoice): def __init__(self, *args, **kwargs): - super(POSInvoice, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def validate(self): if not cint(self.is_pos): @@ -129,7 +129,9 @@ class POSInvoice(SalesInvoice): ) if paid_amt and pay.amount != paid_amt: - return frappe.throw(_("Payment related to {0} is not completed").format(pay.mode_of_payment)) + return frappe.throw( + _("Payment related to {0} is not completed").format(pay.mode_of_payment) + ) def validate_pos_reserved_serial_nos(self, item): serial_nos = get_serial_nos(item.serial_no) @@ -164,7 +166,7 @@ class POSInvoice(SalesInvoice): serial_nos = row.serial_no.split("\n") if serial_nos: - for key, value in collections.Counter(serial_nos).items(): + for _key, value in collections.Counter(serial_nos).items(): if value > 1: frappe.throw(_("Duplicate Serial No {0} found").format("key")) @@ -191,9 +193,7 @@ class POSInvoice(SalesInvoice): frappe.throw( _( "Row #{}: Batch No. {} of item {} has less than required stock available, {} more required" - ).format( - item.idx, bold_invalid_batch_no, bold_item_name, bold_extra_batch_qty_needed - ), + ).format(item.idx, bold_invalid_batch_no, bold_item_name, bold_extra_batch_qty_needed), title=_("Item Unavailable"), ) @@ -249,7 +249,7 @@ class POSInvoice(SalesInvoice): available_stock, is_stock_item = get_stock_availability(d.item_code, d.warehouse) - item_code, warehouse, qty = ( + item_code, warehouse, _qty = ( frappe.bold(d.item_code), frappe.bold(d.warehouse), frappe.bold(d.qty), diff --git a/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py b/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py index bd2fee3b0ad..186c0ea7fd4 100644 --- a/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py +++ b/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py @@ -338,9 +338,7 @@ class TestPOSInvoice(unittest.TestCase): ) pos.set("payments", []) - pos.append( - "payments", {"mode_of_payment": "Bank Draft", "account": "_Test Bank - _TC", "amount": 50} - ) + pos.append("payments", {"mode_of_payment": "Bank Draft", "account": "_Test Bank - _TC", "amount": 50}) pos.append( "payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 60, "default": 1} ) @@ -594,9 +592,7 @@ class TestPOSInvoice(unittest.TestCase): from erpnext.accounts.doctype.loyalty_program.test_loyalty_program import create_records create_records() - frappe.db.set_value( - "Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty" - ) + frappe.db.set_value("Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty") before_lp_details = get_loyalty_program_details_with_points( "Test Loyalty Customer", company="_Test Company", loyalty_program="Test Single Loyalty" ) @@ -670,9 +666,7 @@ class TestPOSInvoice(unittest.TestCase): consolidate_pos_invoices() pos_inv.load_from_db() - rounded_total = frappe.db.get_value( - "Sales Invoice", pos_inv.consolidated_invoice, "rounded_total" - ) + rounded_total = frappe.db.get_value("Sales Invoice", pos_inv.consolidated_invoice, "rounded_total") self.assertEqual(rounded_total, 3470) def test_merging_into_sales_invoice_with_discount_and_inclusive_tax(self): @@ -719,9 +713,7 @@ class TestPOSInvoice(unittest.TestCase): consolidate_pos_invoices() pos_inv.load_from_db() - rounded_total = frappe.db.get_value( - "Sales Invoice", pos_inv.consolidated_invoice, "rounded_total" - ) + rounded_total = frappe.db.get_value("Sales Invoice", pos_inv.consolidated_invoice, "rounded_total") self.assertEqual(rounded_total, 840) def test_merging_with_validate_selling_price(self): @@ -773,9 +765,7 @@ class TestPOSInvoice(unittest.TestCase): consolidate_pos_invoices() pos_inv2.load_from_db() - rounded_total = frappe.db.get_value( - "Sales Invoice", pos_inv2.consolidated_invoice, "rounded_total" - ) + rounded_total = frappe.db.get_value("Sales Invoice", pos_inv2.consolidated_invoice, "rounded_total") self.assertEqual(rounded_total, 400) def test_pos_batch_item_qty_validation(self): @@ -839,19 +829,19 @@ class TestPOSInvoice(unittest.TestCase): pos_inv = create_pos_invoice(qty=1, do_not_submit=1) pos_inv.items[0].rate = 300 pos_inv.save() - self.assertEquals(pos_inv.items[0].discount_percentage, 10) + self.assertEqual(pos_inv.items[0].discount_percentage, 10) # rate shouldn't change - self.assertEquals(pos_inv.items[0].rate, 405) + self.assertEqual(pos_inv.items[0].rate, 405) pos_inv.ignore_pricing_rule = 1 pos_inv.save() - self.assertEquals(pos_inv.ignore_pricing_rule, 1) + self.assertEqual(pos_inv.ignore_pricing_rule, 1) # rate should reset since pricing rules are ignored - self.assertEquals(pos_inv.items[0].rate, 450) + self.assertEqual(pos_inv.items[0].rate, 450) pos_inv.items[0].rate = 300 pos_inv.save() - self.assertEquals(pos_inv.items[0].rate, 300) + self.assertEqual(pos_inv.items[0].rate, 300) finally: item_price.delete() @@ -874,7 +864,7 @@ class TestPOSInvoice(unittest.TestCase): dn = create_delivery_note(item_code="_Test Serialized Item With Series", serial_no=serial_no) delivery_document_no = frappe.db.get_value("Serial No", serial_no, "delivery_document_no") - self.assertEquals(delivery_document_no, dn.name) + self.assertEqual(delivery_document_no, dn.name) init_user_and_profile() diff --git a/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py b/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py index 438ff9f3c4c..5b0d1cfa8ce 100644 --- a/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py +++ b/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py @@ -29,7 +29,7 @@ class POSInvoiceMergeLog(Document): for key, value in pos_occurences.items(): if len(value) > 1: error_list.append( - _("{} is added multiple times on rows: {}".format(frappe.bold(key), frappe.bold(value))) + _(f"{frappe.bold(key)} is added multiple times on rows: {frappe.bold(value)}") ) if error_list: @@ -56,7 +56,9 @@ class POSInvoiceMergeLog(Document): bold_pos_invoice = frappe.bold(d.pos_invoice) bold_status = frappe.bold(status) if docstatus != 1: - frappe.throw(_("Row #{}: POS Invoice {} is not submitted yet").format(d.idx, bold_pos_invoice)) + frappe.throw( + _("Row #{}: POS Invoice {} is not submitted yet").format(d.idx, bold_pos_invoice) + ) if status == "Consolidated": frappe.throw( _("Row #{}: POS Invoice {} has been {}").format(d.idx, bold_pos_invoice, bold_status) @@ -75,15 +77,17 @@ class POSInvoiceMergeLog(Document): d.idx, bold_return_against, bold_pos_invoice, bold_unconsolidated ) msg += " " - msg += _("Original invoice should be consolidated before or along with the return invoice.") + msg += _( + "Original invoice should be consolidated before or along with the return invoice." + ) msg += "

" - msg += _("You can add original invoice {} manually to proceed.").format(bold_return_against) + msg += _("You can add original invoice {} manually to proceed.").format( + bold_return_against + ) frappe.throw(msg) def on_submit(self): - pos_invoice_docs = [ - frappe.get_cached_doc("POS Invoice", d.pos_invoice) for d in self.pos_invoices - ] + pos_invoice_docs = [frappe.get_cached_doc("POS Invoice", d.pos_invoice) for d in self.pos_invoices] returns = [d for d in pos_invoice_docs if d.get("is_return") == 1] sales = [d for d in pos_invoice_docs if d.get("is_return") == 0] @@ -100,9 +104,7 @@ class POSInvoiceMergeLog(Document): self.update_pos_invoices(pos_invoice_docs, sales_invoice, credit_note) def on_cancel(self): - pos_invoice_docs = [ - frappe.get_cached_doc("POS Invoice", d.pos_invoice) for d in self.pos_invoices - ] + pos_invoice_docs = [frappe.get_cached_doc("POS Invoice", d.pos_invoice) for d in self.pos_invoices] self.update_pos_invoices(pos_invoice_docs) self.cancel_linked_invoices() @@ -192,7 +194,9 @@ class POSInvoiceMergeLog(Document): for t in taxes: if t.account_head == tax.account_head and t.cost_center == tax.cost_center: t.tax_amount = flt(t.tax_amount) + flt(tax.tax_amount_after_discount_amount) - t.base_tax_amount = flt(t.base_tax_amount) + flt(tax.base_tax_amount_after_discount_amount) + t.base_tax_amount = flt(t.base_tax_amount) + flt( + tax.base_tax_amount_after_discount_amount + ) update_item_wise_tax_detail(t, tax) found = True if not found: @@ -292,9 +296,7 @@ def update_item_wise_tax_detail(consolidate_tax_row, tax_row): else: consolidated_tax_detail.update({item_code: [tax_data[0], tax_data[1]]}) - consolidate_tax_row.item_wise_tax_detail = json.dumps( - consolidated_tax_detail, separators=(",", ":") - ) + consolidate_tax_row.item_wise_tax_detail = json.dumps(consolidated_tax_detail, separators=(",", ":")) def get_all_unconsolidated_invoices(): @@ -339,9 +341,7 @@ def consolidate_pos_invoices(pos_invoices=None, closing_entry=None): if len(invoices) >= 10 and closing_entry: closing_entry.set_status(update=True, status="Queued") - enqueue_job( - create_merge_logs, invoice_by_customer=invoice_by_customer, closing_entry=closing_entry - ) + enqueue_job(create_merge_logs, invoice_by_customer=invoice_by_customer, closing_entry=closing_entry) else: create_merge_logs(invoice_by_customer, closing_entry) @@ -389,9 +389,7 @@ def split_invoices(invoices): if not item.serial_no: continue - return_against_is_added = any( - d for d in _invoices if d.pos_invoice == pos_invoice.return_against - ) + return_against_is_added = any(d for d in _invoices if d.pos_invoice == pos_invoice.return_against) if return_against_is_added: break @@ -493,7 +491,7 @@ def enqueue_job(job, **kwargs): timeout=10000, event="processing_merge_logs", job_name=job_name, - now=frappe.conf.developer_mode or frappe.flags.in_test + now=frappe.conf.developer_mode or frappe.flags.in_test, ) if job == create_merge_logs: diff --git a/erpnext/accounts/doctype/pos_invoice_merge_log/test_pos_invoice_merge_log.py b/erpnext/accounts/doctype/pos_invoice_merge_log/test_pos_invoice_merge_log.py index 9e696f18b6a..144523624e8 100644 --- a/erpnext/accounts/doctype/pos_invoice_merge_log/test_pos_invoice_merge_log.py +++ b/erpnext/accounts/doctype/pos_invoice_merge_log/test_pos_invoice_merge_log.py @@ -28,15 +28,11 @@ class TestPOSInvoiceMergeLog(unittest.TestCase): pos_inv.submit() pos_inv2 = create_pos_invoice(rate=3200, do_not_submit=1) - pos_inv2.append( - "payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 3200} - ) + pos_inv2.append("payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 3200}) pos_inv2.submit() pos_inv3 = create_pos_invoice(customer="_Test Customer 2", rate=2300, do_not_submit=1) - pos_inv3.append( - "payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 2300} - ) + pos_inv3.append("payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 2300}) pos_inv3.submit() consolidate_pos_invoices() @@ -65,15 +61,11 @@ class TestPOSInvoiceMergeLog(unittest.TestCase): pos_inv.submit() pos_inv2 = create_pos_invoice(rate=3200, do_not_submit=1) - pos_inv2.append( - "payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 3200} - ) + pos_inv2.append("payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 3200}) pos_inv2.submit() pos_inv3 = create_pos_invoice(customer="_Test Customer 2", rate=2300, do_not_submit=1) - pos_inv3.append( - "payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 2300} - ) + pos_inv3.append("payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 2300}) pos_inv3.submit() pos_inv_cn = make_sales_return(pos_inv.name) @@ -309,7 +301,7 @@ class TestPOSInvoiceMergeLog(unittest.TestCase): init_user_and_profile() item_rates = [69, 59, 29] - for i in [1, 2]: + for _i in [1, 2]: inv = create_pos_invoice(is_return=1, do_not_save=1) inv.items = [] for rate in item_rates: diff --git a/erpnext/accounts/doctype/pos_profile/pos_profile.py b/erpnext/accounts/doctype/pos_profile/pos_profile.py index e8aee737f29..2c032dd718b 100644 --- a/erpnext/accounts/doctype/pos_profile/pos_profile.py +++ b/erpnext/accounts/doctype/pos_profile/pos_profile.py @@ -114,10 +114,8 @@ class POSProfile(Document): condition = " where pfu.default = 1 " pos_view_users = frappe.db.sql_list( - """select pfu.user - from `tabPOS Profile User` as pfu {0}""".format( - condition - ) + f"""select pfu.user + from `tabPOS Profile User` as pfu {condition}""" ) for user in pos_view_users: @@ -144,10 +142,8 @@ def get_item_groups(pos_profile): def get_child_nodes(group_type, root): lft, rgt = frappe.db.get_value(group_type, root, ["lft", "rgt"]) return frappe.db.sql( - """ Select name, lft, rgt from `tab{tab}` where - lft >= {lft} and rgt <= {rgt} order by lft""".format( - tab=group_type, lft=lft, rgt=rgt - ), + f""" Select name, lft, rgt from `tab{group_type}` where + lft >= {lft} and rgt <= {rgt} order by lft""", as_dict=1, ) diff --git a/erpnext/accounts/doctype/pos_profile/test_pos_profile.py b/erpnext/accounts/doctype/pos_profile/test_pos_profile.py index 788aa62701d..e03714bdffe 100644 --- a/erpnext/accounts/doctype/pos_profile/test_pos_profile.py +++ b/erpnext/accounts/doctype/pos_profile/test_pos_profile.py @@ -52,11 +52,9 @@ def get_customers_list(pos_profile=None): return ( frappe.db.sql( - """ select name, customer_name, customer_group, + f""" select name, customer_name, customer_group, territory, customer_pos_id from tabCustomer where disabled = 0 - and {cond}""".format( - cond=cond - ), + and {cond}""", tuple(customer_groups), as_dict=1, ) @@ -75,7 +73,7 @@ def get_items_list(pos_profile, company): cond = "and i.item_group in (%s)" % (", ".join(["%s"] * len(args_list))) return frappe.db.sql( - """ + f""" select i.name, i.item_code, i.item_name, i.description, i.item_group, i.has_batch_no, i.has_serial_no, i.is_stock_item, i.brand, i.stock_uom, i.image, @@ -88,10 +86,8 @@ def get_items_list(pos_profile, company): where i.disabled = 0 and i.has_variants = 0 and i.is_sales_item = 1 and i.is_fixed_asset = 0 {cond} - """.format( - cond=cond - ), - tuple([company] + args_list), + """, + tuple([company, *args_list]), as_dict=1, ) diff --git a/erpnext/accounts/doctype/pricing_rule/pricing_rule.py b/erpnext/accounts/doctype/pricing_rule/pricing_rule.py index e2b015bf021..f39aa026b47 100644 --- a/erpnext/accounts/doctype/pricing_rule/pricing_rule.py +++ b/erpnext/accounts/doctype/pricing_rule/pricing_rule.py @@ -77,9 +77,9 @@ class PricingRule(Document): if self.priority and cint(self.priority) == 1: throw( - _("As the field {0} is enabled, the value of the field {1} should be more than 1.").format( - frappe.bold("Apply Discount on Discounted Rate"), frappe.bold("Priority") - ) + _( + "As the field {0} is enabled, the value of the field {1} should be more than 1." + ).format(frappe.bold("Apply Discount on Discounted Rate"), frappe.bold("Priority")) ) def validate_applicable_for_selling_or_buying(self): @@ -273,9 +273,7 @@ def apply_pricing_rule(args, doc=None): def get_serial_no_for_item(args): from erpnext.stock.get_item_details import get_serial_no - item_details = frappe._dict( - {"doctype": args.doctype, "name": args.name, "serial_no": args.serial_no} - ) + item_details = frappe._dict({"doctype": args.doctype, "name": args.name, "serial_no": args.serial_no}) if args.get("parenttype") in ("Sales Invoice", "Delivery Note") and flt(args.stock_qty) > 0: item_details.serial_no = get_serial_no(args) return item_details @@ -373,9 +371,11 @@ def get_pricing_rule_for_item(args, doc=None, for_validate=False): ) if pricing_rule.apply_rule_on_other_items: - item_details["apply_rule_on_other_items"] = json.dumps(pricing_rule.apply_rule_on_other_items) + item_details["apply_rule_on_other_items"] = json.dumps( + pricing_rule.apply_rule_on_other_items + ) - if pricing_rule.coupon_code_based == 1 and args.coupon_code == None: + if pricing_rule.coupon_code_based == 1 and args.coupon_code is None: return item_details if not pricing_rule.validate_applied_rule: @@ -419,7 +419,6 @@ def update_args_for_pricing_rule(args): if args.transaction_type == "selling": if args.customer and not (args.customer_group and args.territory): - if args.quotation_to and args.quotation_to != "Customer": customer = frappe._dict() else: @@ -450,9 +449,9 @@ def get_pricing_rule_details(args, pricing_rule): def apply_price_discount_rule(pricing_rule, item_details, args): item_details.pricing_rule_for = pricing_rule.rate_or_discount - if ( - pricing_rule.margin_type in ["Amount", "Percentage"] and pricing_rule.currency == args.currency - ) or (pricing_rule.margin_type == "Percentage"): + if (pricing_rule.margin_type in ["Amount", "Percentage"] and pricing_rule.currency == args.currency) or ( + pricing_rule.margin_type == "Percentage" + ): item_details.margin_type = pricing_rule.margin_type item_details.has_margin = True @@ -595,7 +594,7 @@ def get_item_uoms(doctype, txt, searchfield, start, page_len, filters): return frappe.get_all( "UOM Conversion Detail", - filters={"parent": ("in", items), "uom": ("like", "{0}%".format(txt))}, + filters={"parent": ("in", items), "uom": ("like", f"{txt}%")}, fields=["distinct uom"], as_list=1, ) diff --git a/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py b/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py index 7f8cc4c63e0..ab52d6c9729 100644 --- a/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py +++ b/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py @@ -103,8 +103,6 @@ class TestPricingRule(unittest.TestCase): self.assertEqual(details.get("discount_percentage"), 15) def test_pricing_rule_for_margin(self): - from frappe import MandatoryError - from erpnext.stock.get_item_details import get_item_details test_record = { @@ -205,8 +203,6 @@ class TestPricingRule(unittest.TestCase): self.assertEqual(details.get("discount_percentage"), 10) def test_pricing_rule_for_variants(self): - from frappe import MandatoryError - from erpnext.stock.get_item_details import get_item_details if not frappe.db.exists("Item", "Test Variant PRT"): @@ -1055,8 +1051,7 @@ def delete_existing_pricing_rules(): "Pricing Rule Item Group", "Pricing Rule Brand", ]: - - frappe.db.sql("delete from `tab{0}`".format(doctype)) + frappe.db.sql(f"delete from `tab{doctype}`") def make_item_price(item, price_list_name, item_price): diff --git a/erpnext/accounts/doctype/pricing_rule/utils.py b/erpnext/accounts/doctype/pricing_rule/utils.py index 8396783ffa1..ce96a3d1240 100644 --- a/erpnext/accounts/doctype/pricing_rule/utils.py +++ b/erpnext/accounts/doctype/pricing_rule/utils.py @@ -101,14 +101,12 @@ def _get_pricing_rules(apply_on, args, values): if not args.get(apply_on_field): return [] - child_doc = "`tabPricing Rule {0}`".format(apply_on) + child_doc = f"`tabPricing Rule {apply_on}`" conditions = item_variant_condition = item_conditions = "" values[apply_on_field] = args.get(apply_on_field) if apply_on_field in ["item_code", "brand"]: - item_conditions = "{child_doc}.{apply_on_field}= %({apply_on_field})s".format( - child_doc=child_doc, apply_on_field=apply_on_field - ) + item_conditions = f"{child_doc}.{apply_on_field}= %({apply_on_field})s" if apply_on_field == "item_code": if args.get("uom", None): @@ -121,9 +119,7 @@ def _get_pricing_rules(apply_on, args, values): args.variant_of = frappe.get_cached_value("Item", args.item_code, "variant_of") if args.variant_of: - item_variant_condition = " or {child_doc}.item_code=%(variant_of)s ".format( - child_doc=child_doc - ) + item_variant_condition = f" or {child_doc}.item_code=%(variant_of)s " values["variant_of"] = args.variant_of elif apply_on_field == "item_group": item_conditions = _get_tree_conditions(args, "Item Group", child_doc, False) @@ -131,7 +127,7 @@ def _get_pricing_rules(apply_on, args, values): conditions += get_other_conditions(conditions, values, args) warehouse_conditions = _get_tree_conditions(args, "Warehouse", "`tabPricing Rule`") if warehouse_conditions: - warehouse_conditions = " and {0}".format(warehouse_conditions) + warehouse_conditions = f" and {warehouse_conditions}" if not args.price_list: args.price_list = None @@ -157,7 +153,7 @@ def _get_pricing_rules(apply_on, args, values): item_variant_condition=item_variant_condition, transaction_type=args.transaction_type, warehouse_cond=warehouse_conditions, - apply_on_other_field="other_{0}".format(apply_on_field), + apply_on_other_field=f"other_{apply_on_field}", conditions=conditions, ), values, @@ -196,14 +192,13 @@ def _get_tree_conditions(args, parenttype, table, allow_blank=True): frappe.throw(_("Invalid {0}").format(args.get(field))) parent_groups = frappe.db.sql_list( - """select name from `tab%s` - where lft<=%s and rgt>=%s""" - % (parenttype, "%s", "%s"), + """select name from `tab{}` + where lft<={} and rgt>={}""".format(parenttype, "%s", "%s"), (lft, rgt), ) if parenttype in ["Customer Group", "Item Group", "Territory"]: - parent_field = "parent_{0}".format(frappe.scrub(parenttype)) + parent_field = f"parent_{frappe.scrub(parenttype)}" root_name = frappe.db.get_list( parenttype, {"is_group": 1, parent_field: ("is", "not set")}, @@ -229,10 +224,10 @@ def _get_tree_conditions(args, parenttype, table, allow_blank=True): def get_other_conditions(conditions, values, args): for field in ["company", "customer", "supplier", "campaign", "sales_partner"]: if args.get(field): - conditions += " and ifnull(`tabPricing Rule`.{0}, '') in (%({1})s, '')".format(field, field) + conditions += f" and ifnull(`tabPricing Rule`.{field}, '') in (%({field})s, '')" values[field] = args.get(field) else: - conditions += " and ifnull(`tabPricing Rule`.{0}, '') = ''".format(field) + conditions += f" and ifnull(`tabPricing Rule`.{field}, '') = ''" for parenttype in ["Customer Group", "Territory", "Supplier Group"]: group_condition = _get_tree_conditions(args, parenttype, "`tabPricing Rule`") @@ -504,7 +499,7 @@ def get_qty_amount_data_for_cumulative(pr_doc, doc, items=None): "transaction_date" if frappe.get_meta(doctype).has_field("transaction_date") else "posting_date" ) - child_doctype = "{0} Item".format(doctype) + child_doctype = f"{doctype} Item" apply_on = frappe.scrub(pr_doc.get("apply_on")) values = [pr_doc.valid_from, pr_doc.valid_upto] @@ -514,9 +509,7 @@ def get_qty_amount_data_for_cumulative(pr_doc, doc, items=None): warehouses = get_child_warehouses(pr_doc.warehouse) condition += """ and `tab{child_doc}`.warehouse in ({warehouses}) - """.format( - child_doc=child_doctype, warehouses=",".join(["%s"] * len(warehouses)) - ) + """.format(child_doc=child_doctype, warehouses=",".join(["%s"] * len(warehouses))) values.extend(warehouses) @@ -528,16 +521,14 @@ def get_qty_amount_data_for_cumulative(pr_doc, doc, items=None): values.extend(items) data_set = frappe.db.sql( - """ SELECT `tab{child_doc}`.stock_qty, - `tab{child_doc}`.amount - FROM `tab{child_doc}`, `tab{parent_doc}` + f""" SELECT `tab{child_doctype}`.stock_qty, + `tab{child_doctype}`.amount + FROM `tab{child_doctype}`, `tab{doctype}` WHERE - `tab{child_doc}`.parent = `tab{parent_doc}`.name and `tab{parent_doc}`.{date_field} - between %s and %s and `tab{parent_doc}`.docstatus = 1 - {condition} group by `tab{child_doc}`.name - """.format( - parent_doc=doctype, child_doc=child_doctype, condition=condition, date_field=date_field - ), + `tab{child_doctype}`.parent = `tab{doctype}`.name and `tab{doctype}`.{date_field} + between %s and %s and `tab{doctype}`.docstatus = 1 + {condition} group by `tab{child_doctype}`.name + """, tuple(values), as_dict=1, ) @@ -556,11 +547,9 @@ def apply_pricing_rule_on_transaction(doc): conditions = get_other_conditions(conditions, values, doc) pricing_rules = frappe.db.sql( - """ Select `tabPricing Rule`.* from `tabPricing Rule` + f""" Select `tabPricing Rule`.* from `tabPricing Rule` where {conditions} and `tabPricing Rule`.disable = 0 - """.format( - conditions=conditions - ), + """, values, as_dict=1, ) @@ -583,7 +572,9 @@ def apply_pricing_rule_on_transaction(doc): continue if ( - d.validate_applied_rule and doc.get(field) is not None and doc.get(field) < d.get(pr_field) + d.validate_applied_rule + and doc.get(field) is not None + and doc.get(field) < d.get(pr_field) ): frappe.msgprint(_("User has not applied rule on the invoice {0}").format(doc.name)) else: @@ -643,9 +634,7 @@ def get_product_discount_rule(pricing_rule, item_details, args=None, doc=None): qty = pricing_rule.free_qty or 1 if pricing_rule.is_recursive: - transaction_qty = ( - args.get("qty") if args else doc.total_qty - ) - pricing_rule.apply_recursion_over + transaction_qty = (args.get("qty") if args else doc.total_qty) - pricing_rule.apply_recursion_over if transaction_qty: qty = flt(transaction_qty) * qty / pricing_rule.recurse_for if pricing_rule.round_free_qty: diff --git a/erpnext/accounts/doctype/process_deferred_accounting/test_process_deferred_accounting.py b/erpnext/accounts/doctype/process_deferred_accounting/test_process_deferred_accounting.py index 263621dcf4d..fddd9f83926 100644 --- a/erpnext/accounts/doctype/process_deferred_accounting/test_process_deferred_accounting.py +++ b/erpnext/accounts/doctype/process_deferred_accounting/test_process_deferred_accounting.py @@ -40,7 +40,7 @@ class TestProcessDeferredAccounting(unittest.TestCase): si.save() si.submit() - process_deferred_accounting = doc = frappe.get_doc( + process_deferred_accounting = frappe.get_doc( dict( doctype="Process Deferred Accounting", posting_date="2023-07-01", diff --git a/erpnext/accounts/doctype/process_payment_reconciliation/process_payment_reconciliation.py b/erpnext/accounts/doctype/process_payment_reconciliation/process_payment_reconciliation.py index a93fd46caf6..33cff14ac4e 100644 --- a/erpnext/accounts/doctype/process_payment_reconciliation/process_payment_reconciliation.py +++ b/erpnext/accounts/doctype/process_payment_reconciliation/process_payment_reconciliation.py @@ -41,9 +41,7 @@ class ProcessPaymentReconciliation(Document): def on_cancel(self): self.db_set("status", "Cancelled") - log = frappe.db.get_value( - "Process Payment Reconciliation Log", filters={"process_pr": self.name} - ) + log = frappe.db.get_value("Process Payment Reconciliation Log", filters={"process_pr": self.name}) if log: frappe.db.set_value("Process Payment Reconciliation Log", log, "status", "Cancelled") @@ -129,7 +127,7 @@ def trigger_job_for_doc(docname: str | None = None): frappe.db.set_value("Process Payment Reconciliation", docname, "status", "Running") job_name = f"start_processing_{docname}" if not is_job_running(job_name): - job = frappe.enqueue( + frappe.enqueue( method="erpnext.accounts.doctype.process_payment_reconciliation.process_payment_reconciliation.reconcile_based_on_filters", queue="long", is_async=True, @@ -147,7 +145,7 @@ def trigger_job_for_doc(docname: str | None = None): # Resume tasks for running doc job_name = f"start_processing_{docname}" if not is_job_running(job_name): - job = frappe.enqueue( + frappe.enqueue( method="erpnext.accounts.doctype.process_payment_reconciliation.process_payment_reconciliation.reconcile_based_on_filters", queue="long", is_async=True, @@ -224,7 +222,7 @@ def reconcile_based_on_filters(doc: None | str = None) -> None: job_name = f"process_{doc}_fetch_and_allocate" if not is_job_running(job_name): - job = frappe.enqueue( + frappe.enqueue( method="erpnext.accounts.doctype.process_payment_reconciliation.process_payment_reconciliation.fetch_and_allocate", queue="long", timeout="3600", @@ -245,7 +243,7 @@ def reconcile_based_on_filters(doc: None | str = None) -> None: if not allocated: job_name = f"process__{doc}_fetch_and_allocate" if not is_job_running(job_name): - job = frappe.enqueue( + frappe.enqueue( method="erpnext.accounts.doctype.process_payment_reconciliation.process_payment_reconciliation.fetch_and_allocate", queue="long", timeout="3600", @@ -263,7 +261,7 @@ def reconcile_based_on_filters(doc: None | str = None) -> None: else: reconcile_job_name = f"process_{doc}_reconcile" if not is_job_running(reconcile_job_name): - job = frappe.enqueue( + frappe.enqueue( method="erpnext.accounts.doctype.process_payment_reconciliation.process_payment_reconciliation.reconcile", queue="long", timeout="3600", @@ -350,7 +348,7 @@ def fetch_and_allocate(doc: str) -> None: reconcile_job_name = f"process_{doc}_reconcile" if not is_job_running(reconcile_job_name): - job = frappe.enqueue( + frappe.enqueue( method="erpnext.accounts.doctype.process_payment_reconciliation.process_payment_reconciliation.reconcile", queue="long", timeout="3600", @@ -391,7 +389,6 @@ def reconcile(doc: None | str = None) -> None: # If Payment Entry, update details only for newly linked references # This is for performance if allocations[0].reference_type == "Payment Entry": - references = [(x.invoice_type, x.invoice_number) for x in allocations] pe = frappe.get_doc(allocations[0].reference_type, allocations[0].reference_name) pe.flags.ignore_validate_update_after_submit = True @@ -405,13 +402,14 @@ def reconcile(doc: None | str = None) -> None: # Update reconciled count reconciled_count = frappe.db.count( - "Process Payment Reconciliation Log Allocations", filters={"parent": log, "reconciled": True} + "Process Payment Reconciliation Log Allocations", + filters={"parent": log, "reconciled": True}, ) frappe.db.set_value( "Process Payment Reconciliation Log", log, "reconciled_entries", reconciled_count ) - except Exception as err: + except Exception: # Update the parent doc about the exception frappe.db.rollback() @@ -449,20 +447,19 @@ def reconcile(doc: None | str = None) -> None: frappe.db.set_value("Process Payment Reconciliation Log", log, "reconciled", True) frappe.db.set_value("Process Payment Reconciliation", doc, "status", "Completed") else: - - if not (frappe.db.get_value("Process Payment Reconciliation", doc, "status") == "Paused"): + if not ( + frappe.db.get_value("Process Payment Reconciliation", doc, "status") == "Paused" + ): # trigger next batch in job # generate reconcile job name allocation = get_next_allocation(log) if allocation: - reconcile_job_name = ( - f"process_{doc}_reconcile_allocation_{allocation[0].idx}_{allocation[-1].idx}" - ) + reconcile_job_name = f"process_{doc}_reconcile_allocation_{allocation[0].idx}_{allocation[-1].idx}" else: reconcile_job_name = f"process_{doc}_reconcile" if not is_job_running(reconcile_job_name): - job = frappe.enqueue( + frappe.enqueue( method="erpnext.accounts.doctype.process_payment_reconciliation.process_payment_reconciliation.reconcile", queue="long", timeout="3600", diff --git a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py index 9c0bedd243f..0c266ce7947 100644 --- a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py +++ b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py @@ -423,9 +423,7 @@ def send_emails(document_name, from_scheduler=False, posting_date=None): else: new_to_date = add_months(new_to_date, 1 if doc.frequency == "Monthly" else 3) new_from_date = add_months(new_to_date, -1 * doc.filter_duration) - doc.add_comment( - "Comment", "Emails sent on: " + frappe.utils.format_datetime(frappe.utils.now()) - ) + doc.add_comment("Comment", "Emails sent on: " + frappe.utils.format_datetime(frappe.utils.now())) if doc.report == "General Ledger": doc.db_set("to_date", new_to_date, commit=True) doc.db_set("from_date", new_from_date, commit=True) diff --git a/erpnext/accounts/doctype/process_statement_of_accounts/test_process_statement_of_accounts.py b/erpnext/accounts/doctype/process_statement_of_accounts/test_process_statement_of_accounts.py index a3a74df4029..92dbb5ef273 100644 --- a/erpnext/accounts/doctype/process_statement_of_accounts/test_process_statement_of_accounts.py +++ b/erpnext/accounts/doctype/process_statement_of_accounts/test_process_statement_of_accounts.py @@ -1,7 +1,6 @@ # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt -import unittest import frappe from frappe.tests.utils import FrappeTestCase diff --git a/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py b/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py index 4d28d106604..e3278098f1a 100644 --- a/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py +++ b/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py @@ -100,9 +100,7 @@ class PromotionalScheme(Document): docnames = frappe.get_all("Pricing Rule", filters={"promotional_scheme": self.name}) for docname in docnames: - if frappe.db.exists( - "Pricing Rule Detail", {"pricing_rule": docname.name, "docstatus": ("<", 2)} - ): + if frappe.db.exists("Pricing Rule Detail", {"pricing_rule": docname.name, "docstatus": ("<", 2)}): raise_for_transaction_exists(self.name) if docnames and not transaction_exists: @@ -177,7 +175,7 @@ def _get_pricing_rules(doc, child_doc, discount_fields, rules=None): args = get_args_for_pricing_rule(doc) applicable_for = frappe.scrub(doc.get("applicable_for")) - for idx, d in enumerate(doc.get(child_doc)): + for _idx, d in enumerate(doc.get(child_doc)): if d.name in rules: if not args.get(applicable_for): docname = get_pricing_rule_docname(d) @@ -187,7 +185,14 @@ def _get_pricing_rules(doc, child_doc, discount_fields, rules=None): for applicable_for_value in args.get(applicable_for): docname = get_pricing_rule_docname(d, applicable_for, applicable_for_value) pr = prepare_pricing_rule( - args, doc, child_doc, discount_fields, d, docname, applicable_for, applicable_for_value + args, + doc, + child_doc, + discount_fields, + d, + docname, + applicable_for, + applicable_for_value, ) new_doc.append(pr) @@ -213,7 +218,7 @@ def _get_pricing_rules(doc, child_doc, discount_fields, rules=None): def get_pricing_rule_docname( - row: dict, applicable_for: str = None, applicable_for_value: str = None + row: dict, applicable_for: str | None = None, applicable_for_value: str | None = None ) -> str: fields = ["promotional_scheme_id", "name"] filters = {"promotional_scheme_id": row.name} diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py index f54787de717..b53627a682f 100644 --- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py +++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py @@ -55,7 +55,7 @@ form_grid_templates = {"items": "templates/form_grid/item_grid.html"} class PurchaseInvoice(BuyingController): def __init__(self, *args, **kwargs): - super(PurchaseInvoice, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.status_updater = [ { "source_dt": "Purchase Invoice Item", @@ -72,7 +72,7 @@ class PurchaseInvoice(BuyingController): ] def onload(self): - super(PurchaseInvoice, self).onload() + super().onload() supplier_tds = frappe.db.get_value("Supplier", self.supplier, "tax_withholding_category") self.set_onload("supplier_tds", supplier_tds) @@ -92,7 +92,7 @@ class PurchaseInvoice(BuyingController): self.validate_posting_time() - super(PurchaseInvoice, self).validate() + super().validate() if not self.is_return: self.po_required() @@ -155,7 +155,6 @@ class PurchaseInvoice(BuyingController): if flt(self.paid_amount) + flt(self.write_off_amount) - flt( self.get("rounded_total") or self.grand_total ) > 1 / (10 ** (self.precision("base_grand_total") + 1)): - frappe.throw(_("""Paid amount + Write Off Amount can not be greater than Grand Total""")) def create_remarks(self): @@ -184,7 +183,7 @@ class PurchaseInvoice(BuyingController): self.tax_withholding_category = tds_category self.set_onload("supplier_tds", tds_category) - super(PurchaseInvoice, self).set_missing_values(for_validate) + super().set_missing_values(for_validate) def validate_credit_to_acc(self): if not self.credit_to: @@ -218,12 +217,12 @@ class PurchaseInvoice(BuyingController): check_list = [] for d in self.get("items"): - if d.purchase_order and not d.purchase_order in check_list and not d.purchase_receipt: + if d.purchase_order and d.purchase_order not in check_list and not d.purchase_receipt: check_list.append(d.purchase_order) check_on_hold_or_closed_status("Purchase Order", d.purchase_order) def validate_with_previous_doc(self): - super(PurchaseInvoice, self).validate_with_previous_doc( + super().validate_with_previous_doc( { "Purchase Order": { "ref_dn_field": "purchase_order", @@ -271,7 +270,7 @@ class PurchaseInvoice(BuyingController): exc=WarehouseMissingError, ) - super(PurchaseInvoice, self).validate_warehouse() + super().validate_warehouse() def validate_item_code(self): for d in self.get("items"): @@ -307,7 +306,6 @@ class PurchaseInvoice(BuyingController): or not frappe.db.get_value("Purchase Order Item", item.po_detail, "delivered_by_supplier") ) ): - if self.update_stock and item.warehouse and (not item.from_warehouse): if ( for_validate @@ -335,12 +333,16 @@ class PurchaseInvoice(BuyingController): if negative_expense_booked_in_pr: if ( - for_validate and item.expense_account and item.expense_account != stock_not_billed_account + for_validate + and item.expense_account + and item.expense_account != stock_not_billed_account ): msg = _( "Row {0}: Expense Head changed to {1} because expense is booked against this account in Purchase Receipt {2}" ).format( - item.idx, frappe.bold(stock_not_billed_account), frappe.bold(item.purchase_receipt) + item.idx, + frappe.bold(stock_not_billed_account), + frappe.bold(item.purchase_receipt), ) frappe.msgprint(msg, title=_("Expense Head Changed")) @@ -349,7 +351,9 @@ class PurchaseInvoice(BuyingController): # If no purchase receipt present then book expense in 'Stock Received But Not Billed' # This is done in cases when Purchase Invoice is created before Purchase Receipt if ( - for_validate and item.expense_account and item.expense_account != stock_not_billed_account + for_validate + and item.expense_account + and item.expense_account != stock_not_billed_account ): msg = _( "Row {0}: Expense Head changed to {1} as no Purchase Receipt is created against Item {2}." @@ -400,7 +404,6 @@ class PurchaseInvoice(BuyingController): def po_required(self): if frappe.db.get_value("Buying Settings", None, "po_required") == "Yes": - if frappe.get_value( "Supplier", self.supplier, "allow_purchase_invoice_creation_without_purchase_order" ): @@ -410,7 +413,9 @@ class PurchaseInvoice(BuyingController): if not d.purchase_order: msg = _("Purchase Order Required for item {}").format(frappe.bold(d.item_code)) msg += "

" - msg += _("To submit the invoice without purchase order please set {0} as {1} in {2}").format( + msg += _( + "To submit the invoice without purchase order please set {0} as {1} in {2}" + ).format( frappe.bold(_("Purchase Order Required")), frappe.bold("No"), get_link_to_form("Buying Settings", "Buying Settings", "Buying Settings"), @@ -420,7 +425,6 @@ class PurchaseInvoice(BuyingController): def pr_required(self): stock_items = self.get_stock_items() if frappe.db.get_value("Buying Settings", None, "pr_required") == "Yes": - if frappe.get_value( "Supplier", self.supplier, "allow_purchase_invoice_creation_without_purchase_receipt" ): @@ -453,7 +457,8 @@ class PurchaseInvoice(BuyingController): frappe.throw(_("Purchase Order {0} is not submitted").format(d.purchase_order)) if d.purchase_receipt: submitted = frappe.db.sql( - "select name from `tabPurchase Receipt` where docstatus = 1 and name = %s", d.purchase_receipt + "select name from `tabPurchase Receipt` where docstatus = 1 and name = %s", + d.purchase_receipt, ) if not submitted: frappe.throw(_("Purchase Receipt {0} is not submitted").format(d.purchase_receipt)) @@ -501,7 +506,9 @@ class PurchaseInvoice(BuyingController): for item in self.get("items"): if item.purchase_receipt: frappe.throw( - _("Stock cannot be updated against Purchase Receipt {0}").format(item.purchase_receipt) + _("Stock cannot be updated against Purchase Receipt {0}").format( + item.purchase_receipt + ) ) def validate_for_repost(self): @@ -511,7 +518,7 @@ class PurchaseInvoice(BuyingController): validate_docs_for_deferred_accounting([], [self.name]) def on_submit(self): - super(PurchaseInvoice, self).on_submit() + super().on_submit() self.check_prev_docstatus() @@ -551,9 +558,7 @@ class PurchaseInvoice(BuyingController): if self.update_stock == 1: self.repost_future_sle_and_gle() - if ( - frappe.db.get_single_value("Buying Settings", "project_update_frequency") == "Each Transaction" - ): + if frappe.db.get_single_value("Buying Settings", "project_update_frequency") == "Each Transaction": self.update_project() update_linked_doc(self.doctype, self.name, self.inter_company_invoice_reference) @@ -733,9 +738,7 @@ class PurchaseInvoice(BuyingController): exchange_rate_map, net_rate_map = get_purchase_document_details(self) provisional_accounting_for_non_stock_items = cint( - frappe.db.get_value( - "Company", self.company, "enable_provisional_accounting_for_non_stock_items" - ) + frappe.db.get_value("Company", self.company, "enable_provisional_accounting_for_non_stock_items") ) if provisional_accounting_for_non_stock_items: self.get_provisional_accounts() @@ -744,7 +747,7 @@ class PurchaseInvoice(BuyingController): if flt(item.base_net_amount): account_currency = get_account_currency(item.expense_account) if item.item_code: - asset_category = frappe.get_cached_value("Item", item.item_code, "asset_category") + frappe.get_cached_value("Item", item.item_code, "asset_category") if ( self.update_stock @@ -849,7 +852,9 @@ class PurchaseInvoice(BuyingController): if flt(item.rm_supp_cost): supplier_warehouse_account = warehouse_account[self.supplier_warehouse]["account"] if not supplier_warehouse_account: - frappe.throw(_("Please set account in Warehouse {0}").format(self.supplier_warehouse)) + frappe.throw( + _("Please set account in Warehouse {0}").format(self.supplier_warehouse) + ) gl_entries.append( self.get_gl_dict( { @@ -899,10 +904,9 @@ class PurchaseInvoice(BuyingController): and self.conversion_rate != exchange_rate_map[item.purchase_receipt] and item.net_rate == net_rate_map[item.pr_detail] ): - - discrepancy_caused_by_exchange_rate_difference = (item.qty * item.net_rate) * ( - exchange_rate_map[item.purchase_receipt] - self.conversion_rate - ) + discrepancy_caused_by_exchange_rate_difference = ( + item.qty * item.net_rate + ) * (exchange_rate_map[item.purchase_receipt] - self.conversion_rate) gl_entries.append( self.get_gl_dict( @@ -983,7 +987,9 @@ class PurchaseInvoice(BuyingController): default_provisional_account = self.get_company_default("default_provisional_account") provisional_accounts = set( [ - d.provisional_expense_account if d.provisional_expense_account else default_provisional_account + d.provisional_expense_account + if d.provisional_expense_account + else default_provisional_account for d in pr_items ] ) @@ -1040,9 +1046,7 @@ class PurchaseInvoice(BuyingController): }, ) - def make_stock_adjustment_entry( - self, gl_entries, item, voucher_wise_stock_value, account_currency - ): + def make_stock_adjustment_entry(self, gl_entries, item, voucher_wise_stock_value, account_currency): net_amt_precision = item.precision("base_net_amount") val_rate_db_precision = 6 if cint(item.precision("valuation_rate")) <= 6 else 9 @@ -1058,7 +1062,6 @@ class PurchaseInvoice(BuyingController): and warehouse_debit_amount != flt(voucher_wise_stock_value.get((item.name, item.warehouse)), net_amt_precision) ): - cost_of_goods_sold_account = self.get_company_default("default_expense_account") stock_amount = flt(voucher_wise_stock_value.get((item.name, item.warehouse)), net_amt_precision) stock_adjustment_amt = warehouse_debit_amount - stock_amount @@ -1281,9 +1284,7 @@ class PurchaseInvoice(BuyingController): # base_rounding_adjustment may become zero due to small precision # eg: rounding_adjustment = 0.01 and exchange rate = 0.05 and precision of base_rounding_adjustment is 2 # then base_rounding_adjustment becomes zero and error is thrown in GL Entry - if ( - not self.is_internal_transfer() and self.rounding_adjustment and self.base_rounding_adjustment - ): + if not self.is_internal_transfer() and self.rounding_adjustment and self.base_rounding_adjustment: round_off_account, round_off_cost_center = get_round_off_account_and_cost_center( self.company, "Purchase Invoice", self.name, self.use_company_roundoff_cost_center ) @@ -1306,7 +1307,7 @@ class PurchaseInvoice(BuyingController): def on_cancel(self): check_if_return_invoice_linked_with_payment_entry(self) - super(PurchaseInvoice, self).on_cancel() + super().on_cancel() self.check_on_hold_or_closed_status() @@ -1337,9 +1338,7 @@ class PurchaseInvoice(BuyingController): if self.update_stock == 1: self.repost_future_sle_and_gle() - if ( - frappe.db.get_single_value("Buying Settings", "project_update_frequency") == "Each Transaction" - ): + if frappe.db.get_single_value("Buying Settings", "project_update_frequency") == "Each Transaction": self.update_project() self.db_set("status", "Cancelled") @@ -1370,9 +1369,7 @@ class PurchaseInvoice(BuyingController): pj = frappe.qb.DocType("Project") for proj, value in projects.items(): - res = ( - frappe.qb.from_(pj).select(pj.total_purchase_cost).where(pj.name == proj).for_update().run() - ) + res = frappe.qb.from_(pj).select(pj.total_purchase_cost).where(pj.name == proj).for_update().run() current_purchase_cost = res and res[0][0] or 0 frappe.db.set_value("Project", proj, "total_purchase_cost", current_purchase_cost + value) @@ -1640,9 +1637,7 @@ def get_purchase_document_details(doc): ) net_rate_map = frappe._dict( - frappe.get_all( - child_doctype, filters={"name": ("in", items)}, fields=["name", "net_rate"], as_list=1 - ) + frappe.get_all(child_doctype, filters={"name": ("in", items)}, fields=["name", "net_rate"], as_list=1) ) return exchange_rate_map, net_rate_map diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py index ba97fc685a3..109b2e8ea62 100644 --- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py +++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py @@ -2,8 +2,6 @@ # License: GNU General Public License v3. See license.txt -import unittest - import frappe from frappe.tests.utils import FrappeTestCase, change_settings from frappe.utils import add_days, cint, flt, getdate, nowdate, today @@ -252,7 +250,6 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): self.assertEqual(pi.on_hold, 0) def test_gl_entries_with_perpetual_inventory_against_pr(self): - pr = make_purchase_receipt( company="_Test Company with perpetual inventory", supplier_warehouse="Work In Progress - TCP1", @@ -303,7 +300,7 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): ] ) - for i, gle in enumerate(gl_entries): + for _i, gle in enumerate(gl_entries): self.assertEqual(expected_values[gle.account][0], gle.account) self.assertEqual(expected_values[gle.account][1], gle.debit) self.assertEqual(expected_values[gle.account][2], gle.credit) @@ -327,9 +324,7 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): pi.submit() # Get exchnage gain and loss account - exchange_gain_loss_account = frappe.db.get_value( - "Company", pi.company, "exchange_gain_loss_account" - ) + exchange_gain_loss_account = frappe.db.get_value("Company", pi.company, "exchange_gain_loss_account") # fetching the latest GL Entry with exchange gain and loss account account amount = frappe.db.get_value( @@ -545,12 +540,10 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): project = frappe.get_doc("Project", {"project_name": "_Test Project for Purchase"}) existing_purchase_cost = frappe.db.sql( - """select sum(base_net_amount) + f"""select sum(base_net_amount) from `tabPurchase Invoice Item` - where project = '{0}' - and docstatus=1""".format( - project.name - ) + where project = '{project.name}' + and docstatus=1""" ) existing_purchase_cost = existing_purchase_cost and existing_purchase_cost[0][0] or 0 @@ -725,7 +718,7 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): "credit", "credit_in_account_currency", ): - for i, gle in enumerate(gl_entries): + for _i, gle in enumerate(gl_entries): self.assertEqual(expected_values[gle.account][field], gle[field]) # Check for valid currency @@ -747,7 +740,6 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): self.assertFalse(gle) def test_purchase_invoice_update_stock_gl_entry_with_perpetual_inventory(self): - pi = make_purchase_invoice( update_stock=1, posting_date=frappe.utils.nowdate(), @@ -776,13 +768,12 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): (d[0], d) for d in [[pi.credit_to, 0.0, 250.0], [stock_in_hand_account, 250.0, 0.0]] ) - for i, gle in enumerate(gl_entries): + for _i, gle in enumerate(gl_entries): self.assertEqual(expected_gl_entries[gle.account][0], gle.account) self.assertEqual(expected_gl_entries[gle.account][1], gle.debit) self.assertEqual(expected_gl_entries[gle.account][2], gle.credit) def test_purchase_invoice_for_is_paid_and_update_stock_gl_entry_with_perpetual_inventory(self): - pi = make_purchase_invoice( update_stock=1, posting_date=frappe.utils.nowdate(), @@ -817,7 +808,7 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): ] ) - for i, gle in enumerate(gl_entries): + for _i, gle in enumerate(gl_entries): self.assertEqual(expected_gl_entries[gle.account][0], gle.account) self.assertEqual(expected_gl_entries[gle.account][1], gle.debit) self.assertEqual(expected_gl_entries[gle.account][2], gle.credit) @@ -1015,12 +1006,8 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): def test_duplicate_due_date_in_terms(self): pi = make_purchase_invoice(do_not_save=1) - pi.append( - "payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50) - ) - pi.append( - "payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50) - ) + pi.append("payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50)) + pi.append("payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50)) self.assertRaises(frappe.ValidationError, pi.insert) @@ -1058,9 +1045,7 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): cost_center = "_Test Cost Center for BS Account - _TC" create_cost_center(cost_center_name="_Test Cost Center for BS Account", company="_Test Company") - pi = make_purchase_invoice_against_cost_center( - cost_center=cost_center, credit_to="Creditors - _TC" - ) + pi = make_purchase_invoice_against_cost_center(cost_center=cost_center, credit_to="Creditors - _TC") self.assertEqual(pi.cost_center, cost_center) expected_values = { @@ -1522,9 +1507,7 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): def test_provisional_accounting_entry(self): setup_provisional_accounting() - pr = make_purchase_receipt( - item_code="_Test Non Stock Item", posting_date=add_days(nowdate(), -2) - ) + pr = make_purchase_receipt(item_code="_Test Non Stock Item", posting_date=add_days(nowdate(), -2)) pi = create_purchase_invoice_from_receipt(pr.name) pi.set_posting_time = 1 @@ -1533,7 +1516,7 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): pi.save() pi.submit() - self.assertEquals(pr.items[0].provisional_expense_account, "Provision Account - _TC") + self.assertEqual(pr.items[0].provisional_expense_account, "Provision Account - _TC") # Check GLE for Purchase Invoice expected_gle = [ @@ -1560,9 +1543,7 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): ["_Test Account Cost for Goods Sold - _TC", 250, 0, pi.posting_date], ] - check_gl_entries( - self, pr.name, expected_gle_for_purchase_receipt_post_pi_cancel, pr.posting_date - ) + check_gl_entries(self, pr.name, expected_gle_for_purchase_receipt_post_pi_cancel, pr.posting_date) toggle_provisional_accounting_setting() @@ -1611,9 +1592,7 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): ["_Test Account Cost for Goods Sold - _TC", 5000, 0, pi.posting_date], ] - check_gl_entries( - self, pr.name, expected_gle_for_purchase_receipt_post_pi_cancel, pr.posting_date - ) + check_gl_entries(self, pr.name, expected_gle_for_purchase_receipt_post_pi_cancel, pr.posting_date) toggle_provisional_accounting_setting() @@ -1659,9 +1638,7 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): def test_adjust_incoming_rate(self): frappe.db.set_single_value("Buying Settings", "maintain_same_rate", 0) - frappe.db.set_single_value( - "Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate", 1 - ) + frappe.db.set_single_value("Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate", 1) # Increase the cost of the item @@ -1713,9 +1690,7 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): ) self.assertEqual(stock_value_difference, 50) - frappe.db.set_single_value( - "Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate", 0 - ) + frappe.db.set_single_value("Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate", 0) # Don't adjust incoming rate @@ -1745,7 +1720,6 @@ class TestPurchaseInvoice(FrappeTestCase, StockTestMixin): frappe.db.set_single_value("Buying Settings", "maintain_same_rate", 1) def test_item_less_defaults(self): - pi = frappe.new_doc("Purchase Invoice") pi.supplier = "_Test Supplier" pi.company = "_Test Company" @@ -2178,9 +2152,7 @@ def setup_provisional_accounting(**args): parent_account=args.parent_account or "Current Liabilities - _TC", company=company, ) - toggle_provisional_accounting_setting( - enable=1, company=company, provisional_account=provisional_account - ) + toggle_provisional_accounting_setting(enable=1, company=company, provisional_account=provisional_account) def toggle_provisional_accounting_setting(**args): diff --git a/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.py b/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.py index 70d29bfda25..7c54b53120a 100644 --- a/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.py +++ b/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.py @@ -17,4 +17,4 @@ class PurchaseTaxesandChargesTemplate(Document): def autoname(self): if self.company and self.title: abbr = frappe.get_cached_value("Company", self.company, "abbr") - self.name = "{0} - {1}".format(self.title, abbr) + self.name = f"{self.title} - {abbr}" diff --git a/erpnext/accounts/doctype/repost_accounting_ledger/repost_accounting_ledger.py b/erpnext/accounts/doctype/repost_accounting_ledger/repost_accounting_ledger.py index 28355964cfa..15478ab8633 100644 --- a/erpnext/accounts/doctype/repost_accounting_ledger/repost_accounting_ledger.py +++ b/erpnext/accounts/doctype/repost_accounting_ledger/repost_accounting_ledger.py @@ -9,7 +9,7 @@ from frappe.utils.data import comma_and class RepostAccountingLedger(Document): def __init__(self, *args, **kwargs): - super(RepostAccountingLedger, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._allowed_types = get_allowed_types_from_settings() def validate(self): @@ -136,7 +136,9 @@ def start_repost(account_repost_doc=str) -> None: doc = frappe.get_doc(x.voucher_type, x.voucher_no) if repost_doc.delete_cancelled_entries: - frappe.db.delete("GL Entry", filters={"voucher_type": doc.doctype, "voucher_no": doc.name}) + frappe.db.delete( + "GL Entry", filters={"voucher_type": doc.doctype, "voucher_no": doc.name} + ) frappe.db.delete( "Payment Ledger Entry", filters={"voucher_type": doc.doctype, "voucher_no": doc.name} ) @@ -182,7 +184,9 @@ def validate_docs_for_deferred_accounting(sales_docs, purchase_docs): if docs_with_deferred_revenue or docs_with_deferred_expense: frappe.throw( _("Documents: {0} have deferred revenue/expense enabled for them. Cannot repost.").format( - frappe.bold(comma_and([x[0] for x in docs_with_deferred_expense + docs_with_deferred_revenue])) + frappe.bold( + comma_and([x[0] for x in docs_with_deferred_expense + docs_with_deferred_revenue]) + ) ) ) diff --git a/erpnext/accounts/doctype/repost_accounting_ledger/test_repost_accounting_ledger.py b/erpnext/accounts/doctype/repost_accounting_ledger/test_repost_accounting_ledger.py index d6f7096132f..f631ef437d6 100644 --- a/erpnext/accounts/doctype/repost_accounting_ledger/test_repost_accounting_ledger.py +++ b/erpnext/accounts/doctype/repost_accounting_ledger/test_repost_accounting_ledger.py @@ -9,7 +9,6 @@ from frappe.utils import add_days, nowdate, today from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry from erpnext.accounts.doctype.payment_request.payment_request import make_payment_request -from erpnext.accounts.doctype.repost_accounting_ledger.repost_accounting_ledger import start_repost from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice from erpnext.accounts.test.accounts_mixin import AccountsTestMixin from erpnext.accounts.utils import get_fiscal_year diff --git a/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.py b/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.py index d603635ac5a..d383b870b2c 100644 --- a/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.py +++ b/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.py @@ -40,7 +40,7 @@ def start_payment_ledger_repost(docname=None): frappe.db.set_value(repost_doc.doctype, repost_doc.name, "repost_error_log", "") frappe.db.set_value(repost_doc.doctype, repost_doc.name, "repost_status", "Completed") - except Exception as e: + except Exception: frappe.db.rollback() traceback = frappe.get_traceback(with_context=True) @@ -53,7 +53,7 @@ def start_payment_ledger_repost(docname=None): class RepostPaymentLedger(Document): def __init__(self, *args, **kwargs): - super(RepostPaymentLedger, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.vouchers = [] def before_validate(self): diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py index 6a1a5f3a7c9..3ea4b91641c 100644 --- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py +++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py @@ -50,7 +50,7 @@ form_grid_templates = {"items": "templates/form_grid/item_grid.html"} class SalesInvoice(SellingController): def __init__(self, *args, **kwargs): - super(SalesInvoice, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.status_updater = [ { "source_dt": "Sales Invoice Item", @@ -87,7 +87,7 @@ class SalesInvoice(SellingController): self.indicator_title = _("Paid") def validate(self): - super(SalesInvoice, self).validate() + super().validate() self.validate_auto_set_posting_time() if not (self.is_pos or self.is_debit_note): @@ -293,9 +293,7 @@ class SalesInvoice(SellingController): self.update_time_sheet(self.name) - if ( - frappe.db.get_single_value("Selling Settings", "sales_update_frequency") == "Each Transaction" - ): + if frappe.db.get_single_value("Selling Settings", "sales_update_frequency") == "Each Transaction": update_company_current_month_sales(self.company) self.update_project() update_linked_doc(self.doctype, self.name, self.inter_company_invoice_reference) @@ -308,9 +306,7 @@ class SalesInvoice(SellingController): and not self.dont_create_loyalty_points ): self.make_loyalty_point_entry() - elif ( - self.is_return and self.return_against and not self.is_consolidated and self.loyalty_program - ): + elif self.is_return and self.return_against and not self.is_consolidated and self.loyalty_program: against_si_doc = frappe.get_doc("Sales Invoice", self.return_against) against_si_doc.delete_loyalty_point_entry() against_si_doc.make_loyalty_point_entry() @@ -339,11 +335,11 @@ class SalesInvoice(SellingController): def check_if_consolidated_invoice(self): # since POS Invoice extends Sales Invoice, we explicitly check if doctype is Sales Invoice if self.doctype == "Sales Invoice" and self.is_consolidated: - invoice_or_credit_note = ( - "consolidated_credit_note" if self.is_return else "consolidated_invoice" - ) + invoice_or_credit_note = "consolidated_credit_note" if self.is_return else "consolidated_invoice" pos_closing_entry = frappe.get_all( - "POS Invoice Merge Log", filters={invoice_or_credit_note: self.name}, pluck="pos_closing_entry" + "POS Invoice Merge Log", + filters={invoice_or_credit_note: self.name}, + pluck="pos_closing_entry", ) if pos_closing_entry and pos_closing_entry[0]: msg = _("To cancel a {} you need to cancel the POS Closing Entry {}.").format( @@ -355,13 +351,13 @@ class SalesInvoice(SellingController): def before_cancel(self): self.check_if_consolidated_invoice() - super(SalesInvoice, self).before_cancel() + super().before_cancel() self.update_time_sheet(None) def on_cancel(self): check_if_return_invoice_linked_with_payment_entry(self) - super(SalesInvoice, self).on_cancel() + super().on_cancel() self.check_sales_order_on_hold_or_close("sales_order") @@ -391,16 +387,12 @@ class SalesInvoice(SellingController): self.db_set("status", "Cancelled") self.db_set("repost_required", 0) - if ( - frappe.db.get_single_value("Selling Settings", "sales_update_frequency") == "Each Transaction" - ): + if frappe.db.get_single_value("Selling Settings", "sales_update_frequency") == "Each Transaction": update_company_current_month_sales(self.company) self.update_project() if not self.is_return and not self.is_consolidated and self.loyalty_program: self.delete_loyalty_point_entry() - elif ( - self.is_return and self.return_against and not self.is_consolidated and self.loyalty_program - ): + elif self.is_return and self.return_against and not self.is_consolidated and self.loyalty_program: against_si_doc = frappe.get_doc("Sales Invoice", self.return_against) against_si_doc.delete_loyalty_point_entry() against_si_doc.make_loyalty_point_entry() @@ -504,7 +496,7 @@ class SalesInvoice(SellingController): if not self.due_date and self.customer: self.due_date = get_due_date(self.posting_date, "Customer", self.customer, self.company) - super(SalesInvoice, self).set_missing_values(for_validate) + super().set_missing_values(for_validate) print_format = pos.get("print_format") if pos else None if not print_format and not cint(frappe.db.get_value("Print Format", "POS Invoice", "disabled")): @@ -694,7 +686,8 @@ class SalesInvoice(SellingController): if account.report_type != "Balance Sheet": msg = ( - _("Please ensure {} account is a Balance Sheet account.").format(frappe.bold("Debit To")) + " " + _("Please ensure {} account is a Balance Sheet account.").format(frappe.bold("Debit To")) + + " " ) msg += _( "You can change the parent account to a Balance Sheet account or select a different account." @@ -723,11 +716,16 @@ class SalesInvoice(SellingController): ) def validate_with_previous_doc(self): - super(SalesInvoice, self).validate_with_previous_doc( + super().validate_with_previous_doc( { "Sales Order": { "ref_dn_field": "sales_order", - "compare_fields": [["customer", "="], ["company", "="], ["project", "="], ["currency", "="]], + "compare_fields": [ + ["customer", "="], + ["company", "="], + ["project", "="], + ["currency", "="], + ], }, "Sales Order Item": { "ref_dn_field": "so_detail", @@ -737,7 +735,12 @@ class SalesInvoice(SellingController): }, "Delivery Note": { "ref_dn_field": "delivery_note", - "compare_fields": [["customer", "="], ["company", "="], ["project", "="], ["currency", "="]], + "compare_fields": [ + ["customer", "="], + ["company", "="], + ["project", "="], + ["currency", "="], + ], }, "Delivery Note Item": { "ref_dn_field": "dn_detail", @@ -792,13 +795,14 @@ class SalesInvoice(SellingController): } for key, value in prev_doc_field_map.items(): if frappe.db.get_single_value("Selling Settings", value[0]) == "Yes": - if frappe.get_value("Customer", self.customer, value[0]): continue for d in self.get("items"): if d.item_code and not d.get(key.lower().replace(" ", "_")) and not self.get(value[1]): - msgprint(_("{0} is mandatory for Item {1}").format(key, d.item_code), raise_exception=1) + msgprint( + _("{0} is mandatory for Item {1}").format(key, d.item_code), raise_exception=1 + ) def validate_proj_cust(self): """check for does customer belong to same project as entered..""" @@ -825,7 +829,7 @@ class SalesInvoice(SellingController): msgprint(_("Item Code required at Row No {0}").format(d.idx), raise_exception=True) def validate_warehouse(self): - super(SalesInvoice, self).validate_warehouse() + super().validate_warehouse() for d in self.get_item_list(): if ( @@ -1154,7 +1158,9 @@ class SalesInvoice(SellingController): asset.db_set("disposal_date", None) if asset.calculate_depreciation: - posting_date = frappe.db.get_value("Sales Invoice", self.return_against, "posting_date") + posting_date = frappe.db.get_value( + "Sales Invoice", self.return_against, "posting_date" + ) reverse_depreciation_entry_made_after_disposal(asset, posting_date) reset_depreciation_schedule(asset, self.posting_date) @@ -1188,7 +1194,9 @@ class SalesInvoice(SellingController): else item.deferred_revenue_account ) - amount, base_amount = self.get_amount_and_base_amount(item, enable_discount_accounting) + amount, base_amount = self.get_amount_and_base_amount( + item, enable_discount_accounting + ) account_currency = get_account_currency(income_account) gl_entries.append( @@ -1212,7 +1220,7 @@ class SalesInvoice(SellingController): # expense account gl entries if cint(self.update_stock) and erpnext.is_perpetual_inventory_enabled(self.company): - gl_entries += super(SalesInvoice, self).get_gl_entries() + gl_entries += super().get_gl_entries() def get_asset(self, item): if item.get("asset"): @@ -1275,7 +1283,6 @@ class SalesInvoice(SellingController): def make_pos_gl_entries(self, gl_entries): if cint(self.is_pos): - skip_change_gl_entries = not cint( frappe.db.get_single_value("Accounts Settings", "post_change_gl_entries") ) @@ -1434,7 +1441,9 @@ class SalesInvoice(SellingController): "credit_in_account_currency": flt( self.rounding_adjustment, self.precision("rounding_adjustment") ), - "credit": flt(self.base_rounding_adjustment, self.precision("base_rounding_adjustment")), + "credit": flt( + self.base_rounding_adjustment, self.precision("base_rounding_adjustment") + ), "cost_center": round_off_cost_center if self.use_company_roundoff_cost_center else (self.cost_center or round_off_cost_center), @@ -1456,7 +1465,11 @@ class SalesInvoice(SellingController): ) billed_amt = billed_amt and billed_amt[0][0] or 0 frappe.db.set_value( - "Delivery Note Item", d.dn_detail, "billed_amt", billed_amt, update_modified=update_modified + "Delivery Note Item", + d.dn_detail, + "billed_amt", + billed_amt, + update_modified=update_modified, ) updated_delivery_notes.append(d.delivery_note) elif d.so_detail: @@ -1564,7 +1577,6 @@ class SalesInvoice(SellingController): and getdate(lp_details.from_date) <= getdate(self.posting_date) and (not lp_details.to_date or getdate(lp_details.to_date) >= getdate(self.posting_date)) ): - collection_factor = lp_details.collection_factor if lp_details.collection_factor else 1.0 points_earned = cint(eligible_amount / collection_factor) @@ -1815,7 +1827,7 @@ def validate_inter_company_party(doctype, party, company, inter_company_referenc filters={"parenttype": partytype, "parent": party}, ) companies = [d.company for d in companies] - if not company in companies: + if company not in companies: frappe.throw( _( "{0} not allowed to transact with {1}. Please change the Company or add the Company in the 'Allowed To Transact With'-Section in the Customer record." @@ -1824,7 +1836,6 @@ def validate_inter_company_party(doctype, party, company, inter_company_referenc def update_linked_doc(doctype, name, inter_company_reference): - if doctype in ["Sales Invoice", "Purchase Invoice"]: ref_field = "inter_company_invoice_reference" else: @@ -1835,7 +1846,6 @@ def update_linked_doc(doctype, name, inter_company_reference): def unlink_inter_company_doc(doctype, name, inter_company_reference): - if doctype in ["Sales Invoice", "Purchase Invoice"]: ref_doc = "Purchase Invoice" if doctype == "Sales Invoice" else "Sales Invoice" ref_field = "inter_company_invoice_reference" @@ -2010,16 +2020,13 @@ def get_internal_party(parties, link_doctype, doc): def validate_inter_company_transaction(doc, doctype): - details = get_inter_company_details(doc, doctype) price_list = ( doc.selling_price_list if doctype in ["Sales Invoice", "Sales Order", "Delivery Note"] else doc.buying_price_list ) - valid_price_list = frappe.db.get_value( - "Price List", {"name": price_list, "buying": 1, "selling": 1} - ) + valid_price_list = frappe.db.get_value("Price List", {"name": price_list, "buying": 1, "selling": 1}) if not valid_price_list and not doc.is_internal_transfer(): frappe.throw(_("Selected Price List should have buying and selling fields checked.")) @@ -2280,9 +2287,7 @@ def update_pr_items(doc, sales_item_map, purchase_item_map, parent_child_map, wa for item in doc.get("items"): item.warehouse = warehouse_map.get(sales_item_map.get(item.delivery_note_item)) if not item.warehouse and item.get("purchase_order") and item.get("purchase_order_item"): - item.warehouse = frappe.db.get_value( - "Purchase Order Item", item.purchase_order_item, "warehouse" - ) + item.warehouse = frappe.db.get_value("Purchase Order Item", item.purchase_order_item, "warehouse") def get_delivery_note_details(internal_reference): @@ -2534,9 +2539,7 @@ def check_if_return_invoice_linked_with_payment_entry(self): # If a Return invoice is linked with payment entry along with other invoices, # the cancellation of the Return causes allocated amount to be greater than paid - if not frappe.db.get_single_value( - "Accounts Settings", "unlink_payment_on_cancellation_of_invoice" - ): + if not frappe.db.get_single_value("Accounts Settings", "unlink_payment_on_cancellation_of_invoice"): return payment_entries = [] diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py index 5993c81a174..ea9f0151074 100644 --- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py +++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py @@ -2,7 +2,6 @@ # License: GNU General Public License v3. See license.txt import copy -import unittest import frappe from frappe.model.dynamic_links import get_dynamic_link_map @@ -901,7 +900,7 @@ class TestSalesInvoice(FrappeTestCase): ] ) - for i, gle in enumerate(gl_entries): + for _i, gle in enumerate(gl_entries): self.assertEqual(expected_values[gle.account][0], gle.account) self.assertEqual(expected_values[gle.account][1], gle.debit) self.assertEqual(expected_values[gle.account][2], gle.credit) @@ -927,7 +926,7 @@ class TestSalesInvoice(FrappeTestCase): write_off_account="_Test Write Off - TCP1", ) - pr = make_purchase_receipt( + make_purchase_receipt( company="_Test Company with perpetual inventory", item_code="_Test FG Item", warehouse="Stores - TCP1", @@ -1308,7 +1307,7 @@ class TestSalesInvoice(FrappeTestCase): expected_values = dict( (d[0], d) for d in [["Debtors - TCP1", 100.0, 0.0], ["Sales - TCP1", 0.0, 100.0]] ) - for i, gle in enumerate(gl_entries): + for _i, gle in enumerate(gl_entries): self.assertEqual(expected_values[gle.account][0], gle.account) self.assertEqual(expected_values[gle.account][1], gle.debit) self.assertEqual(expected_values[gle.account][2], gle.credit) @@ -1332,7 +1331,7 @@ class TestSalesInvoice(FrappeTestCase): [test_records[1]["items"][0]["income_account"], 0.0, 100.0], ] ) - for i, gle in enumerate(gl_entries): + for _i, gle in enumerate(gl_entries): self.assertEqual(expected_values[gle.account][0], gle.account) self.assertEqual(expected_values[gle.account][1], gle.debit) self.assertEqual(expected_values[gle.account][2], gle.credit) @@ -1422,9 +1421,7 @@ class TestSalesInvoice(FrappeTestCase): si.submit() self.assertFalse(frappe.db.get_value("Serial No", serial_nos[0], "warehouse")) - self.assertEqual( - frappe.db.get_value("Serial No", serial_nos[0], "delivery_document_no"), si.name - ) + self.assertEqual(frappe.db.get_value("Serial No", serial_nos[0], "delivery_document_no"), si.name) return si @@ -1752,7 +1749,7 @@ class TestSalesInvoice(FrappeTestCase): "credit", "credit_in_account_currency", ): - for i, gle in enumerate(gl_entries): + for _i, gle in enumerate(gl_entries): self.assertEqual(expected_values[gle.account][field], gle[field]) # cancel @@ -2294,12 +2291,8 @@ class TestSalesInvoice(FrappeTestCase): def test_duplicate_due_date_in_terms(self): si = create_sales_invoice(do_not_save=1) - si.append( - "payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50) - ) - si.append( - "payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50) - ) + si.append("payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50)) + si.append("payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50)) self.assertRaises(frappe.ValidationError, si.insert) @@ -2493,9 +2486,7 @@ class TestSalesInvoice(FrappeTestCase): item.no_of_months = 12 item.save() - si = create_sales_invoice( - item=item.name, posting_date="2019-01-16", rate=50000, do_not_submit=True - ) + si = create_sales_invoice(item=item.name, posting_date="2019-01-16", rate=50000, do_not_submit=True) si.items[0].enable_deferred_revenue = 1 si.items[0].service_start_date = "2019-01-16" si.items[0].service_end_date = "2019-03-31" @@ -2815,21 +2806,16 @@ class TestSalesInvoice(FrappeTestCase): item.save() sales_invoice = create_sales_invoice(item="T Shirt", rate=700, do_not_submit=True) - self.assertEqual( - sales_invoice.items[0].item_tax_template, "_Test Account Excise Duty @ 12 - _TC" - ) + self.assertEqual(sales_invoice.items[0].item_tax_template, "_Test Account Excise Duty @ 12 - _TC") # Apply discount sales_invoice.apply_discount_on = "Net Total" sales_invoice.discount_amount = 300 sales_invoice.save() - self.assertEqual( - sales_invoice.items[0].item_tax_template, "_Test Account Excise Duty @ 10 - _TC" - ) + self.assertEqual(sales_invoice.items[0].item_tax_template, "_Test Account Excise Duty @ 10 - _TC") @change_settings("Selling Settings", {"enable_discount_accounting": 1}) def test_sales_invoice_with_discount_accounting_enabled(self): - discount_account = create_account( account_name="Discount Account", parent_account="Indirect Expenses - _TC", @@ -2847,7 +2833,6 @@ class TestSalesInvoice(FrappeTestCase): @change_settings("Selling Settings", {"enable_discount_accounting": 1}) def test_additional_discount_for_sales_invoice_with_discount_accounting_enabled(self): - from erpnext.accounts.doctype.repost_accounting_ledger.test_repost_accounting_ledger import ( update_repost_settings, ) @@ -2860,7 +2845,7 @@ class TestSalesInvoice(FrappeTestCase): company="_Test Company", ) - tds_payable_account = create_account( + create_account( account_name="TDS Payable", account_type="Tax", parent_account="Duties and Taxes - _TC", @@ -3182,9 +3167,7 @@ class TestSalesInvoice(FrappeTestCase): """ from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note - over_billing_allowance = frappe.db.get_single_value( - "Accounts Settings", "over_billing_allowance" - ) + over_billing_allowance = frappe.db.get_single_value("Accounts Settings", "over_billing_allowance") frappe.db.set_value("Accounts Settings", None, "over_billing_allowance", 0) dn = create_delivery_note() @@ -3376,7 +3359,7 @@ class TestSalesInvoice(FrappeTestCase): self.assertEqual(len(journals), 1) je_type = frappe.get_cached_value("Journal Entry", journals[0], "voucher_type") self.assertEqual(je_type, "Exchange Gain Or Loss") - ledger_outstanding = frappe.db.get_all( + frappe.db.get_all( "Payment Ledger Entry", filters={"against_voucher_no": si.name, "delinked": 0}, fields=["sum(amount), sum(amount_in_account_currency)"], diff --git a/erpnext/accounts/doctype/sales_taxes_and_charges_template/sales_taxes_and_charges_template.py b/erpnext/accounts/doctype/sales_taxes_and_charges_template/sales_taxes_and_charges_template.py index d9009bae4c0..1bedf2c743e 100644 --- a/erpnext/accounts/doctype/sales_taxes_and_charges_template/sales_taxes_and_charges_template.py +++ b/erpnext/accounts/doctype/sales_taxes_and_charges_template/sales_taxes_and_charges_template.py @@ -22,7 +22,7 @@ class SalesTaxesandChargesTemplate(Document): def autoname(self): if self.company and self.title: abbr = frappe.get_cached_value("Company", self.company, "abbr") - self.name = "{0} - {1}".format(self.title, abbr) + self.name = f"{self.title} - {abbr}" def set_missing_values(self): for data in self.taxes: @@ -37,10 +37,8 @@ def valdiate_taxes_and_charges_template(doc): if doc.is_default == 1: frappe.db.sql( - """update `tab{0}` set is_default = 0 - where is_default = 1 and name != %s and company = %s""".format( - doc.doctype - ), + f"""update `tab{doc.doctype}` set is_default = 0 + where is_default = 1 and name != %s and company = %s""", (doc.name, doc.company), ) diff --git a/erpnext/accounts/doctype/share_transfer/share_transfer.py b/erpnext/accounts/doctype/share_transfer/share_transfer.py index 4f49843c1eb..21f9b1c2595 100644 --- a/erpnext/accounts/doctype/share_transfer/share_transfer.py +++ b/erpnext/accounts/doctype/share_transfer/share_transfer.py @@ -178,7 +178,9 @@ class ShareTransfer(Document): doc = self.get_shareholder_doc(shareholder) for entry in doc.share_balance: if ( - entry.share_type != self.share_type or entry.from_no > self.to_no or entry.to_no < self.from_no + entry.share_type != self.share_type + or entry.from_no > self.to_no + or entry.to_no < self.from_no ): continue # since query lies outside bounds elif entry.from_no <= self.from_no and entry.to_no >= self.to_no: # both inside @@ -230,7 +232,9 @@ class ShareTransfer(Document): for entry in current_entries: # use spaceage logic here if ( - entry.share_type != self.share_type or entry.from_no > self.to_no or entry.to_no < self.from_no + entry.share_type != self.share_type + or entry.from_no > self.to_no + or entry.to_no < self.from_no ): new_entries.append(entry) continue # since query lies outside bounds @@ -240,7 +244,9 @@ class ShareTransfer(Document): if entry.to_no == self.to_no: pass # nothing to append else: - new_entries.append(self.return_share_balance_entry(self.to_no + 1, entry.to_no, entry.rate)) + new_entries.append( + self.return_share_balance_entry(self.to_no + 1, entry.to_no, entry.rate) + ) else: if entry.to_no == self.to_no: new_entries.append( @@ -250,7 +256,9 @@ class ShareTransfer(Document): new_entries.append( self.return_share_balance_entry(entry.from_no, self.from_no - 1, entry.rate) ) - new_entries.append(self.return_share_balance_entry(self.to_no + 1, entry.to_no, entry.rate)) + new_entries.append( + self.return_share_balance_entry(self.to_no + 1, entry.to_no, entry.rate) + ) elif entry.from_no >= self.from_no and entry.to_no <= self.to_no: # split and check pass # nothing to append @@ -282,7 +290,7 @@ class ShareTransfer(Document): def get_shareholder_doc(self, shareholder): # Get Shareholder doc based on the Shareholder name if shareholder: - query_filters = {"name": shareholder} + pass name = frappe.db.get_value("Shareholder", {"name": shareholder}, "name") diff --git a/erpnext/accounts/doctype/shipping_rule/shipping_rule.py b/erpnext/accounts/doctype/shipping_rule/shipping_rule.py index 1d79503a05e..2c6d5eb5f11 100644 --- a/erpnext/accounts/doctype/shipping_rule/shipping_rule.py +++ b/erpnext/accounts/doctype/shipping_rule/shipping_rule.py @@ -44,7 +44,8 @@ class ShippingRule(Document): zero_to_values.append(d) elif d.from_value >= d.to_value: throw( - _("From value must be less than to value in row {0}").format(d.idx), FromGreaterThanToError + _("From value must be less than to value in row {0}").format(d.idx), + FromGreaterThanToError, ) # check if more than two or more rows has To Value = 0 @@ -87,9 +88,7 @@ class ShippingRule(Document): def get_shipping_amount_from_rules(self, value): for condition in self.get("conditions"): - if not condition.to_value or ( - flt(condition.from_value) <= flt(value) <= flt(condition.to_value) - ): + if not condition.to_value or (flt(condition.from_value) <= flt(value) <= flt(condition.to_value)): return condition.shipping_amount return 0.0 @@ -104,7 +103,9 @@ class ShippingRule(Document): ) if shipping_country not in [d.country for d in self.countries]: frappe.throw( - _("Shipping rule not applicable for country {0} in Shipping Address").format(shipping_country) + _("Shipping rule not applicable for country {0} in Shipping Address").format( + shipping_country + ) ) def add_shipping_rule_to_tax_table(self, doc, shipping_amount): @@ -172,11 +173,9 @@ class ShippingRule(Document): messages = [] for d1, d2 in overlaps: messages.append( - "%s-%s = %s " - % (d1.from_value, d1.to_value, fmt_money(d1.shipping_amount, currency=company_currency)) + f"{d1.from_value}-{d1.to_value} = {fmt_money(d1.shipping_amount, currency=company_currency)} " + _("and") - + " %s-%s = %s" - % (d2.from_value, d2.to_value, fmt_money(d2.shipping_amount, currency=company_currency)) + + f" {d2.from_value}-{d2.to_value} = {fmt_money(d2.shipping_amount, currency=company_currency)}" ) msgprint("\n".join(messages), raise_exception=OverlappingConditionError) diff --git a/erpnext/accounts/doctype/shipping_rule/test_shipping_rule.py b/erpnext/accounts/doctype/shipping_rule/test_shipping_rule.py index a24e834c572..a5a0ada8ba5 100644 --- a/erpnext/accounts/doctype/shipping_rule/test_shipping_rule.py +++ b/erpnext/accounts/doctype/shipping_rule/test_shipping_rule.py @@ -45,7 +45,6 @@ class TestShippingRule(unittest.TestCase): def create_shipping_rule(shipping_rule_type, shipping_rule_name): - if frappe.db.exists("Shipping Rule", shipping_rule_name): return frappe.get_doc("Shipping Rule", shipping_rule_name) diff --git a/erpnext/accounts/doctype/subscription/subscription.py b/erpnext/accounts/doctype/subscription/subscription.py index 6e5ccb9ee8d..fea2ae9bf8e 100644 --- a/erpnext/accounts/doctype/subscription/subscription.py +++ b/erpnext/accounts/doctype/subscription/subscription.py @@ -357,9 +357,7 @@ class Subscription(Document): invoice.company = company invoice.set_posting_time = 1 invoice.posting_date = ( - self.current_invoice_start - if self.generate_invoice_at_period_start - else self.current_invoice_end + self.current_invoice_start if self.generate_invoice_at_period_start else self.current_invoice_end ) invoice.cost_center = self.cost_center @@ -561,10 +559,9 @@ class Subscription(Document): 3. Change the `Subscription` status to 'Cancelled' """ - if not self.is_current_invoice_generated( - self.current_invoice_start, self.current_invoice_end - ) and (self.is_postpaid_to_invoice() or self.is_prepaid_to_invoice()): - + if not self.is_current_invoice_generated(self.current_invoice_start, self.current_invoice_end) and ( + self.is_postpaid_to_invoice() or self.is_prepaid_to_invoice() + ): prorate = frappe.db.get_single_value("Subscription Settings", "prorate") self.generate_invoice(prorate) @@ -609,10 +606,11 @@ class Subscription(Document): # Generate invoices periodically even if current invoice are unpaid if ( self.generate_new_invoices_past_due_date - and not self.is_current_invoice_generated(self.current_invoice_start, self.current_invoice_end) + and not self.is_current_invoice_generated( + self.current_invoice_start, self.current_invoice_end + ) and (self.is_postpaid_to_invoice() or self.is_prepaid_to_invoice()) ): - prorate = frappe.db.get_single_value("Subscription Settings", "prorate") self.generate_invoice(prorate) @@ -628,7 +626,7 @@ class Subscription(Document): Returns `True` if the most recent invoice for the `Subscription` is not paid """ doctype = "Sales Invoice" if self.party_type == "Customer" else "Purchase Invoice" - current_invoice = self.get_current_invoice() + self.get_current_invoice() invoice_list = [d.invoice for d in self.invoices] outstanding_invoices = frappe.get_all( diff --git a/erpnext/accounts/doctype/subscription/test_subscription.py b/erpnext/accounts/doctype/subscription/test_subscription.py index 89ba0c8055e..2f0b87e9ea2 100644 --- a/erpnext/accounts/doctype/subscription/test_subscription.py +++ b/erpnext/accounts/doctype/subscription/test_subscription.py @@ -1,7 +1,6 @@ # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt -import unittest import frappe from frappe.tests.utils import FrappeTestCase @@ -85,9 +84,7 @@ def create_parties(): customer = frappe.new_doc("Customer") customer.customer_name = "_Test Subscription Customer" customer.billing_currency = "USD" - customer.append( - "accounts", {"company": "_Test Company", "account": "_Test Receivable USD - _TC"} - ) + customer.append("accounts", {"company": "_Test Company", "account": "_Test Receivable USD - _TC"}) customer.insert() @@ -358,9 +355,7 @@ class TestSubscription(FrappeTestCase): invoice = subscription.get_current_invoice() diff = flt(date_diff(nowdate(), subscription.current_invoice_start) + 1) - plan_days = flt( - date_diff(subscription.current_invoice_end, subscription.current_invoice_start) + 1 - ) + plan_days = flt(date_diff(subscription.current_invoice_end, subscription.current_invoice_start) + 1) prorate_factor = flt(diff / plan_days) self.assertEqual( @@ -417,9 +412,7 @@ class TestSubscription(FrappeTestCase): invoice = subscription.get_current_invoice() diff = flt(date_diff(nowdate(), subscription.current_invoice_start) + 1) - plan_days = flt( - date_diff(subscription.current_invoice_end, subscription.current_invoice_start) + 1 - ) + plan_days = flt(date_diff(subscription.current_invoice_end, subscription.current_invoice_start) + 1) prorate_factor = flt(diff / plan_days) self.assertEqual(flt(invoice.grand_total, 2), flt(prorate_factor * 900, 2)) diff --git a/erpnext/accounts/doctype/subscription_plan/subscription_plan.py b/erpnext/accounts/doctype/subscription_plan/subscription_plan.py index 75223c2ccca..4c4a812dd77 100644 --- a/erpnext/accounts/doctype/subscription_plan/subscription_plan.py +++ b/erpnext/accounts/doctype/subscription_plan/subscription_plan.py @@ -21,9 +21,7 @@ class SubscriptionPlan(Document): @frappe.whitelist() -def get_plan_rate( - plan, quantity=1, customer=None, start_date=None, end_date=None, prorate_factor=1 -): +def get_plan_rate(plan, quantity=1, customer=None, start_date=None, end_date=None, prorate_factor=1): plan = frappe.get_doc("Subscription Plan", plan) if plan.price_determination == "Fixed Rate": return plan.cost * prorate_factor diff --git a/erpnext/accounts/doctype/tax_rule/tax_rule.py b/erpnext/accounts/doctype/tax_rule/tax_rule.py index 4d201292ed2..959c3b57456 100644 --- a/erpnext/accounts/doctype/tax_rule/tax_rule.py +++ b/erpnext/accounts/doctype/tax_rule/tax_rule.py @@ -82,27 +82,23 @@ class TaxRule(Document): for d in filters: if conds: conds += " and " - conds += """ifnull({0}, '') = {1}""".format(d, frappe.db.escape(cstr(filters[d]))) + conds += f"""ifnull({d}, '') = {frappe.db.escape(cstr(filters[d]))}""" if self.from_date and self.to_date: - conds += """ and ((from_date > '{from_date}' and from_date < '{to_date}') or - (to_date > '{from_date}' and to_date < '{to_date}') or - ('{from_date}' > from_date and '{from_date}' < to_date) or - ('{from_date}' = from_date and '{to_date}' = to_date))""".format( - from_date=self.from_date, to_date=self.to_date - ) + conds += f""" and ((from_date > '{self.from_date}' and from_date < '{self.to_date}') or + (to_date > '{self.from_date}' and to_date < '{self.to_date}') or + ('{self.from_date}' > from_date and '{self.from_date}' < to_date) or + ('{self.from_date}' = from_date and '{self.to_date}' = to_date))""" elif self.from_date and not self.to_date: - conds += """ and to_date > '{from_date}'""".format(from_date=self.from_date) + conds += f""" and to_date > '{self.from_date}'""" elif self.to_date and not self.from_date: - conds += """ and from_date < '{to_date}'""".format(to_date=self.to_date) + conds += f""" and from_date < '{self.to_date}'""" tax_rule = frappe.db.sql( - "select name, priority \ - from `tabTax Rule` where {0} and name != '{1}'".format( - conds, self.name - ), + f"select name, priority \ + from `tabTax Rule` where {conds} and name != '{self.name}'", as_dict=1, ) @@ -117,7 +113,6 @@ class TaxRule(Document): and cint(frappe.db.get_single_value("E Commerce Settings", "enabled")) and not frappe.db.get_value("Tax Rule", {"use_for_shopping_cart": 1, "name": ["!=", self.name]}) ): - self.use_for_shopping_cart = 1 frappe.msgprint( _( @@ -174,27 +169,25 @@ def get_tax_template(posting_date, args): conditions.append("(from_date is null) and (to_date is null)") conditions.append( - "ifnull(tax_category, '') = {0}".format(frappe.db.escape(cstr(args.get("tax_category")))) + "ifnull(tax_category, '') = {}".format(frappe.db.escape(cstr(args.get("tax_category")))) ) if "tax_category" in args.keys(): del args["tax_category"] for key, value in args.items(): if key == "use_for_shopping_cart": - conditions.append("use_for_shopping_cart = {0}".format(1 if value else 0)) + conditions.append(f"use_for_shopping_cart = {1 if value else 0}") elif key == "customer_group": if not value: value = get_root_of("Customer Group") customer_group_condition = get_customer_group_condition(value) - conditions.append("ifnull({0}, '') in ('', {1})".format(key, customer_group_condition)) + conditions.append(f"ifnull({key}, '') in ('', {customer_group_condition})") else: - conditions.append("ifnull({0}, '') in ('', {1})".format(key, frappe.db.escape(cstr(value)))) + conditions.append(f"ifnull({key}, '') in ('', {frappe.db.escape(cstr(value))})") tax_rule = frappe.db.sql( """select * from `tabTax Rule` - where {0}""".format( - " and ".join(conditions) - ), + where {}""".format(" and ".join(conditions)), as_dict=True, ) @@ -219,7 +212,7 @@ def get_tax_template(posting_date, args): )[0] tax_template = rule.sales_tax_template or rule.purchase_tax_template - doctype = "{0} Taxes and Charges Template".format(rule.tax_type) + doctype = f"{rule.tax_type} Taxes and Charges Template" if frappe.db.get_value(doctype, tax_template, "disabled") == 1: return None @@ -229,9 +222,7 @@ def get_tax_template(posting_date, args): def get_customer_group_condition(customer_group): condition = "" - customer_groups = [ - "%s" % (frappe.db.escape(d.name)) for d in get_parent_customer_groups(customer_group) - ] + customer_groups = ["%s" % (frappe.db.escape(d.name)) for d in get_parent_customer_groups(customer_group)] if customer_groups: condition = ",".join(["%s"] * len(customer_groups)) % (tuple(customer_groups)) return condition diff --git a/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py b/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py index 1d1955e3d51..58ce2840b4b 100644 --- a/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py +++ b/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py @@ -36,13 +36,11 @@ class TaxWithholdingCategory(Document): def validate_thresholds(self): for d in self.get("rates"): - if ( - d.cumulative_threshold and d.single_threshold and d.cumulative_threshold < d.single_threshold - ): + if d.cumulative_threshold and d.single_threshold and d.cumulative_threshold < d.single_threshold: frappe.throw( - _("Row #{0}: Cumulative threshold cannot be less than Single Transaction threshold").format( - d.idx - ) + _( + "Row #{0}: Cumulative threshold cannot be less than Single Transaction threshold" + ).format(d.idx) ) @@ -295,9 +293,7 @@ def get_tax_amount(party_type, parties, inv, tax_details, posting_date, pan_no=N def get_invoice_vouchers(parties, tax_details, company, party_type="Supplier"): doctype = "Purchase Invoice" if party_type == "Supplier" else "Sales Invoice" field = ( - "base_tax_withholding_net_total as base_net_total" - if party_type == "Supplier" - else "base_net_total" + "base_tax_withholding_net_total as base_net_total" if party_type == "Supplier" else "base_net_total" ) voucher_wise_amount = {} vouchers = [] @@ -351,9 +347,7 @@ def get_invoice_vouchers(parties, tax_details, company, party_type="Supplier"): return vouchers, voucher_wise_amount -def get_advance_vouchers( - parties, company=None, from_date=None, to_date=None, party_type="Supplier" -): +def get_advance_vouchers(parties, company=None, from_date=None, to_date=None, party_type="Supplier"): """ Use Payment Ledger to fetch unallocated Advance Payments """ @@ -374,9 +368,7 @@ def get_advance_vouchers( if from_date and to_date: conditions.append(ple.posting_date[from_date:to_date]) - advances = ( - qb.from_(ple).select(ple.voucher_no).distinct().where(Criterion.all(conditions)).run(as_list=1) - ) + advances = qb.from_(ple).select(ple.voucher_no).distinct().where(Criterion.all(conditions)).run(as_list=1) if advances: advances = [x[0] for x in advances] @@ -542,9 +534,7 @@ def get_tcs_amount(parties, inv, tax_details, vouchers, adv_vouchers): conditions.append(ple.voucher_no == ple.against_voucher_no) conditions.append(ple.company == inv.company) - advances = ( - qb.from_(ple).select(Abs(Sum(ple.amount))).where(Criterion.all(conditions)).run(as_list=1) - ) + (qb.from_(ple).select(Abs(Sum(ple.amount))).where(Criterion.all(conditions)).run(as_list=1)) advance_amt = ( qb.from_(ple).select(Abs(Sum(ple.amount))).where(Criterion.all(conditions)).run()[0][0] or 0.0 @@ -603,9 +593,7 @@ def get_limit_consumed(ldc, parties): return limit_consumed -def get_lower_deduction_amount( - current_amount, limit_consumed, certificate_limit, rate, tax_details -): +def get_lower_deduction_amount(current_amount, limit_consumed, certificate_limit, rate, tax_details): if certificate_limit - flt(limit_consumed) - flt(current_amount) >= 0: return current_amount * rate / 100 else: @@ -617,9 +605,7 @@ def get_lower_deduction_amount( def is_valid_certificate(ldc, posting_date, limit_consumed): available_amount = flt(ldc.certificate_limit) - flt(limit_consumed) - if ( - getdate(ldc.valid_from) <= getdate(posting_date) <= getdate(ldc.valid_upto) - ) and available_amount > 0: + if (getdate(ldc.valid_from) <= getdate(posting_date) <= getdate(ldc.valid_upto)) and available_amount > 0: return True return False diff --git a/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py b/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py index 0a749f96652..a5509619583 100644 --- a/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py +++ b/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py @@ -96,9 +96,7 @@ class TestTaxWithholdingCategory(unittest.TestCase): def test_tax_withholding_category_checks(self): invoices = [] - frappe.db.set_value( - "Supplier", "Test TDS Supplier3", "tax_withholding_category", "New TDS Category" - ) + frappe.db.set_value("Supplier", "Test TDS Supplier3", "tax_withholding_category", "New TDS Category") # First Invoice with no tds check pi = create_purchase_invoice(supplier="Test TDS Supplier3", rate=20000, do_not_save=True) @@ -453,7 +451,7 @@ class TestTaxWithholdingCategory(unittest.TestCase): pe3.save() pe3.submit() - self.assertEquals(pe3.get("taxes")[0].tax_amount, 1200) + self.assertEqual(pe3.get("taxes")[0].tax_amount, 1200) pe1.cancel() pe2.cancel() pe3.cancel() @@ -850,9 +848,7 @@ def create_tax_withholding_category( ).insert() -def create_lower_deduction_certificate( - supplier, tax_withholding_category, tax_rate, certificate_no, limit -): +def create_lower_deduction_certificate(supplier, tax_withholding_category, tax_rate, certificate_no, limit): fiscal_year = get_fiscal_year(today(), company="_Test Company") if not frappe.db.exists("Lower Deduction Certificate", certificate_no): frappe.get_doc( diff --git a/erpnext/accounts/doctype/unreconcile_payment/test_unreconcile_payment.py b/erpnext/accounts/doctype/unreconcile_payment/test_unreconcile_payment.py index 57f66dd21db..882dd1d6dab 100644 --- a/erpnext/accounts/doctype/unreconcile_payment/test_unreconcile_payment.py +++ b/erpnext/accounts/doctype/unreconcile_payment/test_unreconcile_payment.py @@ -93,7 +93,7 @@ class TestUnreconcilePayment(AccountsTestMixin, FrappeTestCase): unreconcile.add_references() self.assertEqual(len(unreconcile.allocations), 2) allocations = [x.reference_name for x in unreconcile.allocations] - self.assertEquals([si1.name, si2.name], allocations) + self.assertEqual([si1.name, si2.name], allocations) # unreconcile si1 for x in unreconcile.allocations: if x.reference_name != si1.name: @@ -158,7 +158,7 @@ class TestUnreconcilePayment(AccountsTestMixin, FrappeTestCase): unreconcile.add_references() self.assertEqual(len(unreconcile.allocations), 2) allocations = [x.reference_name for x in unreconcile.allocations] - self.assertEquals([si1.name, si2.name], allocations) + self.assertEqual([si1.name, si2.name], allocations) # unreconcile si1 from pe2 for x in unreconcile.allocations: if x.reference_name != si1.name: @@ -216,7 +216,7 @@ class TestUnreconcilePayment(AccountsTestMixin, FrappeTestCase): unreconcile.add_references() self.assertEqual(len(unreconcile.allocations), 2) allocations = [x.reference_name for x in unreconcile.allocations] - self.assertEquals([si1.name, si2.name], allocations) + self.assertEqual([si1.name, si2.name], allocations) # unreconcile si1 from pe for x in unreconcile.allocations: if x.reference_name != si1.name: @@ -301,7 +301,7 @@ class TestUnreconcilePayment(AccountsTestMixin, FrappeTestCase): unreconcile.add_references() self.assertEqual(len(unreconcile.allocations), 2) allocations = [x.reference_name for x in unreconcile.allocations] - self.assertEquals([si1.name, si2.name], allocations) + self.assertEqual([si1.name, si2.name], allocations) # unreconcile si1 from pe2 for x in unreconcile.allocations: if x.reference_name != si1.name: @@ -353,7 +353,7 @@ class TestUnreconcilePayment(AccountsTestMixin, FrappeTestCase): unreconcile.add_references() self.assertEqual(len(unreconcile.allocations), 1) allocations = [x.reference_name for x in unreconcile.allocations] - self.assertEquals([so.name], allocations) + self.assertEqual([so.name], allocations) # unreconcile so unreconcile.save().submit() diff --git a/erpnext/accounts/doctype/unreconcile_payment/unreconcile_payment.py b/erpnext/accounts/doctype/unreconcile_payment/unreconcile_payment.py index dd714573b1b..091bccf5099 100644 --- a/erpnext/accounts/doctype/unreconcile_payment/unreconcile_payment.py +++ b/erpnext/accounts/doctype/unreconcile_payment/unreconcile_payment.py @@ -18,7 +18,7 @@ from erpnext.accounts.utils import ( class UnreconcilePayment(Document): def validate(self): self.supported_types = ["Payment Entry", "Journal Entry"] - if not self.voucher_type in self.supported_types: + if self.voucher_type not in self.supported_types: frappe.throw(_("Only {0} are supported").format(comma_and(self.supported_types))) @frappe.whitelist() @@ -70,7 +70,7 @@ class UnreconcilePayment(Document): @frappe.whitelist() -def doc_has_references(doctype: str = None, docname: str = None): +def doc_has_references(doctype: str | None = None, docname: str | None = None): if doctype in ["Sales Invoice", "Purchase Invoice"]: return frappe.db.count( "Payment Ledger Entry", @@ -85,7 +85,7 @@ def doc_has_references(doctype: str = None, docname: str = None): @frappe.whitelist() def get_linked_payments_for_doc( - company: str = None, doctype: str = None, docname: str = None + company: str | None = None, doctype: str | None = None, docname: str | None = None ) -> list: if company and doctype and docname: _dt = doctype diff --git a/erpnext/accounts/general_ledger.py b/erpnext/accounts/general_ledger.py index 432abc250b1..58601f3b08d 100644 --- a/erpnext/accounts/general_ledger.py +++ b/erpnext/accounts/general_ledger.py @@ -78,7 +78,7 @@ def make_acc_dimensions_offsetting_entry(gl_map): "credit": credit, "debit_in_account_currency": debit, "credit_in_account_currency": credit, - "remarks": _("Offsetting for Accounting Dimension") + " - {0}".format(dimension.name), + "remarks": _("Offsetting for Accounting Dimension") + f" - {dimension.name}", "against_voucher": None, } ) @@ -179,9 +179,7 @@ def process_gl_map(gl_map, merge_entries=True, precision=None): def distribute_gl_based_on_cost_center_allocation(gl_map, precision=None): - cost_center_allocation = get_cost_center_allocation_data( - gl_map[0]["company"], gl_map[0]["posting_date"] - ) + cost_center_allocation = get_cost_center_allocation_data(gl_map[0]["company"], gl_map[0]["posting_date"]) if not cost_center_allocation: return gl_map @@ -190,9 +188,7 @@ def distribute_gl_based_on_cost_center_allocation(gl_map, precision=None): cost_center = d.get("cost_center") # Validate budget against main cost center - validate_expense_against_budget( - d, expense_amount=flt(d.debit, precision) - flt(d.credit, precision) - ) + validate_expense_against_budget(d, expense_amount=flt(d.debit, precision) - flt(d.credit, precision)) if cost_center and cost_center_allocation.get(cost_center): for sub_cost_center, percentage in cost_center_allocation.get(cost_center, {}).items(): @@ -224,9 +220,7 @@ def get_cost_center_allocation_data(company, posting_date): cc_allocation = frappe._dict() for d in records: - cc_allocation.setdefault(d.main_cost_center, frappe._dict()).setdefault( - d.cost_center, d.percentage - ) + cc_allocation.setdefault(d.main_cost_center, frappe._dict()).setdefault(d.cost_center, d.percentage) return cc_allocation @@ -540,9 +534,7 @@ def update_accounting_dimensions(round_off_gle): round_off_gle[dimension] = dimension_values.get(dimension) -def get_round_off_account_and_cost_center( - company, voucher_type, voucher_no, use_company_default=False -): +def get_round_off_account_and_cost_center(company, voucher_type, voucher_no, use_company_default=False): round_off_account, round_off_cost_center = frappe.get_cached_value( "Company", company, ["round_off_account", "round_off_cost_center"] ) or [None, None] @@ -650,9 +642,7 @@ def check_freezing_date(posting_date, adv_adj=False): def validate_against_pcv(is_opening, posting_date, company): - if is_opening and frappe.db.exists( - "Period Closing Voucher", {"docstatus": 1, "company": company} - ): + if is_opening and frappe.db.exists("Period Closing Voucher", {"docstatus": 1, "company": company}): frappe.throw( _("Opening Entry can not be created after Period Closing Voucher is created."), title=_("Invalid Opening Entry"), @@ -663,9 +653,7 @@ def validate_against_pcv(is_opening, posting_date, company): ) if last_pcv_date and getdate(posting_date) <= getdate(last_pcv_date): - message = _("Books have been closed till the period ending on {0}").format( - formatdate(last_pcv_date) - ) + message = _("Books have been closed till the period ending on {0}").format(formatdate(last_pcv_date)) message += "
" message += _("You cannot create/amend any accounting entries till this date.") frappe.throw(message, title=_("Period Closed")) diff --git a/erpnext/accounts/party.py b/erpnext/accounts/party.py index 8f8b9a81f8a..2b95e16f356 100644 --- a/erpnext/accounts/party.py +++ b/erpnext/accounts/party.py @@ -2,8 +2,6 @@ # License: GNU General Public License v3. See license.txt -from typing import Optional - import frappe from frappe import _, msgprint, qb, scrub from frappe.contacts.doctype.address.address import get_company_address, get_default_address @@ -69,7 +67,6 @@ def get_party_details( shipping_address=None, pos_profile=None, ): - if not party: return {} if not frappe.db.exists(party_type, party): @@ -153,9 +150,7 @@ def _get_party_details( party_details["taxes_and_charges"] = tax_template if cint(fetch_payment_terms_template): - party_details["payment_terms_template"] = get_payment_terms_template( - party.name, party_type, company - ) + party_details["payment_terms_template"] = get_payment_terms_template(party.name, party_type, company) if not party_details.get("currency"): party_details["currency"] = currency @@ -173,9 +168,7 @@ def _get_party_details( # supplier tax withholding category if party_type == "Supplier" and party: - party_details["supplier_tds"] = frappe.get_value( - party_type, party.name, "tax_withholding_category" - ) + party_details["supplier_tds"] = frappe.get_value(party_type, party.name, "tax_withholding_category") if not party_details.get("tax_category") and pos_profile: party_details["tax_category"] = frappe.get_value("POS Profile", pos_profile, "tax_category") @@ -195,12 +188,8 @@ def set_address_details( *, ignore_permissions=False, ): - billing_address_field = ( - "customer_address" if party_type == "Lead" else party_type.lower() + "_address" - ) - party_details[billing_address_field] = party_address or get_default_address( - party_type, party.name - ) + billing_address_field = "customer_address" if party_type == "Lead" else party_type.lower() + "_address" + party_details[billing_address_field] = party_address or get_default_address(party_type, party.name) if doctype: party_details.update( get_fetch_values(doctype, billing_address_field, party_details[billing_address_field]) @@ -310,9 +299,7 @@ def set_contact_details(party_details, party, party_type): "department as contact_department", ] - contact_details = frappe.db.get_value( - "Contact", party_details.contact_person, fields, as_dict=True - ) + contact_details = frappe.db.get_value("Contact", party_details.contact_person, fields, as_dict=True) contact_details.contact_display = " ".join( filter( @@ -338,9 +325,7 @@ def set_other_values(party_details, party, party_type): party_details[f] = party.get(f) # fields prepended with default in Customer doctype - for f in ["currency"] + ( - ["sales_partner", "commission_rate"] if party_type == "Customer" else [] - ): + for f in ["currency"] + (["sales_partner", "commission_rate"] if party_type == "Customer" else []): if party.get("default_" + f): party_details[f] = party.get("default_" + f) @@ -377,14 +362,10 @@ def set_price_list(party_details, party, party_type, given_price_list, pos=None) "Price List", price_list, "currency", cache=True ) - party_details[ - "selling_price_list" if party.doctype == "Customer" else "buying_price_list" - ] = price_list + party_details["selling_price_list" if party.doctype == "Customer" else "buying_price_list"] = price_list -def set_account_and_due_date( - party, account, party_type, company, posting_date, bill_date, doctype -): +def set_account_and_due_date(party, account, party_type, company, posting_date, bill_date, doctype): if doctype not in ["POS Invoice", "Sales Invoice", "Purchase Invoice"]: # not an invoice return {party_type.lower(): party} @@ -449,9 +430,7 @@ def get_party_account(party_type, party=None, company=None): @frappe.whitelist() def get_party_bank_account(party_type, party): - return frappe.db.get_value( - "Bank Account", {"party_type": party_type, "party": party, "is_default": 1} - ) + return frappe.db.get_value("Bank Account", {"party_type": party_type, "party": party, "is_default": 1}) def get_party_account_currency(party_type, party, company): @@ -573,9 +552,7 @@ def get_due_date(posting_date, party_type, party, company=None, bill_date=None): template_name = get_payment_terms_template(party, party_type, company) if template_name: - due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime( - "%Y-%m-%d" - ) + due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime("%Y-%m-%d") else: if party_type == "Supplier": supplier_group = frappe.get_cached_value(party_type, party, "supplier_group") @@ -735,7 +712,6 @@ def get_payment_terms_template(party_name, party_type, company=None): def validate_party_frozen_disabled(party_type, party_name): - if frappe.flags.ignore_party_validation: return @@ -748,7 +724,7 @@ def validate_party_frozen_disabled(party_type, party_name): frozen_accounts_modifier = frappe.db.get_single_value( "Accounts Settings", "frozen_accounts_modifier" ) - if not frozen_accounts_modifier in frappe.get_roles(): + if frozen_accounts_modifier not in frappe.get_roles(): frappe.throw(_("{0} {1} is frozen").format(party_type, party_name), PartyFrozen) elif party_type == "Employee": @@ -871,9 +847,7 @@ def get_dashboard_info(party_type, party, loyalty_program=None): party_account_currency = get_party_account_currency(party_type, party, d.company) if party_account_currency == company_default_currency: - billing_this_year = flt( - company_wise_billing_this_year.get(d.company, {}).get("base_grand_total") - ) + billing_this_year = flt(company_wise_billing_this_year.get(d.company, {}).get("base_grand_total")) else: billing_this_year = flt(company_wise_billing_this_year.get(d.company, {}).get("grand_total")) @@ -899,7 +873,7 @@ def get_dashboard_info(party_type, party, loyalty_program=None): return company_wise_info -def get_party_shipping_address(doctype: str, name: str) -> Optional[str]: +def get_party_shipping_address(doctype: str, name: str) -> str | None: """ Returns an Address name (best guess) for the given doctype and name for which `address_type == 'Shipping'` is true. and/or `is_shipping_address = 1`. @@ -965,7 +939,7 @@ def get_partywise_advanced_payment_amount( return frappe._dict(data) -def get_default_contact(doctype: str, name: str) -> Optional[str]: +def get_default_contact(doctype: str, name: str) -> str | None: """ Returns contact name only if there is a primary contact for given doctype and name. diff --git a/erpnext/accounts/report/account_balance/account_balance.py b/erpnext/accounts/report/account_balance/account_balance.py index 824a965cdcf..6f9f7ebcb8d 100644 --- a/erpnext/accounts/report/account_balance/account_balance.py +++ b/erpnext/accounts/report/account_balance/account_balance.py @@ -61,7 +61,6 @@ def get_conditions(filters): def get_data(filters): - data = [] conditions = get_conditions(filters) accounts = frappe.db.get_all( diff --git a/erpnext/accounts/report/accounts_payable/test_accounts_payable.py b/erpnext/accounts/report/accounts_payable/test_accounts_payable.py index b4cb25ff1b8..f5c9d16073e 100644 --- a/erpnext/accounts/report/accounts_payable/test_accounts_payable.py +++ b/erpnext/accounts/report/accounts_payable/test_accounts_payable.py @@ -1,16 +1,10 @@ -import unittest - import frappe -from frappe.tests.utils import FrappeTestCase, change_settings -from frappe.utils import add_days, flt, getdate, today +from frappe.tests.utils import FrappeTestCase +from frappe.utils import today -from erpnext import get_default_cost_center -from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import make_purchase_invoice -from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice from erpnext.accounts.report.accounts_payable.accounts_payable import execute from erpnext.accounts.test.accounts_mixin import AccountsTestMixin -from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase): diff --git a/erpnext/accounts/report/accounts_receivable/accounts_receivable.py b/erpnext/accounts/report/accounts_receivable/accounts_receivable.py index 609a4abe66f..dcfd85afddb 100644 --- a/erpnext/accounts/report/accounts_receivable/accounts_receivable.py +++ b/erpnext/accounts/report/accounts_receivable/accounts_receivable.py @@ -40,24 +40,20 @@ def execute(filters=None): return ReceivablePayableReport(filters).run(args) -class ReceivablePayableReport(object): +class ReceivablePayableReport: def __init__(self, filters=None): self.filters = frappe._dict(filters or {}) self.qb_selection_filter = [] self.ple = qb.DocType("Payment Ledger Entry") self.filters.report_date = getdate(self.filters.report_date or nowdate()) self.age_as_on = ( - getdate(nowdate()) - if self.filters.report_date > getdate(nowdate()) - else self.filters.report_date + getdate(nowdate()) if self.filters.report_date > getdate(nowdate()) else self.filters.report_date ) def run(self, args): self.filters.update(args) self.set_defaults() - self.party_naming_by = frappe.db.get_value( - args.get("naming_by")[0], None, args.get("naming_by")[1] - ) + self.party_naming_by = frappe.db.get_value(args.get("naming_by")[0], None, args.get("naming_by")[1]) self.get_columns() self.get_data() self.get_chart_data() @@ -72,9 +68,7 @@ class ReceivablePayableReport(object): self.currency_precision = get_currency_precision() or 2 self.dr_or_cr = "debit" if self.filters.account_type == "Receivable" else "credit" self.account_type = self.filters.account_type - self.party_type = frappe.db.get_all( - "Party Type", {"account_type": self.account_type}, pluck="name" - ) + self.party_type = frappe.db.get_all("Party Type", {"account_type": self.account_type}, pluck="name") self.party_details = {} self.invoices = set() self.skip_total_row = 0 @@ -128,7 +122,7 @@ class ReceivablePayableReport(object): else: key = (ple.account, ple.voucher_type, ple.voucher_no, ple.party) - if not key in self.voucher_balance: + if key not in self.voucher_balance: self.voucher_balance[key] = frappe._dict( voucher_type=ple.voucher_type, voucher_no=ple.voucher_no, @@ -281,7 +275,7 @@ class ReceivablePayableReport(object): def build_data(self): # set outstanding for all the accumulated balances # as we can use this to filter out invoices without outstanding - for key, row in self.voucher_balance.items(): + for _key, row in self.voucher_balance.items(): row.outstanding = flt(row.invoiced - row.paid - row.credit_note, self.currency_precision) row.outstanding_in_account_currency = flt( row.invoiced_in_account_currency @@ -295,7 +289,7 @@ class ReceivablePayableReport(object): must_consider = False if self.filters.get("for_revaluation_journals"): if (abs(row.outstanding) > 0.0 / 10**self.currency_precision) or ( - (abs(row.outstanding_in_account_currency) > 0.0 / 10**self.currency_precision) + abs(row.outstanding_in_account_currency) > 0.0 / 10**self.currency_precision ): must_consider = True else: @@ -481,19 +475,17 @@ class ReceivablePayableReport(object): def get_payment_terms(self, row): # build payment_terms for row payment_terms_details = frappe.db.sql( - """ + f""" select si.name, si.party_account_currency, si.currency, si.conversion_rate, si.total_advance, ps.due_date, ps.payment_term, ps.payment_amount, ps.base_payment_amount, ps.description, ps.paid_amount, ps.discounted_amount - from `tab{0}` si, `tabPayment Schedule` ps + from `tab{row.voucher_type}` si, `tabPayment Schedule` ps where si.name = ps.parent and si.name = %s order by ps.paid_amount desc, due_date - """.format( - row.voucher_type - ), + """, row.voucher_no, as_dict=1, ) @@ -737,9 +729,7 @@ class ReceivablePayableReport(object): row.age = (getdate(self.age_as_on) - getdate(entry_date)).days or 0 index = None - if not ( - self.filters.range1 and self.filters.range2 and self.filters.range3 and self.filters.range4 - ): + if not (self.filters.range1 and self.filters.range2 and self.filters.range3 and self.filters.range4): self.filters.range1, self.filters.range2, self.filters.range3, self.filters.range4 = ( 30, 60, @@ -765,12 +755,10 @@ class ReceivablePayableReport(object): if self.filters.show_future_payments: self.qb_selection_filter.append( - ( - self.ple.posting_date.lte(self.filters.report_date) - | ( - (self.ple.voucher_no == self.ple.against_voucher_no) - & (Date(self.ple.creation).lte(self.filters.report_date)) - ) + self.ple.posting_date.lte(self.filters.report_date) + | ( + (self.ple.voucher_no == self.ple.against_voucher_no) + & (Date(self.ple.creation).lte(self.filters.report_date)) ) ) else: @@ -838,7 +826,7 @@ class ReceivablePayableReport(object): self.qb_selection_filter = [] self.or_filters = [] - for party_type in self.party_type: + for _party_type in self.party_type: self.add_common_filters() if self.account_type == "Receivable": @@ -975,7 +963,7 @@ class ReceivablePayableReport(object): return True def get_party_details(self, party): - if not party in self.party_details: + if party not in self.party_details: if self.account_type == "Receivable": fields = ["customer_name", "territory", "customer_group", "customer_primary_contact"] diff --git a/erpnext/accounts/report/accounts_receivable/test_accounts_receivable.py b/erpnext/accounts/report/accounts_receivable/test_accounts_receivable.py index 01129824bca..a65e424173c 100644 --- a/erpnext/accounts/report/accounts_receivable/test_accounts_receivable.py +++ b/erpnext/accounts/report/accounts_receivable/test_accounts_receivable.py @@ -1,11 +1,8 @@ -import unittest - import frappe from frappe import qb from frappe.tests.utils import FrappeTestCase, change_settings from frappe.utils import add_days, flt, getdate, today -from erpnext import get_default_cost_center from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice from erpnext.accounts.report.accounts_receivable.accounts_receivable import execute @@ -126,7 +123,6 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase): # check invoice grand total and invoiced column's value for 3 payment terms si = self.create_sales_invoice() - name = si.name report = execute(filters) @@ -218,7 +214,7 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase): [0, 0, 100.0, 0.0, -100.0, cr_note.name], ] self.assertEqual(len(report[1]), 2) - si_row = [ + si_row = next( [ row.invoice_grand_total, row.invoiced, @@ -229,9 +225,9 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase): ] for row in report[1] if row.voucher_no == si.name - ][0] + ) - cr_note_row = [ + cr_note_row = next( [ row.invoice_grand_total, row.invoiced, @@ -242,7 +238,7 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase): ] for row in report[1] if row.voucher_no == cr_note.name - ][0] + ) self.assertEqual(expected_data_after_credit_note[0], si_row) self.assertEqual(expected_data_after_credit_note[1], cr_note_row) @@ -317,9 +313,7 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase): err.extend("accounts", accounts) err.accounts[0].new_exchange_rate = 85 row = err.accounts[0] - row.new_balance_in_base_currency = flt( - row.new_exchange_rate * flt(row.balance_in_account_currency) - ) + row.new_balance_in_base_currency = flt(row.new_exchange_rate * flt(row.balance_in_account_currency)) row.gain_loss = row.new_balance_in_base_currency - flt(row.balance_in_base_currency) err.set_total_gain_loss() err = err.save().submit() @@ -340,7 +334,7 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase): report = execute(filters) expected_data_for_err = [0, -500, 0, 500] - row = [x for x in report[1] if x.voucher_type == je.doctype and x.voucher_no == je.name][0] + row = next(x for x in report[1] if x.voucher_type == je.doctype and x.voucher_no == je.name) self.assertEqual( expected_data_for_err, [ @@ -575,7 +569,7 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase): self.assertEqual(expected_data, [row.invoiced, row.outstanding, row.sales_person]) def test_cost_center_filter(self): - si = self.create_sales_invoice() + self.create_sales_invoice() filters = { "company": self.company, "report_date": today(), @@ -592,7 +586,7 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase): self.assertEqual(expected_data, [row.invoiced, row.outstanding, row.cost_center]) def test_customer_group_filter(self): - si = self.create_sales_invoice() + self.create_sales_invoice() cus_group = frappe.db.get_value("Customer", self.customer, "customer_group") filters = { "company": self.company, @@ -614,7 +608,7 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase): self.assertEqual(len(report), 0) def test_multi_customer_group_filter(self): - si = self.create_sales_invoice() + self.create_sales_invoice() cus_group = frappe.db.get_value("Customer", self.customer, "customer_group") # Create a list of customer groups, e.g., ["Group1", "Group2"] cus_groups_list = [cus_group, "_Test Customer Group 1"] @@ -727,7 +721,6 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase): si.conversion_rate = 80 si.debit_to = self.debtors_usd si.save().submit() - name = si.name # check invoice grand total and invoiced column's value for 3 payment terms report = execute(filters) @@ -787,9 +780,7 @@ class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase): def test_report_output_if_party_is_missing(self): acc_name = "Additional Debtors" - if not frappe.db.get_value( - "Account", filters={"account_name": acc_name, "company": self.company} - ): + if not frappe.db.get_value("Account", filters={"account_name": acc_name, "company": self.company}): additional_receivable_acc = frappe.get_doc( { "doctype": "Account", diff --git a/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py b/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py index a92f960fdf0..b1c02b38452 100644 --- a/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py +++ b/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py @@ -23,12 +23,8 @@ def execute(filters=None): class AccountsReceivableSummary(ReceivablePayableReport): def run(self, args): self.account_type = args.get("account_type") - self.party_type = frappe.db.get_all( - "Party Type", {"account_type": self.account_type}, pluck="name" - ) - self.party_naming_by = frappe.db.get_value( - args.get("naming_by")[0], None, args.get("naming_by")[1] - ) + self.party_type = frappe.db.get_all("Party Type", {"account_type": self.account_type}, pluck="name") + self.party_naming_by = frappe.db.get_value(args.get("naming_by")[0], None, args.get("naming_by")[1]) self.get_columns() self.get_data(args) return self.columns, self.data diff --git a/erpnext/accounts/report/accounts_receivable_summary/test_accounts_receivable_summary.py b/erpnext/accounts/report/accounts_receivable_summary/test_accounts_receivable_summary.py index 3ee35a114d1..4ef607bab28 100644 --- a/erpnext/accounts/report/accounts_receivable_summary/test_accounts_receivable_summary.py +++ b/erpnext/accounts/report/accounts_receivable_summary/test_accounts_receivable_summary.py @@ -1,5 +1,3 @@ -import unittest - import frappe from frappe.tests.utils import FrappeTestCase, change_settings from frappe.utils import today diff --git a/erpnext/accounts/report/asset_depreciations_and_balances/asset_depreciations_and_balances.py b/erpnext/accounts/report/asset_depreciations_and_balances/asset_depreciations_and_balances.py index bdc8d8504f8..1754780e346 100644 --- a/erpnext/accounts/report/asset_depreciations_and_balances/asset_depreciations_and_balances.py +++ b/erpnext/accounts/report/asset_depreciations_and_balances/asset_depreciations_and_balances.py @@ -62,7 +62,7 @@ def get_asset_categories(filters): if filters.get("asset_category"): condition += " and asset_category = %(asset_category)s" return frappe.db.sql( - """ + f""" SELECT asset_category, ifnull(sum(case when purchase_date < %(from_date)s then case when ifnull(disposal_date, 0) = 0 or disposal_date >= %(from_date)s then @@ -101,11 +101,9 @@ def get_asset_categories(filters): 0 end), 0) as cost_of_scrapped_asset from `tabAsset` - where docstatus=1 and company=%(company)s and purchase_date <= %(to_date)s {} + where docstatus=1 and company=%(company)s and purchase_date <= %(to_date)s {condition} group by asset_category - """.format( - condition - ), + """, { "to_date": filters.to_date, "from_date": filters.from_date, @@ -170,9 +168,7 @@ def get_assets(filters): where a.docstatus=1 and a.company=%(company)s and a.purchase_date <= %(to_date)s {0} group by a.asset_category) as results group by results.asset_category - """.format( - condition - ), + """.format(condition), {"to_date": filters.to_date, "from_date": filters.from_date, "company": filters.company}, as_dict=1, ) diff --git a/erpnext/accounts/report/balance_sheet/balance_sheet.py b/erpnext/accounts/report/balance_sheet/balance_sheet.py index 5d6ca23a6b2..2106451bd1a 100644 --- a/erpnext/accounts/report/balance_sheet/balance_sheet.py +++ b/erpnext/accounts/report/balance_sheet/balance_sheet.py @@ -180,7 +180,6 @@ def get_report_summary( filters, consolidated=False, ): - net_asset, net_liability, net_equity, net_provisional_profit_loss = 0.0, 0.0, 0.0, 0.0 if filters.get("accumulated_values"): diff --git a/erpnext/accounts/report/balance_sheet/test_balance_sheet.py b/erpnext/accounts/report/balance_sheet/test_balance_sheet.py index 3cb6efebee3..ca357ece1d1 100644 --- a/erpnext/accounts/report/balance_sheet/test_balance_sheet.py +++ b/erpnext/accounts/report/balance_sheet/test_balance_sheet.py @@ -13,15 +13,13 @@ class TestBalanceSheet(FrappeTestCase): from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import make_purchase_invoice from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import ( create_sales_invoice, - make_sales_invoice, ) - from erpnext.accounts.utils import get_fiscal_year frappe.db.sql("delete from `tabPurchase Invoice` where company='_Test Company 6'") frappe.db.sql("delete from `tabSales Invoice` where company='_Test Company 6'") frappe.db.sql("delete from `tabGL Entry` where company='_Test Company 6'") - pi = make_purchase_invoice( + make_purchase_invoice( company="_Test Company 6", warehouse="Finished Goods - _TC6", expense_account="Cost of Goods Sold - _TC6", @@ -29,7 +27,7 @@ class TestBalanceSheet(FrappeTestCase): qty=10, rate=100, ) - si = create_sales_invoice( + create_sales_invoice( company="_Test Company 6", debit_to="Debtors - _TC6", income_account="Sales - _TC6", diff --git a/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py b/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py index cb7445546f1..ab8bdd7afbd 100644 --- a/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py +++ b/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py @@ -63,31 +63,27 @@ def get_conditions(filters): def get_entries(filters): conditions = get_conditions(filters) journal_entries = frappe.db.sql( - """SELECT + f"""SELECT "Journal Entry", jv.name, jv.posting_date, jv.cheque_no, jv.clearance_date, jvd.against_account, jvd.debit - jvd.credit FROM `tabJournal Entry Account` jvd, `tabJournal Entry` jv WHERE - jvd.parent = jv.name and jv.docstatus=1 and jvd.account = %(account)s {0} - order by posting_date DESC, jv.name DESC""".format( - conditions - ), + jvd.parent = jv.name and jv.docstatus=1 and jvd.account = %(account)s {conditions} + order by posting_date DESC, jv.name DESC""", filters, as_list=1, ) payment_entries = frappe.db.sql( - """SELECT + f"""SELECT "Payment Entry", name, posting_date, reference_no, clearance_date, party, if(paid_from=%(account)s, ((paid_amount * -1) - total_taxes_and_charges) , received_amount) FROM `tabPayment Entry` WHERE - docstatus=1 and (paid_from = %(account)s or paid_to = %(account)s) {0} - order by posting_date DESC, name DESC""".format( - conditions - ), + docstatus=1 and (paid_from = %(account)s or paid_to = %(account)s) {conditions} + order by posting_date DESC, name DESC""", filters, as_list=1, ) diff --git a/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py b/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py index fbc1a69ddc5..7c2389d8dd5 100644 --- a/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py +++ b/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py @@ -35,10 +35,7 @@ def execute(filters=None): amounts_not_reflected_in_system = get_amounts_not_reflected_in_system(filters) bank_bal = ( - flt(balance_as_per_system) - - flt(total_debit) - + flt(total_credit) - + amounts_not_reflected_in_system + flt(balance_as_per_system) - flt(total_debit) + flt(total_credit) + amounts_not_reflected_in_system ) data += [ @@ -220,7 +217,7 @@ def get_loan_entries(filters): ) if doctype == "Loan Repayment" and frappe.db.has_column("Loan Repayment", "repay_from_salary"): - query = query.where((loan_doc.repay_from_salary == 0)) + query = query.where(loan_doc.repay_from_salary == 0) entries = query.run(as_dict=1) loan_docs.extend(entries) @@ -282,7 +279,7 @@ def get_loan_amount(filters): ) if doctype == "Loan Repayment" and frappe.db.has_column("Loan Repayment", "repay_from_salary"): - query = query.where((loan_doc.repay_from_salary == 0)) + query = query.where(loan_doc.repay_from_salary == 0) amount = query.run()[0][0] total_amount += flt(amount) diff --git a/erpnext/accounts/report/billed_items_to_be_received/billed_items_to_be_received.py b/erpnext/accounts/report/billed_items_to_be_received/billed_items_to_be_received.py index 62bee82590b..f6efc8a685c 100644 --- a/erpnext/accounts/report/billed_items_to_be_received/billed_items_to_be_received.py +++ b/erpnext/accounts/report/billed_items_to_be_received/billed_items_to_be_received.py @@ -30,9 +30,7 @@ def get_report_filters(report_filters): ] if report_filters.get("purchase_invoice"): - filters.append( - ["Purchase Invoice", "per_received", "in", [report_filters.get("purchase_invoice")]] - ) + filters.append(["Purchase Invoice", "per_received", "in", [report_filters.get("purchase_invoice")]]) return filters @@ -40,10 +38,10 @@ def get_report_filters(report_filters): def get_report_fields(): fields = [] for p_field in ["name", "supplier", "company", "posting_date", "currency"]: - fields.append("`tabPurchase Invoice`.`{}`".format(p_field)) + fields.append(f"`tabPurchase Invoice`.`{p_field}`") for c_field in ["item_code", "item_name", "uom", "qty", "received_qty", "rate", "amount"]: - fields.append("`tabPurchase Invoice Item`.`{}`".format(c_field)) + fields.append(f"`tabPurchase Invoice Item`.`{c_field}`") return fields diff --git a/erpnext/accounts/report/budget_variance_report/budget_variance_report.py b/erpnext/accounts/report/budget_variance_report/budget_variance_report.py index 96cfab9f11f..e540aa9993c 100644 --- a/erpnext/accounts/report/budget_variance_report/budget_variance_report.py +++ b/erpnext/accounts/report/budget_variance_report/budget_variance_report.py @@ -112,7 +112,9 @@ def get_columns(filters): ]: if group_months: label = label % ( - formatdate(from_date, format_string="MMM") + "-" + formatdate(to_date, format_string="MMM") + formatdate(from_date, format_string="MMM") + + "-" + + formatdate(to_date, format_string="MMM") ) else: label = label % formatdate(from_date, format_string="MMM") @@ -147,9 +149,7 @@ def get_cost_centers(filters): where company = %s {order_by} - """.format( - tab=filters.get("budget_against"), order_by=order_by - ), + """.format(tab=filters.get("budget_against"), order_by=order_by), filters.get("company"), ) else: @@ -159,9 +159,7 @@ def get_cost_centers(filters): name from `tab{tab}` - """.format( - tab=filters.get("budget_against") - ) + """.format(tab=filters.get("budget_against")) ) # nosec @@ -170,12 +168,12 @@ def get_dimension_target_details(filters): budget_against = frappe.scrub(filters.get("budget_against")) cond = "" if filters.get("budget_against_filter"): - cond += """ and b.{budget_against} in (%s)""".format(budget_against=budget_against) % ", ".join( + cond += f""" and b.{budget_against} in (%s)""" % ", ".join( ["%s"] * len(filters.get("budget_against_filter")) ) return frappe.db.sql( - """ + f""" select b.{budget_against} as budget_against, b.monthly_distribution, @@ -194,10 +192,7 @@ def get_dimension_target_details(filters): {cond} order by b.fiscal_year - """.format( - budget_against=budget_against, - cond=cond, - ), + """, tuple( [ filters.from_fiscal_year, @@ -244,15 +239,13 @@ def get_actual_details(name, filters): if filters.get("budget_against") == "Cost Center": cc_lft, cc_rgt = frappe.db.get_value("Cost Center", name, ["lft", "rgt"]) - cond = """ - and lft >= "{lft}" - and rgt <= "{rgt}" - """.format( - lft=cc_lft, rgt=cc_rgt - ) + cond = f""" + and lft >= "{cc_lft}" + and rgt <= "{cc_rgt}" + """ ac_details = frappe.db.sql( - """ + f""" select gl.account, gl.debit, @@ -275,7 +268,7 @@ def get_actual_details(name, filters): select name from - `tab{tab}` + `tab{filters.budget_against}` where name = gl.{budget_against} {cond} @@ -283,9 +276,7 @@ def get_actual_details(name, filters): group by gl.name order by gl.fiscal_year - """.format( - tab=filters.budget_against, budget_against=budget_against, cond=cond - ), + """, (filters.from_fiscal_year, filters.to_fiscal_year, name), as_dict=1, ) @@ -314,7 +305,9 @@ def get_dimension_account_month_map(filters): tav_dict = cam_map[ccd.budget_against][ccd.account][ccd.fiscal_year][month] month_percentage = ( - tdd.get(ccd.monthly_distribution, {}).get(month, 0) if ccd.monthly_distribution else 100.0 / 12 + tdd.get(ccd.monthly_distribution, {}).get(month, 0) + if ccd.monthly_distribution + else 100.0 / 12 ) tav_dict.target = flt(ccd.budget_amount) * month_percentage / 100 @@ -327,7 +320,6 @@ def get_dimension_account_month_map(filters): def get_fiscal_years(filters): - fiscal_year = frappe.db.sql( """ select @@ -344,7 +336,6 @@ def get_fiscal_years(filters): def get_chart_data(filters, columns, data): - if not data: return None @@ -360,7 +351,9 @@ def get_chart_data(filters, columns, data): else: if group_months: label = ( - formatdate(from_date, format_string="MMM") + "-" + formatdate(to_date, format_string="MMM") + formatdate(from_date, format_string="MMM") + + "-" + + formatdate(to_date, format_string="MMM") ) labels.append(label) else: diff --git a/erpnext/accounts/report/cash_flow/cash_flow.py b/erpnext/accounts/report/cash_flow/cash_flow.py index af706811ab2..87bde218dae 100644 --- a/erpnext/accounts/report/cash_flow/cash_flow.py +++ b/erpnext/accounts/report/cash_flow/cash_flow.py @@ -114,9 +114,7 @@ def execute(filters=None): add_total_row_account( data, data, _("Net Change in Cash"), period_list, company_currency, summary_data, filters ) - columns = get_columns( - filters.periodicity, period_list, filters.accumulated_values, filters.company - ) + columns = get_columns(filters.periodicity, period_list, filters.accumulated_values, filters.company) chart = get_chart_data(columns, data) @@ -183,8 +181,8 @@ def get_account_type_based_gl_data(company, filters=None): if filters.include_default_book_entries: company_fb = frappe.db.get_value("Company", company, "default_finance_book") - cond = """ AND (finance_book in (%s, %s, '') OR finance_book IS NULL) - """ % ( + cond = """ AND (finance_book in ({}, {}, '') OR finance_book IS NULL) + """.format( frappe.db.escape(filters.finance_book), frappe.db.escape(company_fb), ) @@ -198,15 +196,13 @@ def get_account_type_based_gl_data(company, filters=None): cond += " and cost_center in %(cost_center)s" gl_sum = frappe.db.sql_list( - """ + f""" select sum(credit) - sum(debit) from `tabGL Entry` where company=%(company)s and posting_date >= %(start_date)s and posting_date <= %(end_date)s and voucher_type != 'Period Closing Voucher' and account in ( SELECT name FROM tabAccount WHERE account_type = %(account_type)s) {cond} - """.format( - cond=cond - ), + """, filters, ) @@ -224,9 +220,7 @@ def get_start_date(period, accumulated_values, company): return start_date -def add_total_row_account( - out, data, label, period_list, currency, summary_data, filters, consolidated=False -): +def add_total_row_account(out, data, label, period_list, currency, summary_data, filters, consolidated=False): total_row = { "account_name": "'" + _("{0}").format(label) + "'", "account": "'" + _("{0}").format(label) + "'", @@ -258,9 +252,7 @@ def get_report_summary(summary_data, currency): report_summary = [] for label, value in summary_data.items(): - report_summary.append( - {"value": value, "label": label, "datatype": "Currency", "currency": currency} - ) + report_summary.append({"value": value, "label": label, "datatype": "Currency", "currency": currency}) return report_summary @@ -273,7 +265,7 @@ def get_chart_data(columns, data): "values": [account.get(d.get("fieldname")) for d in columns[2:]], } for account in data - if account.get("parent_account") == None and account.get("currency") + if account.get("parent_account") is None and account.get("currency") ] datasets = datasets[:-1] diff --git a/erpnext/accounts/report/cash_flow/custom_cash_flow.py b/erpnext/accounts/report/cash_flow/custom_cash_flow.py index 24e585e07f6..2e227609b0e 100644 --- a/erpnext/accounts/report/cash_flow/custom_cash_flow.py +++ b/erpnext/accounts/report/cash_flow/custom_cash_flow.py @@ -131,7 +131,12 @@ def setup_mappers(mappers): account_types_labels = sorted( set( - (d["label"], d["is_working_capital"], d["is_income_tax_liability"], d["is_income_tax_expense"]) + ( + d["label"], + d["is_working_capital"], + d["is_income_tax_liability"], + d["is_income_tax_expense"], + ) for d in account_types ), key=lambda x: x[1], @@ -319,14 +324,10 @@ def add_data_for_operating_activities( data.append(interest_paid) section_data.append(interest_paid) - _add_total_row_account( - data, section_data, mapper["section_footer"], period_list, company_currency - ) + _add_total_row_account(data, section_data, mapper["section_footer"], period_list, company_currency) -def calculate_adjustment( - filters, non_expense_mapper, expense_mapper, use_accumulated_values, period_list -): +def calculate_adjustment(filters, non_expense_mapper, expense_mapper, use_accumulated_values, period_list): liability_accounts = [d["names"] for d in non_expense_mapper] expense_accounts = [d["names"] for d in expense_mapper] @@ -388,9 +389,7 @@ def add_data_for_other_activities( data.append(account_data) section_data.append(account_data) - _add_total_row_account( - data, section_data, mapper["section_footer"], period_list, company_currency - ) + _add_total_row_account(data, section_data, mapper["section_footer"], period_list, company_currency) def compute_data(filters, company_currency, profit_data, period_list, light_mappers, full_mapper): @@ -465,21 +464,15 @@ def execute(filters=None): company_currency = frappe.get_cached_value("Company", filters.company, "default_currency") - data = compute_data( - filters, company_currency, net_profit_loss, period_list, mappers, cash_flow_accounts - ) + data = compute_data(filters, company_currency, net_profit_loss, period_list, mappers, cash_flow_accounts) _add_total_row_account(data, data, _("Net Change in Cash"), period_list, company_currency) - columns = get_columns( - filters.periodicity, period_list, filters.accumulated_values, filters.company - ) + columns = get_columns(filters.periodicity, period_list, filters.accumulated_values, filters.company) return columns, data -def _get_account_type_based_data( - filters, account_names, period_list, accumulated_values, opening_balances=0 -): +def _get_account_type_based_data(filters, account_names, period_list, accumulated_values, opening_balances=0): if not account_names or not account_names[0] or not type(account_names[0]) == str: # only proceed if account_names is a list of account names return {} diff --git a/erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py b/erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py index fe4b6c71ebc..794721b6c92 100644 --- a/erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py +++ b/erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py @@ -55,9 +55,7 @@ def execute(filters=None): fiscal_year, companies, columns, filters ) elif filters.get("report") == "Profit and Loss Statement": - data, message, chart, report_summary = get_profit_loss_data( - fiscal_year, companies, columns, filters - ) + data, message, chart, report_summary = get_profit_loss_data(fiscal_year, companies, columns, filters) else: if cint(frappe.db.get_single_value("Accounts Settings", "use_custom_cash_flow")): from erpnext.accounts.report.cash_flow.custom_cash_flow import execute as execute_custom @@ -86,9 +84,7 @@ def get_balance_sheet_data(fiscal_year, companies, columns, filters): asset, liability, equity, companies, filters.get("company"), company_currency, True ) - message, opening_balance = prepare_companywise_opening_balance( - asset, liability, equity, companies - ) + message, opening_balance = prepare_companywise_opening_balance(asset, liability, equity, companies) if opening_balance: unclosed = { @@ -197,9 +193,7 @@ def get_income_expense_data(companies, fiscal_year, filters): expense = get_data(companies, "Expense", "Debit", fiscal_year, filters, True) - net_profit_loss = get_net_profit_loss( - income, expense, companies, filters.company, company_currency, True - ) + net_profit_loss = get_net_profit_loss(income, expense, companies, filters.company, company_currency, True) return income, expense, net_profit_loss @@ -328,9 +322,7 @@ def get_columns(companies, filters): return columns -def get_data( - companies, root_type, balance_must_be, fiscal_year, filters=None, ignore_closing_entries=False -): +def get_data(companies, root_type, balance_must_be, fiscal_year, filters=None, ignore_closing_entries=False): accounts, accounts_by_name, parent_children_map = get_account_heads(root_type, companies, filters) if not accounts: @@ -354,7 +346,6 @@ def get_data( root_type, as_dict=1, ): - set_gl_entries_by_account( start_date, end_date, @@ -371,9 +362,7 @@ def get_data( calculate_values(accounts_by_name, gl_entries_by_account, companies, filters, fiscal_year) accumulate_values_into_parents(accounts, accounts_by_name, companies) - out = prepare_data( - accounts, start_date, end_date, balance_must_be, companies, company_currency, filters - ) + out = prepare_data(accounts, start_date, end_date, balance_must_be, companies, company_currency, filters) out = filter_out_zero_value_rows( out, parent_children_map, show_zero_values=filters.get("show_zero_values") @@ -393,9 +382,7 @@ def get_company_currency(filters=None): def calculate_values(accounts_by_name, gl_entries_by_account, companies, filters, fiscal_year): start_date = ( - fiscal_year.year_start_date - if filters.filter_based_on == "Fiscal Year" - else filters.period_start_date + fiscal_year.year_start_date if filters.filter_based_on == "Fiscal Year" else filters.period_start_date ) for entries in gl_entries_by_account.values(): @@ -427,8 +414,12 @@ def calculate_values(accounts_by_name, gl_entries_by_account, companies, filters and parent_company_currency != child_company_currency and filters.get("accumulated_in_group_company") ): - debit = convert(debit, parent_company_currency, child_company_currency, filters.end_date) - credit = convert(credit, parent_company_currency, child_company_currency, filters.end_date) + debit = convert( + debit, parent_company_currency, child_company_currency, filters.end_date + ) + credit = convert( + credit, parent_company_currency, child_company_currency, filters.end_date + ) d[company] = d.get(company, 0.0) + flt(debit) - flt(credit) @@ -512,10 +503,8 @@ def get_subsidiary_companies(company): lft, rgt = frappe.get_cached_value("Company", company, ["lft", "rgt"]) return frappe.db.sql_list( - """select name from `tabCompany` - where lft >= {0} and rgt <= {1} order by lft, rgt""".format( - lft, rgt - ) + f"""select name from `tabCompany` + where lft >= {lft} and rgt <= {rgt} order by lft, rgt""" ) @@ -552,9 +541,7 @@ def get_accounts(root_type, companies): return accounts -def prepare_data( - accounts, start_date, end_date, balance_must_be, companies, company_currency, filters -): +def prepare_data(accounts, start_date, end_date, balance_must_be, companies, company_currency, filters): data = [] for d in accounts: @@ -564,9 +551,7 @@ def prepare_data( row = frappe._dict( { "account_name": ( - "%s - %s" % (_(d.account_number), _(d.account_name)) - if d.account_number - else _(d.account_name) + f"{_(d.account_number)} - {_(d.account_name)}" if d.account_number else _(d.account_name) ), "account": _(d.name), "parent_account": _(d.parent_account), @@ -614,9 +599,7 @@ def set_gl_entries_by_account( ): """Returns a dict like { "account": [gl entries], ... }""" - company_lft, company_rgt = frappe.get_cached_value( - "Company", filters.get("company"), ["lft", "rgt"] - ) + company_lft, company_rgt = frappe.get_cached_value("Company", filters.get("company"), ["lft", "rgt"]) companies = frappe.db.sql( """ select name, default_currency from `tabCompany` @@ -744,7 +727,7 @@ def get_additional_conditions(from_date, ignore_closing_entries, filters, d): additional_conditions = [] if ignore_closing_entries: - additional_conditions.append((gle.voucher_type != "Period Closing Voucher")) + additional_conditions.append(gle.voucher_type != "Period Closing Voucher") if from_date: additional_conditions.append(gle.posting_date >= from_date) @@ -807,7 +790,7 @@ def filter_accounts(accounts, depth=10): def add_to_list(parent, level): if level < depth: children = parent_children_map.get(parent) or [] - sort_accounts(children, is_root=True if parent == None else False) + sort_accounts(children, is_root=True if parent is None else False) for child in children: child.indent = level diff --git a/erpnext/accounts/report/customer_ledger_summary/customer_ledger_summary.py b/erpnext/accounts/report/customer_ledger_summary/customer_ledger_summary.py index 2da6d18f005..108f9f617df 100644 --- a/erpnext/accounts/report/customer_ledger_summary/customer_ledger_summary.py +++ b/erpnext/accounts/report/customer_ledger_summary/customer_ledger_summary.py @@ -7,7 +7,7 @@ from frappe import _, qb, scrub from frappe.utils import getdate, nowdate -class PartyLedgerSummaryReport(object): +class PartyLedgerSummaryReport: def __init__(self, filters=None): self.filters = frappe._dict(filters or {}) self.filters.from_date = getdate(self.filters.from_date or nowdate()) @@ -21,9 +21,7 @@ class PartyLedgerSummaryReport(object): frappe.throw(_("From Date must be before To Date")) self.filters.party_type = args.get("party_type") - self.party_naming_by = frappe.db.get_value( - args.get("naming_by")[0], None, args.get("naming_by")[1] - ) + self.party_naming_by = frappe.db.get_value(args.get("naming_by")[0], None, args.get("naming_by")[1]) self.get_gl_entries() self.get_additional_columns() @@ -49,7 +47,7 @@ class PartyLedgerSummaryReport(object): .select( customer.name, customer.territory, customer.customer_group, customer.default_sales_partner ) - .where((customer.disabled == 0)) + .where(customer.disabled == 0) .run(as_dict=True) ) @@ -62,7 +60,7 @@ class PartyLedgerSummaryReport(object): result = ( frappe.qb.from_(supplier) .select(supplier.name, supplier.supplier_group) - .where((supplier.disabled == 0)) + .where(supplier.disabled == 0) .run(as_dict=True) ) @@ -184,9 +182,7 @@ class PartyLedgerSummaryReport(object): return columns def get_data(self): - company_currency = frappe.get_cached_value( - "Company", self.filters.get("company"), "default_currency" - ) + company_currency = frappe.get_cached_value("Company", self.filters.get("company"), "default_currency") invoice_dr_or_cr = "debit" if self.filters.party_type == "Customer" else "credit" reverse_dr_or_cr = "credit" if self.filters.party_type == "Customer" else "debit" @@ -260,7 +256,7 @@ class PartyLedgerSummaryReport(object): join = "left join `tabSupplier` p on gle.party = p.name" self.gl_entries = frappe.db.sql( - """ + f""" select gle.posting_date, gle.party, gle.voucher_type, gle.voucher_no, gle.against_voucher_type, gle.against_voucher, gle.debit, gle.credit, gle.is_opening {join_field} @@ -270,9 +266,7 @@ class PartyLedgerSummaryReport(object): gle.docstatus < 2 and gle.is_cancelled = 0 and gle.party_type=%(party_type)s and ifnull(gle.party, '') != '' and gle.posting_date <= %(to_date)s {conditions} order by gle.posting_date - """.format( - join=join, join_field=join_field, conditions=conditions - ), + """, self.filters, as_dict=True, ) @@ -296,22 +290,18 @@ class PartyLedgerSummaryReport(object): ) conditions.append( - """party in (select name from tabCustomer - where exists(select name from `tabCustomer Group` where lft >= {0} and rgt <= {1} - and name=tabCustomer.customer_group))""".format( - lft, rgt - ) + f"""party in (select name from tabCustomer + where exists(select name from `tabCustomer Group` where lft >= {lft} and rgt <= {rgt} + and name=tabCustomer.customer_group))""" ) if self.filters.get("territory"): lft, rgt = frappe.db.get_value("Territory", self.filters.get("territory"), ["lft", "rgt"]) conditions.append( - """party in (select name from tabCustomer - where exists(select name from `tabTerritory` where lft >= {0} and rgt <= {1} - and name=tabCustomer.territory))""".format( - lft, rgt - ) + f"""party in (select name from tabCustomer + where exists(select name from `tabTerritory` where lft >= {lft} and rgt <= {rgt} + and name=tabCustomer.territory))""" ) if self.filters.get("payment_terms_template"): @@ -331,12 +321,10 @@ class PartyLedgerSummaryReport(object): conditions.append( """exists(select name from `tabSales Team` steam where - steam.sales_person in (select name from `tabSales Person` where lft >= {0} and rgt <= {1}) + steam.sales_person in (select name from `tabSales Person` where lft >= {} and rgt <= {}) and ((steam.parent = voucher_no and steam.parenttype = voucher_type) or (steam.parent = against_voucher and steam.parenttype = against_voucher_type) - or (steam.parent = party and steam.parenttype = 'Customer')))""".format( - lft, rgt - ) + or (steam.parent = party and steam.parenttype = 'Customer')))""".format(lft, rgt) ) if self.filters.party_type == "Supplier": @@ -392,7 +380,7 @@ class PartyLedgerSummaryReport(object): ) gl_entries = frappe.db.sql( - """ + f""" select posting_date, account, party, voucher_type, voucher_no, debit, credit from @@ -406,10 +394,7 @@ class PartyLedgerSummaryReport(object): where gle.party_type=%(party_type)s and ifnull(party, '') != '' and gle.posting_date between %(from_date)s and %(to_date)s and gle.docstatus < 2 {conditions} ) - """.format( - accounts_query=accounts_query, - conditions=conditions, - ), + """, self.filters, as_dict=True, ) @@ -440,14 +425,14 @@ class PartyLedgerSummaryReport(object): if parties and accounts: if len(parties) == 1: - party = list(parties.keys())[0] + party = next(iter(parties.keys())) for account, amount in accounts.items(): self.party_adjustment_accounts.add(account) self.party_adjustment_details.setdefault(party, {}) self.party_adjustment_details[party].setdefault(account, 0) self.party_adjustment_details[party][account] += amount elif len(accounts) == 1 and not has_irrelevant_entry: - account = list(accounts.keys())[0] + account = next(iter(accounts.keys())) self.party_adjustment_accounts.add(account) for party, amount in parties.items(): self.party_adjustment_details.setdefault(party, {}) diff --git a/erpnext/accounts/report/deferred_revenue_and_expense/deferred_revenue_and_expense.py b/erpnext/accounts/report/deferred_revenue_and_expense/deferred_revenue_and_expense.py index cad5325c6e9..303305d20c5 100644 --- a/erpnext/accounts/report/deferred_revenue_and_expense/deferred_revenue_and_expense.py +++ b/erpnext/accounts/report/deferred_revenue_and_expense/deferred_revenue_and_expense.py @@ -10,7 +10,7 @@ from erpnext.accounts.report.financial_statements import get_period_list from erpnext.accounts.utils import get_fiscal_year -class Deferred_Item(object): +class Deferred_Item: """ Helper class for processing items with deferred revenue/expense """ @@ -152,13 +152,11 @@ class Deferred_Item(object): if posting.posted == "posted": actual += self.get_amount(posting) - self.period_total.append( - frappe._dict({"key": period.key, "total": period_sum, "actual": actual}) - ) + self.period_total.append(frappe._dict({"key": period.key, "total": period_sum, "actual": actual})) return self.period_total -class Deferred_Invoice(object): +class Deferred_Invoice: def __init__(self, invoice, items, filters, period_list): """ Helper class for processing invoices with deferred revenue/expense items @@ -219,7 +217,7 @@ class Deferred_Invoice(object): return ret_data -class Deferred_Revenue_and_Expense_Report(object): +class Deferred_Revenue_and_Expense_Report: def __init__(self, filters=None): """ Initialize deferred revenue/expense report with user provided filters or system defaults, if none is provided diff --git a/erpnext/accounts/report/deferred_revenue_and_expense/test_deferred_revenue_and_expense.py b/erpnext/accounts/report/deferred_revenue_and_expense/test_deferred_revenue_and_expense.py index 7b1a9027780..f8a965b699c 100644 --- a/erpnext/accounts/report/deferred_revenue_and_expense/test_deferred_revenue_and_expense.py +++ b/erpnext/accounts/report/deferred_revenue_and_expense/test_deferred_revenue_and_expense.py @@ -1,5 +1,3 @@ -import unittest - import frappe from frappe import qb from frappe.tests.utils import FrappeTestCase, change_settings @@ -13,8 +11,6 @@ from erpnext.accounts.report.deferred_revenue_and_expense.deferred_revenue_and_e ) from erpnext.accounts.test.accounts_mixin import AccountsTestMixin from erpnext.accounts.utils import get_fiscal_year -from erpnext.buying.doctype.supplier.test_supplier import create_supplier -from erpnext.stock.doctype.item.test_item import create_item class TestDeferredRevenueAndExpense(FrappeTestCase, AccountsTestMixin): diff --git a/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py b/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py index ecad9f104fa..6c1e73d5edc 100644 --- a/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py +++ b/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py @@ -15,7 +15,6 @@ from erpnext.accounts.report.trial_balance.trial_balance import validate_filters def execute(filters=None): - validate_filters(filters) dimension_list = get_dimensions(filters) @@ -90,9 +89,7 @@ def set_gl_entries_by_account(dimension_list, filters, account, gl_entries_by_ac gl_filters["dimensions"] = set(dimension_list) if filters.get("include_default_book_entries"): - gl_filters["company_fb"] = frappe.db.get_value( - "Company", filters.company, "default_finance_book" - ) + gl_filters["company_fb"] = frappe.db.get_value("Company", filters.company, "default_finance_book") gl_entries = frappe.db.sql( """ @@ -119,7 +116,6 @@ def set_gl_entries_by_account(dimension_list, filters, account, gl_entries_by_ac def format_gl_entries(gl_entries_by_account, accounts_by_name, dimension_list, dimension_type): - for entries in gl_entries_by_account.values(): for entry in entries: d = accounts_by_name.get(entry.account) @@ -151,7 +147,7 @@ def prepare_data(accounts, filters, company_currency, dimension_list): "to_date": filters.to_date, "currency": company_currency, "account_name": ( - "{} - {}".format(d.account_number, d.account_name) if d.account_number else d.account_name + f"{d.account_number} - {d.account_name}" if d.account_number else d.account_name ), } @@ -183,7 +179,7 @@ def accumulate_values_into_parents(accounts, accounts_by_name, dimension_list): def get_condition(dimension): conditions = [] - conditions.append("{0} in %(dimensions)s".format(frappe.scrub(dimension))) + conditions.append(f"{frappe.scrub(dimension)} in %(dimensions)s") return " and {}".format(" and ".join(conditions)) if conditions else "" diff --git a/erpnext/accounts/report/financial_statements.py b/erpnext/accounts/report/financial_statements.py index 096bb107069..56f3bd1caa4 100644 --- a/erpnext/accounts/report/financial_statements.py +++ b/erpnext/accounts/report/financial_statements.py @@ -162,7 +162,6 @@ def get_data( ignore_accumulated_values_for_fy=False, total=True, ): - accounts = get_accounts(company, root_type) if not accounts: return None @@ -178,7 +177,6 @@ def get_data( root_type, as_dict=1, ): - set_gl_entries_by_account( company, period_list[0]["year_start_date"] if only_current_fiscal_year else None, @@ -236,7 +234,8 @@ def calculate_values( if entry.posting_date <= period.to_date: if (accumulated_values or entry.posting_date >= period.from_date) and ( - not ignore_accumulated_values_for_fy or entry.fiscal_year == period.to_date_fiscal_year + not ignore_accumulated_values_for_fy + or entry.fiscal_year == period.to_date_fiscal_year ): d[period.key] = d.get(period.key, 0.0) + flt(entry.debit) - flt(entry.credit) @@ -280,9 +279,7 @@ def prepare_data(accounts, balance_must_be, period_list, company_currency): "is_group": d.is_group, "opening_balance": d.get("opening_balance", 0.0) * (1 if balance_must_be == "Debit" else -1), "account_name": ( - "%s - %s" % (_(d.account_number), _(d.account_name)) - if d.account_number - else _(d.account_name) + f"{_(d.account_number)} - {_(d.account_name)}" if d.account_number else _(d.account_name) ), } ) @@ -370,7 +367,7 @@ def filter_accounts(accounts, depth=20): def add_to_list(parent, level): if level < depth: children = parent_children_map.get(parent) or [] - sort_accounts(children, is_root=True if parent == None else False) + sort_accounts(children, is_root=True if parent is None else False) for child in children: child.indent = level @@ -561,7 +558,9 @@ def apply_additional_conditions(doctype, query, from_date, ignore_closing_entrie company_fb = frappe.get_cached_value("Company", filters.company, "default_finance_book") if filters.finance_book and company_fb and cstr(filters.finance_book) != cstr(company_fb): - frappe.throw(_("To use a different finance book, please uncheck 'Include Default FB Entries'")) + frappe.throw( + _("To use a different finance book, please uncheck 'Include Default FB Entries'") + ) query = query.where( (gl_entry.finance_book.isin([cstr(filters.finance_book), cstr(company_fb), ""])) diff --git a/erpnext/accounts/report/general_and_payment_ledger_comparison/general_and_payment_ledger_comparison.py b/erpnext/accounts/report/general_and_payment_ledger_comparison/general_and_payment_ledger_comparison.py index 696a03b0a70..89cf7e504f0 100644 --- a/erpnext/accounts/report/general_and_payment_ledger_comparison/general_and_payment_ledger_comparison.py +++ b/erpnext/accounts/report/general_and_payment_ledger_comparison/general_and_payment_ledger_comparison.py @@ -7,7 +7,7 @@ from frappe.query_builder import Criterion from frappe.query_builder.functions import Sum -class General_Payment_Ledger_Comparison(object): +class General_Payment_Ledger_Comparison: """ A Utility report to compare Voucher-wise balance between General and Payment Ledger """ @@ -58,10 +58,9 @@ class General_Payment_Ledger_Comparison(object): for acc_type, val in self.account_types.items(): if val.accounts: - filter_criterion = [] if self.filters.voucher_no: - filter_criterion.append((gle.voucher_no == self.filters.voucher_no)) + filter_criterion.append(gle.voucher_no == self.filters.voucher_no) if self.filters.period_start_date: filter_criterion.append(gle.posting_date.gte(self.filters.period_start_date)) @@ -102,10 +101,9 @@ class General_Payment_Ledger_Comparison(object): for acc_type, val in self.account_types.items(): if val.accounts: - filter_criterion = [] if self.filters.voucher_no: - filter_criterion.append((ple.voucher_no == self.filters.voucher_no)) + filter_criterion.append(ple.voucher_no == self.filters.voucher_no) if self.filters.period_start_date: filter_criterion.append(ple.posting_date.gte(self.filters.period_start_date)) @@ -141,7 +139,7 @@ class General_Payment_Ledger_Comparison(object): self.ple_balances = set() # consolidate both receivable and payable balances in one set - for acc_type, val in self.account_types.items(): + for _acc_type, val in self.account_types.items(): self.gle_balances = set(val.gle) | self.gle_balances self.ple_balances = set(val.ple) | self.ple_balances @@ -177,7 +175,6 @@ class General_Payment_Ledger_Comparison(object): def get_columns(self): self.columns = [] - options = None self.columns.append( dict( label=_("Company"), diff --git a/erpnext/accounts/report/general_and_payment_ledger_comparison/test_general_and_payment_ledger_comparison.py b/erpnext/accounts/report/general_and_payment_ledger_comparison/test_general_and_payment_ledger_comparison.py index 59e906ba332..afa81b83cfc 100644 --- a/erpnext/accounts/report/general_and_payment_ledger_comparison/test_general_and_payment_ledger_comparison.py +++ b/erpnext/accounts/report/general_and_payment_ledger_comparison/test_general_and_payment_ledger_comparison.py @@ -1,5 +1,3 @@ -import unittest - import frappe from frappe import qb from frappe.tests.utils import FrappeTestCase @@ -40,9 +38,7 @@ class TestGeneralAndPaymentLedger(FrappeTestCase, AccountsTestMixin): ) # manually edit the payment ledger entry - ple = frappe.db.get_all( - "Payment Ledger Entry", filters={"voucher_no": sinv.name, "delinked": 0} - )[0] + ple = frappe.db.get_all("Payment Ledger Entry", filters={"voucher_no": sinv.name, "delinked": 0})[0] frappe.db.set_value("Payment Ledger Entry", ple.name, "amount", sinv.grand_total - 1) filters = frappe._dict({"company": self.company}) diff --git a/erpnext/accounts/report/general_ledger/general_ledger.py b/erpnext/accounts/report/general_ledger/general_ledger.py index 269d25b99db..685797abd19 100644 --- a/erpnext/accounts/report/general_ledger/general_ledger.py +++ b/erpnext/accounts/report/general_ledger/general_ledger.py @@ -102,9 +102,7 @@ def validate_party(filters): def set_account_currency(filters): if filters.get("account") or (filters.get("party") and len(filters.party) == 1): - filters["company_currency"] = frappe.get_cached_value( - "Company", filters.company, "default_currency" - ) + filters["company_currency"] = frappe.get_cached_value("Company", filters.company, "default_currency") account_currency = None if filters.get("account"): @@ -164,9 +162,7 @@ def get_gl_entries(filters, accounting_dimensions): credit_in_account_currency """ if filters.get("show_remarks"): - if remarks_length := frappe.db.get_single_value( - "Accounts Settings", "general_ledger_remarks_length" - ): + if remarks_length := frappe.db.get_single_value("Accounts Settings", "general_ledger_remarks_length"): select_fields += f",substr(remarks, 1, {remarks_length}) as 'remarks'" else: select_fields += """,remarks""" @@ -182,16 +178,14 @@ def get_gl_entries(filters, accounting_dimensions): order_by_statement = "order by account, posting_date, creation" if filters.get("include_default_book_entries"): - filters["company_fb"] = frappe.db.get_value( - "Company", filters.get("company"), "default_finance_book" - ) + filters["company_fb"] = frappe.db.get_value("Company", filters.get("company"), "default_finance_book") dimension_fields = "" if accounting_dimensions: dimension_fields = ", ".join(accounting_dimensions) + "," gl_entries = frappe.db.sql( - """ + f""" select name as gl_entry, posting_date, account, party_type, party, voucher_type, voucher_no, {dimension_fields} @@ -199,14 +193,9 @@ def get_gl_entries(filters, accounting_dimensions): against_voucher_type, against_voucher, account_currency, against, is_opening, creation {select_fields} from `tabGL Entry` - where company=%(company)s {conditions} + where company=%(company)s {get_conditions(filters)} {order_by_statement} - """.format( - dimension_fields=dimension_fields, - select_fields=select_fields, - conditions=get_conditions(filters), - order_by_statement=order_by_statement, - ), + """, filters, as_dict=1, ) @@ -273,7 +262,9 @@ def get_conditions(filters): if filters.get("company_fb") and cstr(filters.get("finance_book")) != cstr( filters.get("company_fb") ): - frappe.throw(_("To use a different finance book, please uncheck 'Include Default FB Entries'")) + frappe.throw( + _("To use a different finance book, please uncheck 'Include Default FB Entries'") + ) else: conditions.append("(finance_book in (%(finance_book)s, '') OR finance_book IS NULL)") else: @@ -305,9 +296,9 @@ def get_conditions(filters): filters[dimension.fieldname] = get_dimension_with_children( dimension.document_type, filters.get(dimension.fieldname) ) - conditions.append("{0} in %({0})s".format(dimension.fieldname)) + conditions.append(f"{dimension.fieldname} in %({dimension.fieldname})s") else: - conditions.append("{0} in %({0})s".format(dimension.fieldname)) + conditions.append(f"{dimension.fieldname} in %({dimension.fieldname})s") return "and {}".format(" and ".join(conditions)) if conditions else "" @@ -339,7 +330,7 @@ def get_data_with_opening_closing(filters, account_details, accounting_dimension data.append(totals.opening) if filters.get("group_by") != "Group by Voucher (Consolidated)": - for acc, acc_dict in gle_map.items(): + for _acc, acc_dict in gle_map.items(): # acc if acc_dict.entries: # opening @@ -371,7 +362,7 @@ def get_data_with_opening_closing(filters, account_details, accounting_dimension def get_totals_dict(): def _get_debit_credit_dict(label): return _dict( - account="'{0}'".format(label), + account=f"'{label}'", debit=0.0, credit=0.0, debit_in_account_currency=0.0, @@ -420,9 +411,10 @@ def get_accountwise_gle(filters, accounting_dimensions, gl_entries, gle_map): data[key].debit_in_account_currency += gle.debit_in_account_currency data[key].credit_in_account_currency += gle.credit_in_account_currency - if filters.get("show_net_values_in_party_account") and account_type_map.get( - data[key].account - ) in ("Receivable", "Payable"): + if filters.get("show_net_values_in_party_account") and account_type_map.get(data[key].account) in ( + "Receivable", + "Payable", + ): net_value = data[key].debit - data[key].credit net_value_in_account_currency = ( data[key].debit_in_account_currency - data[key].credit_in_account_currency @@ -495,21 +487,19 @@ def get_accountwise_gle(filters, accounting_dimensions, gl_entries, gle_map): def get_account_type_map(company): account_type_map = frappe._dict( - frappe.get_all( - "Account", fields=["name", "account_type"], filters={"company": company}, as_list=1 - ) + frappe.get_all("Account", fields=["name", "account_type"], filters={"company": company}, as_list=1) ) return account_type_map def get_result_as_list(data, filters): - balance, balance_in_account_currency = 0, 0 + balance, _balance_in_account_currency = 0, 0 inv_details = get_supplier_invoice_details() for d in data: if not d.get("posting_date"): - balance, balance_in_account_currency = 0, 0 + balance, _balance_in_account_currency = 0, 0 balance = get_balance(d, balance, "debit", "credit") d["balance"] = balance diff --git a/erpnext/accounts/report/general_ledger/test_general_ledger.py b/erpnext/accounts/report/general_ledger/test_general_ledger.py index 75f94309bcc..33b356feb33 100644 --- a/erpnext/accounts/report/general_ledger/test_general_ledger.py +++ b/erpnext/accounts/report/general_ledger/test_general_ledger.py @@ -203,9 +203,7 @@ class TestGeneralLedger(FrappeTestCase): revaluation.extend("accounts", accounts) row = revaluation.accounts[0] row.new_exchange_rate = 83 - row.new_balance_in_base_currency = flt( - row.new_exchange_rate * flt(row.balance_in_account_currency) - ) + row.new_balance_in_base_currency = flt(row.new_exchange_rate * flt(row.balance_in_account_currency)) row.gain_loss = row.new_balance_in_base_currency - flt(row.balance_in_base_currency) revaluation.set_total_gain_loss() revaluation = revaluation.save().submit() diff --git a/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py index 5ccd4f0f16f..b90e2e44bf3 100644 --- a/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py +++ b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py @@ -49,9 +49,7 @@ def execute(filters=None): total=False, ) - columns = get_columns( - filters.periodicity, period_list, filters.accumulated_values, filters.company - ) + columns = get_columns(filters.periodicity, period_list, filters.accumulated_values, filters.company) gross_income = get_revenue(income, period_list) gross_expense = get_revenue(expense, period_list) @@ -119,9 +117,7 @@ def execute(filters=None): def get_revenue(data, period_list, include_in_gross=1): - revenue = [ - item for item in data if item["include_in_gross"] == include_in_gross or item["is_group"] == 1 - ] + revenue = [item for item in data if item["include_in_gross"] == include_in_gross or item["is_group"] == 1] data_to_be_removed = True while data_to_be_removed: diff --git a/erpnext/accounts/report/gross_profit/gross_profit.py b/erpnext/accounts/report/gross_profit/gross_profit.py index 187a154a651..0d61a33e064 100644 --- a/erpnext/accounts/report/gross_profit/gross_profit.py +++ b/erpnext/accounts/report/gross_profit/gross_profit.py @@ -158,9 +158,7 @@ def execute(filters=None): return columns, data -def get_data_when_grouped_by_invoice( - columns, gross_profit_data, filters, group_wise_columns, data -): +def get_data_when_grouped_by_invoice(columns, gross_profit_data, filters, group_wise_columns, data): column_names = get_column_names() # to display item as Item Code: Item Name @@ -395,7 +393,7 @@ def get_column_names(): ) -class GrossProfitGenerator(object): +class GrossProfitGenerator: def __init__(self, filters=None): self.sle = {} self.data = [] @@ -499,7 +497,8 @@ class GrossProfitGenerator(object): for i, row in enumerate(self.grouped[key]): if row.indent == 1.0: if ( - row.parent in self.returned_invoices and row.item_code in self.returned_invoices[row.parent] + row.parent in self.returned_invoices + and row.item_code in self.returned_invoices[row.parent] ): returned_item_rows = self.returned_invoices[row.parent][row.item_code] for returned_item_row in returned_item_rows: @@ -512,7 +511,9 @@ class GrossProfitGenerator(object): row.qty = 0 returned_item_row.qty += row.qty row.base_amount += flt(returned_item_row.base_amount, self.currency_precision) - row.buying_amount = flt(flt(row.qty) * flt(row.buying_rate), self.currency_precision) + row.buying_amount = flt( + flt(row.qty) * flt(row.buying_rate), self.currency_precision + ) if flt(row.qty) or row.base_amount: row = self.set_average_rate(row) self.grouped_data.append(row) @@ -567,9 +568,7 @@ class GrossProfitGenerator(object): new_row.buying_rate = ( flt(new_row.buying_amount / new_row.qty, self.float_precision) if new_row.qty else 0 ) - new_row.base_rate = ( - flt(new_row.base_amount / new_row.qty, self.float_precision) if new_row.qty else 0 - ) + new_row.base_rate = flt(new_row.base_amount / new_row.qty, self.float_precision) if new_row.qty else 0 return new_row def set_average_gross_profit(self, new_row): @@ -656,7 +655,7 @@ class GrossProfitGenerator(object): elif self.delivery_notes.get((row.parent, row.item_code), None): # check if Invoice has delivery notes dn = self.delivery_notes.get((row.parent, row.item_code)) - parenttype, parent, item_row, warehouse = ( + parenttype, parent, item_row, _warehouse = ( "Delivery Note", dn["delivery_note"], dn["item_row"], @@ -695,7 +694,7 @@ class GrossProfitGenerator(object): def get_average_buying_rate(self, row, item_code): args = row - if not item_code in self.average_buying_rate: + if item_code not in self.average_buying_rate: args.update( { "voucher_type": row.parenttype, @@ -748,7 +747,7 @@ class GrossProfitGenerator(object): conditions += " and (is_return = 0 or (is_return=1 and return_against is null))" if self.filters.item_group: - conditions += " and {0}".format(get_item_group_condition(self.filters.item_group)) + conditions += f" and {get_item_group_condition(self.filters.item_group)}" if self.filters.sales_person: conditions += """ @@ -767,12 +766,10 @@ class GrossProfitGenerator(object): if self.filters.group_by == "Payment Term": payment_term_cols = """,if(`tabSales Invoice`.is_return = 1, - '{0}', - coalesce(schedule.payment_term, '{1}')) as payment_term, + '{}', + coalesce(schedule.payment_term, '{}')) as payment_term, schedule.invoice_portion, - schedule.payment_amount """.format( - _("Sales Return"), _("No Terms") - ) + schedule.payment_amount """.format(_("Sales Return"), _("No Terms")) payment_term_table = """ left join `tabPayment Schedule` schedule on schedule.parent = `tabSales Invoice`.name and `tabSales Invoice`.is_return = 0 """ else: @@ -939,9 +936,7 @@ class GrossProfitGenerator(object): ) def get_bundle_item_details(self, item_code): - return frappe.db.get_value( - "Item", item_code, ["item_name", "description", "item_group", "brand"] - ) + return frappe.db.get_value("Item", item_code, ["item_name", "description", "item_group", "brand"]) def get_stock_ledger_entries(self, item_code, warehouse): if item_code and warehouse: diff --git a/erpnext/accounts/report/gross_profit/test_gross_profit.py b/erpnext/accounts/report/gross_profit/test_gross_profit.py index aa820aa4c73..8d15900741e 100644 --- a/erpnext/accounts/report/gross_profit/test_gross_profit.py +++ b/erpnext/accounts/report/gross_profit/test_gross_profit.py @@ -1,7 +1,7 @@ import frappe from frappe import qb from frappe.tests.utils import FrappeTestCase -from frappe.utils import add_days, flt, nowdate +from frappe.utils import flt, nowdate from erpnext.accounts.doctype.sales_invoice.sales_invoice import make_delivery_note from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice 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 230b18c293f..df3fc48f9e1 100644 --- a/erpnext/accounts/report/inactive_sales_items/inactive_sales_items.py +++ b/erpnext/accounts/report/inactive_sales_items/inactive_sales_items.py @@ -92,7 +92,6 @@ def get_data(filters): def get_sales_details(filters): - data = [] item_details_map = {} date_field = "s.transaction_date" if filters["based_on"] == "Sales Order" else "s.posting_date" @@ -116,7 +115,6 @@ def get_sales_details(filters): def get_territories(filters): - filter_dict = {} if filters.get("territory"): filter_dict.update({"name": filters["territory"]}) diff --git a/erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py b/erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py index b5dd66f75fe..2f87b5be836 100644 --- a/erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py +++ b/erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py @@ -140,7 +140,6 @@ def _execute(filters=None, additional_table_columns=None): def get_columns(additional_table_columns, filters): - columns = [] if filters.get("group_by") != ("Item"): @@ -194,7 +193,12 @@ def get_columns(additional_table_columns, filters): "options": "Supplier", "width": 120, }, - {"label": _("Supplier Name"), "fieldname": "supplier_name", "fieldtype": "Data", "width": 120}, + { + "label": _("Supplier Name"), + "fieldname": "supplier_name", + "fieldtype": "Data", + "width": 120, + }, ] ) @@ -326,14 +330,12 @@ def get_items(filters, additional_query_columns): `tabPurchase Invoice Item`.`purchase_receipt`, `tabPurchase Invoice Item`.`po_detail`, `tabPurchase Invoice Item`.`expense_account`, `tabPurchase Invoice Item`.`stock_qty`, `tabPurchase Invoice Item`.`stock_uom`, `tabPurchase Invoice Item`.`base_net_amount`, - `tabPurchase Invoice`.`supplier_name`, `tabPurchase Invoice`.`mode_of_payment` {0} + `tabPurchase Invoice`.`supplier_name`, `tabPurchase Invoice`.`mode_of_payment` {} from `tabPurchase Invoice`, `tabPurchase Invoice Item`, `tabItem` where `tabPurchase Invoice`.name = `tabPurchase Invoice Item`.`parent` and `tabItem`.name = `tabPurchase Invoice Item`.`item_code` and - `tabPurchase Invoice`.docstatus = 1 {1} - """.format( - additional_query_columns, conditions - ), + `tabPurchase Invoice`.docstatus = 1 {} + """.format(additional_query_columns, conditions), filters, as_dict=1, ) diff --git a/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py b/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py index 94457d59981..c7819731930 100644 --- a/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py +++ b/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py @@ -217,7 +217,12 @@ def get_columns(additional_table_columns, filters): "options": "Customer", "width": 120, }, - {"label": _("Customer Name"), "fieldname": "customer_name", "fieldtype": "Data", "width": 120}, + { + "label": _("Customer Name"), + "fieldname": "customer_name", + "fieldtype": "Data", + "width": 120, + }, ] ) @@ -365,9 +370,7 @@ def get_conditions(filters, additional_conditions=None): conditions += """and ifnull(`tabSales Invoice Item`.item_group, '') = %(item_group)s""" if not filters.get("group_by"): - conditions += ( - "ORDER BY `tabSales Invoice`.posting_date desc, `tabSales Invoice Item`.item_group desc" - ) + conditions += "ORDER BY `tabSales Invoice`.posting_date desc, `tabSales Invoice Item`.item_group desc" else: conditions += get_group_by_conditions(filters, "Sales Invoice") @@ -376,13 +379,13 @@ def get_conditions(filters, additional_conditions=None): def get_group_by_conditions(filters, doctype): if filters.get("group_by") == "Invoice": - return "ORDER BY `tab{0} Item`.parent desc".format(doctype) + return f"ORDER BY `tab{doctype} Item`.parent desc" elif filters.get("group_by") == "Item": - return "ORDER BY `tab{0} Item`.`item_code`".format(doctype) + return f"ORDER BY `tab{doctype} Item`.`item_code`" elif filters.get("group_by") == "Item Group": - return "ORDER BY `tab{0} Item`.{1}".format(doctype, frappe.scrub(filters.get("group_by"))) + return "ORDER BY `tab{} Item`.{}".format(doctype, frappe.scrub(filters.get("group_by"))) elif filters.get("group_by") in ("Customer", "Customer Group", "Territory", "Supplier"): - return "ORDER BY `tab{0}`.{1}".format(doctype, frappe.scrub(filters.get("group_by"))) + return "ORDER BY `tab{}`.{}".format(doctype, frappe.scrub(filters.get("group_by"))) def get_items(filters, additional_query_columns, additional_conditions=None): @@ -408,14 +411,12 @@ def get_items(filters, additional_query_columns, additional_conditions=None): `tabSales Invoice Item`.stock_qty, `tabSales Invoice Item`.stock_uom, `tabSales Invoice Item`.base_net_rate, `tabSales Invoice Item`.base_net_amount, `tabSales Invoice`.customer_name, `tabSales Invoice`.customer_group, `tabSales Invoice Item`.so_detail, - `tabSales Invoice`.update_stock, `tabSales Invoice Item`.uom, `tabSales Invoice Item`.qty {0} + `tabSales Invoice`.update_stock, `tabSales Invoice Item`.uom, `tabSales Invoice Item`.qty {} from `tabSales Invoice`, `tabSales Invoice Item`, `tabItem` where `tabSales Invoice`.name = `tabSales Invoice Item`.parent and `tabItem`.name = `tabSales Invoice Item`.`item_code` and - `tabSales Invoice`.docstatus = 1 {1} - """.format( - additional_query_columns, conditions - ), + `tabSales Invoice`.docstatus = 1 {} + """.format(additional_query_columns, conditions), filters, as_dict=1, ) # nosec @@ -445,20 +446,15 @@ def get_delivery_notes_against_sales_order(item_list): def get_grand_total(filters, doctype): - return frappe.db.sql( - """ SELECT - SUM(`tab{0}`.base_grand_total) - FROM `tab{0}` - WHERE `tab{0}`.docstatus = 1 + f""" SELECT + SUM(`tab{doctype}`.base_grand_total) + FROM `tab{doctype}` + WHERE `tab{doctype}`.docstatus = 1 and posting_date between %s and %s - """.format( - doctype - ), + """, (filters.get("from_date"), filters.get("to_date")), - )[0][ - 0 - ] # nosec + )[0][0] # nosec def get_tax_accounts( @@ -477,9 +473,7 @@ def get_tax_accounts( add_deduct_tax = "charge_type" tax_amount_precision = ( - get_field_precision( - frappe.get_meta(tax_doctype).get_field("tax_amount"), currency=company_currency - ) + get_field_precision(frappe.get_meta(tax_doctype).get_field("tax_amount"), currency=company_currency) or 2 ) @@ -489,11 +483,13 @@ def get_tax_accounts( conditions = "" if doctype == "Purchase Invoice": - conditions = " and category in ('Total', 'Valuation and Total') and base_tax_amount_after_discount_amount != 0" + conditions = ( + " and category in ('Total', 'Valuation and Total') and base_tax_amount_after_discount_amount != 0" + ) add_deduct_tax = "add_deduct_tax" tax_details = frappe.db.sql( - """ + f""" select name, parent, description, item_wise_tax_detail, account_head, charge_type, {add_deduct_tax}, base_tax_amount_after_discount_amount @@ -504,11 +500,9 @@ def get_tax_accounts( and parent in (%s) %s order by description - """.format( - add_deduct_tax=add_deduct_tax - ) + """ % (tax_doctype, "%s", ", ".join(["%s"] * len(invoice_item_row)), conditions), - tuple([doctype] + list(invoice_item_row)), + tuple([doctype, *list(invoice_item_row)]), ) account_doctype = frappe.qb.DocType("Account") @@ -516,13 +510,13 @@ def get_tax_accounts( query = ( frappe.qb.from_(account_doctype) .select(account_doctype.name) - .where((account_doctype.account_type == "Tax")) + .where(account_doctype.account_type == "Tax") ) tax_accounts = query.run() for ( - name, + _name, parent, description, item_wise_tax_detail, @@ -583,7 +577,9 @@ def get_tax_accounts( itemised_tax.setdefault(d.name, {})[description] = frappe._dict( { "tax_rate": "NA", - "tax_amount": flt((tax_amount * d.base_net_amount) / d.base_net_total, tax_amount_precision), + "tax_amount": flt( + (tax_amount * d.base_net_amount) / d.base_net_total, tax_amount_precision + ), } ) diff --git a/erpnext/accounts/report/payment_ledger/payment_ledger.py b/erpnext/accounts/report/payment_ledger/payment_ledger.py index 8875d2743fe..9852c6e7ab9 100644 --- a/erpnext/accounts/report/payment_ledger/payment_ledger.py +++ b/erpnext/accounts/report/payment_ledger/payment_ledger.py @@ -8,7 +8,7 @@ from frappe import _, qb from frappe.query_builder import Criterion -class PaymentLedger(object): +class PaymentLedger: def __init__(self, filters=None): self.filters = filters self.columns, self.data = [], [] diff --git a/erpnext/accounts/report/payment_ledger/test_payment_ledger.py b/erpnext/accounts/report/payment_ledger/test_payment_ledger.py index 5ae9b87cde9..c982f3166e7 100644 --- a/erpnext/accounts/report/payment_ledger/test_payment_ledger.py +++ b/erpnext/accounts/report/payment_ledger/test_payment_ledger.py @@ -1,5 +1,3 @@ -import unittest - import frappe from frappe import qb from frappe.tests.utils import FrappeTestCase @@ -57,7 +55,7 @@ class TestPaymentLedger(FrappeTestCase): income_account=self.income_account, warehouse=self.warehouse, ) - pe = get_payment_entry(sinv.doctype, sinv.name).save().submit() + get_payment_entry(sinv.doctype, sinv.name).save().submit() filters = frappe._dict({"company": self.company}) columns, data = execute(filters=filters) diff --git a/erpnext/accounts/report/payment_period_based_on_invoice_date/payment_period_based_on_invoice_date.py b/erpnext/accounts/report/payment_period_based_on_invoice_date/payment_period_based_on_invoice_date.py index eaeaa62d9a2..834eb5f519c 100644 --- a/erpnext/accounts/report/payment_period_based_on_invoice_date/payment_period_based_on_invoice_date.py +++ b/erpnext/accounts/report/payment_period_based_on_invoice_date/payment_period_based_on_invoice_date.py @@ -163,10 +163,8 @@ def get_entries(filters): """select voucher_type, voucher_no, party_type, party, posting_date, debit, credit, remarks, against_voucher from `tabGL Entry` - where company=%(company)s and voucher_type in ('Journal Entry', 'Payment Entry') and is_cancelled = 0 {0} - """.format( - get_conditions(filters) - ), + where company=%(company)s and voucher_type in ('Journal Entry', 'Payment Entry') and is_cancelled = 0 {} + """.format(get_conditions(filters)), filters, as_dict=1, ) @@ -175,7 +173,7 @@ def get_entries(filters): def get_invoice_posting_date_map(filters): invoice_details = {} dt = "Sales Invoice" if filters.get("payment_type") == _("Incoming") else "Purchase Invoice" - for t in frappe.db.sql("select name, posting_date, due_date from `tab{0}`".format(dt), as_dict=1): + for t in frappe.db.sql(f"select name, posting_date, due_date from `tab{dt}`", as_dict=1): invoice_details[t.name] = t return invoice_details diff --git a/erpnext/accounts/report/pos_register/pos_register.py b/erpnext/accounts/report/pos_register/pos_register.py index 3c687d0b48e..2248f6eca65 100644 --- a/erpnext/accounts/report/pos_register/pos_register.py +++ b/erpnext/accounts/report/pos_register/pos_register.py @@ -50,18 +50,20 @@ def get_pos_entries(filters, group_by_field): order_by = "p.posting_date" select_mop_field, from_sales_invoice_payment, group_by_mop_condition = "", "", "" if group_by_field == "mode_of_payment": - select_mop_field = ", sip.mode_of_payment, sip.base_amount - IF(sip.type='Cash', p.change_amount, 0) as paid_amount" + select_mop_field = ( + ", sip.mode_of_payment, sip.base_amount - IF(sip.type='Cash', p.change_amount, 0) as paid_amount" + ) from_sales_invoice_payment = ", `tabSales Invoice Payment` sip" group_by_mop_condition = "sip.parent = p.name AND ifnull(sip.base_amount - IF(sip.type='Cash', p.change_amount, 0), 0) != 0 AND" order_by += ", sip.mode_of_payment" elif group_by_field: - order_by += ", p.{}".format(group_by_field) + order_by += f", p.{group_by_field}" select_mop_field = ", p.base_paid_amount - p.change_amount as paid_amount " # nosemgrep return frappe.db.sql( - """ + f""" SELECT p.posting_date, p.name as pos_invoice, p.pos_profile, p.company, p.owner, p.customer, p.is_return, p.base_grand_total as grand_total {select_mop_field} @@ -73,13 +75,7 @@ def get_pos_entries(filters, group_by_field): {conditions} ORDER BY {order_by} - """.format( - select_mop_field=select_mop_field, - from_sales_invoice_payment=from_sales_invoice_payment, - group_by_mop_condition=group_by_mop_condition, - conditions=conditions, - order_by=order_by, - ), + """, filters, as_dict=1, ) @@ -132,9 +128,7 @@ def validate_filters(filters): def get_conditions(filters): - conditions = ( - "company = %(company)s AND posting_date >= %(from_date)s AND posting_date <= %(to_date)s" - ) + conditions = "company = %(company)s AND posting_date >= %(from_date)s AND posting_date <= %(to_date)s" if filters.get("pos_profile"): conditions += " AND pos_profile = %(pos_profile)s" diff --git a/erpnext/accounts/report/profit_and_loss_statement/profit_and_loss_statement.py b/erpnext/accounts/report/profit_and_loss_statement/profit_and_loss_statement.py index 002c05c9e3f..4571c4b26a0 100644 --- a/erpnext/accounts/report/profit_and_loss_statement/profit_and_loss_statement.py +++ b/erpnext/accounts/report/profit_and_loss_statement/profit_and_loss_statement.py @@ -57,9 +57,7 @@ def execute(filters=None): if net_profit_loss: data.append(net_profit_loss) - columns = get_columns( - filters.periodicity, period_list, filters.accumulated_values, filters.company - ) + columns = get_columns(filters.periodicity, period_list, filters.accumulated_values, filters.company) chart = get_chart_data(filters, columns, income, expense, net_profit_loss) diff --git a/erpnext/accounts/report/purchase_register/purchase_register.py b/erpnext/accounts/report/purchase_register/purchase_register.py index f745c87a00a..92d91a4cc46 100644 --- a/erpnext/accounts/report/purchase_register/purchase_register.py +++ b/erpnext/accounts/report/purchase_register/purchase_register.py @@ -316,16 +316,12 @@ def get_account_columns(invoice_list, include_payments): tuple([inv.name for inv in invoice_list]), ) - purchase_taxes_query = get_taxes_query( - invoice_list, "Purchase Taxes and Charges", "Purchase Invoice" - ) + purchase_taxes_query = get_taxes_query(invoice_list, "Purchase Taxes and Charges", "Purchase Invoice") purchase_tax_accounts = purchase_taxes_query.run(as_dict=True, pluck="account_head") tax_accounts = purchase_tax_accounts if include_payments: - advance_taxes_query = get_taxes_query( - invoice_list, "Advance Taxes and Charges", "Payment Entry" - ) + advance_taxes_query = get_taxes_query(invoice_list, "Advance Taxes and Charges", "Payment Entry") advance_tax_accounts = advance_taxes_query.run(as_dict=True, pluck="account_head") tax_accounts = set(tax_accounts + advance_tax_accounts) @@ -399,7 +395,7 @@ def get_invoices(filters, additional_query_columns): pi.outstanding_amount, pi.mode_of_payment, ) - .where((pi.docstatus == 1)) + .where(pi.docstatus == 1) .orderby(pi.posting_date, pi.name, order=Order.desc) ) @@ -481,9 +477,7 @@ def get_internal_invoice_map(invoice_list): return internal_invoice_map -def get_invoice_tax_map( - invoice_list, invoice_expense_map, expense_accounts, include_payments=False -): +def get_invoice_tax_map(invoice_list, invoice_expense_map, expense_accounts, include_payments=False): tax_details = frappe.db.sql( """ select parent, account_head, case add_deduct_tax when "Add" then sum(base_tax_amount_after_discount_amount) @@ -548,9 +542,7 @@ def get_invoice_po_pr_map(invoice_list): invoice_po_pr_map.setdefault(d.parent, frappe._dict()).setdefault("purchase_receipt", pr_list) if d.project: - invoice_po_pr_map.setdefault(d.parent, frappe._dict()).setdefault("project", []).append( - d.project - ) + invoice_po_pr_map.setdefault(d.parent, frappe._dict()).setdefault("project", []).append(d.project) return invoice_po_pr_map diff --git a/erpnext/accounts/report/purchase_register/test_purchase_register.py b/erpnext/accounts/report/purchase_register/test_purchase_register.py index 6903662e687..a7a5c07152b 100644 --- a/erpnext/accounts/report/purchase_register/test_purchase_register.py +++ b/erpnext/accounts/report/purchase_register/test_purchase_register.py @@ -3,7 +3,7 @@ import frappe from frappe.tests.utils import FrappeTestCase -from frappe.utils import add_months, getdate, today +from frappe.utils import add_months, today from erpnext.accounts.report.purchase_register.purchase_register import execute @@ -13,9 +13,7 @@ class TestPurchaseRegister(FrappeTestCase): frappe.db.sql("delete from `tabPurchase Invoice` where company='_Test Company 6'") frappe.db.sql("delete from `tabGL Entry` where company='_Test Company 6'") - filters = frappe._dict( - company="_Test Company 6", from_date=add_months(today(), -1), to_date=today() - ) + filters = frappe._dict(company="_Test Company 6", from_date=add_months(today(), -1), to_date=today()) pi = make_purchase_invoice() @@ -40,7 +38,7 @@ class TestPurchaseRegister(FrappeTestCase): supplier="_Test Supplier", ) - pi = make_purchase_invoice() + make_purchase_invoice() pe = make_payment_entry() report_results = execute(filters) @@ -58,7 +56,7 @@ def make_purchase_invoice(): from erpnext.accounts.doctype.cost_center.test_cost_center import create_cost_center from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse - gst_acc = create_account( + create_account( account_name="GST", account_type="Tax", parent_account="Duties and Taxes - _TC6", diff --git a/erpnext/accounts/report/sales_payment_summary/sales_payment_summary.py b/erpnext/accounts/report/sales_payment_summary/sales_payment_summary.py index 057721479e3..7c2bf7ee18c 100644 --- a/erpnext/accounts/report/sales_payment_summary/sales_payment_summary.py +++ b/erpnext/accounts/report/sales_payment_summary/sales_payment_summary.py @@ -144,9 +144,9 @@ def get_pos_invoice_data(filters): "ON (" "t1.parent = a.name and t1.base_total = a.base_total) " "WHERE a.docstatus = 1" - " AND {conditions} " + f" AND {conditions} " "GROUP BY " - "owner, posting_date, warehouse".format(conditions=conditions), + "owner, posting_date, warehouse", filters, as_dict=1, ) @@ -156,7 +156,7 @@ def get_pos_invoice_data(filters): def get_sales_invoice_data(filters): conditions = get_conditions(filters) return frappe.db.sql( - """ + f""" select a.posting_date, a.owner, sum(a.net_total) as "net_total", @@ -168,9 +168,7 @@ def get_sales_invoice_data(filters): and {conditions} group by a.owner, a.posting_date - """.format( - conditions=conditions - ), + """, filters, as_dict=1, ) @@ -182,7 +180,7 @@ def get_mode_of_payments(filters): invoice_list_names = ",".join("'" + invoice["name"] + "'" for invoice in invoice_list) if invoice_list: inv_mop = frappe.db.sql( - """select a.owner,a.posting_date, ifnull(b.mode_of_payment, '') as mode_of_payment + f"""select a.owner,a.posting_date, ifnull(b.mode_of_payment, '') as mode_of_payment from `tabSales Invoice` a, `tabSales Invoice Payment` b where a.name = b.parent and a.docstatus = 1 @@ -202,9 +200,7 @@ def get_mode_of_payments(filters): and a.docstatus = 1 and b.reference_type = 'Sales Invoice' and b.reference_name in ({invoice_list_names}) - """.format( - invoice_list_names=invoice_list_names - ), + """, as_dict=1, ) for d in inv_mop: @@ -215,11 +211,9 @@ def get_mode_of_payments(filters): def get_invoices(filters): conditions = get_conditions(filters) return frappe.db.sql( - """select a.name + f"""select a.name from `tabSales Invoice` a - where a.docstatus = 1 and {conditions}""".format( - conditions=conditions - ), + where a.docstatus = 1 and {conditions}""", filters, as_dict=1, ) @@ -231,7 +225,7 @@ def get_mode_of_payment_details(filters): invoice_list_names = ",".join("'" + invoice["name"] + "'" for invoice in invoice_list) if invoice_list: inv_mop_detail = frappe.db.sql( - """ + f""" select t.owner, t.posting_date, t.mode_of_payment, @@ -264,23 +258,19 @@ def get_mode_of_payment_details(filters): group by a.owner, a.posting_date, mode_of_payment ) t group by t.owner, t.posting_date, t.mode_of_payment - """.format( - invoice_list_names=invoice_list_names - ), + """, as_dict=1, ) inv_change_amount = frappe.db.sql( - """select a.owner, a.posting_date, + f"""select a.owner, a.posting_date, ifnull(b.mode_of_payment, '') as mode_of_payment, sum(a.base_change_amount) as change_amount from `tabSales Invoice` a, `tabSales Invoice Payment` b where a.name = b.parent and a.name in ({invoice_list_names}) and b.type = 'Cash' and a.base_change_amount > 0 - group by a.owner, a.posting_date, mode_of_payment""".format( - invoice_list_names=invoice_list_names - ), + group by a.owner, a.posting_date, mode_of_payment""", as_dict=1, ) diff --git a/erpnext/accounts/report/sales_payment_summary/test_sales_payment_summary.py b/erpnext/accounts/report/sales_payment_summary/test_sales_payment_summary.py index 3ad0ff2ce26..3be96c6de93 100644 --- a/erpnext/accounts/report/sales_payment_summary/test_sales_payment_summary.py +++ b/erpnext/accounts/report/sales_payment_summary/test_sales_payment_summary.py @@ -33,7 +33,7 @@ class TestSalesPaymentSummary(unittest.TestCase): def test_get_mode_of_payments(self): filters = get_filters() - for dummy in range(2): + for _dummy in range(2): si = create_sales_invoice_record() si.insert() si.submit() @@ -53,8 +53,8 @@ class TestSalesPaymentSummary(unittest.TestCase): pe.submit() mop = get_mode_of_payments(filters) - self.assertTrue("Credit Card" in list(mop.values())[0]) - self.assertTrue("Cash" in list(mop.values())[0]) + self.assertTrue("Credit Card" in next(iter(mop.values()))) + self.assertTrue("Cash" in next(iter(mop.values()))) # Cancel all Cash payment entry and check if this mode of payment is still fetched. payment_entries = frappe.get_all( @@ -67,13 +67,13 @@ class TestSalesPaymentSummary(unittest.TestCase): pe.cancel() mop = get_mode_of_payments(filters) - self.assertTrue("Credit Card" in list(mop.values())[0]) - self.assertTrue("Cash" not in list(mop.values())[0]) + self.assertTrue("Credit Card" in next(iter(mop.values()))) + self.assertTrue("Cash" not in next(iter(mop.values()))) def test_get_mode_of_payments_details(self): filters = get_filters() - for dummy in range(2): + for _dummy in range(2): si = create_sales_invoice_record() si.insert() si.submit() @@ -94,7 +94,7 @@ class TestSalesPaymentSummary(unittest.TestCase): mopd = get_mode_of_payment_details(filters) - mopd_values = list(mopd.values())[0] + mopd_values = next(iter(mopd.values())) for mopd_value in mopd_values: if mopd_value[0] == "Credit Card": cc_init_amount = mopd_value[1] @@ -110,7 +110,7 @@ class TestSalesPaymentSummary(unittest.TestCase): pe.cancel() mopd = get_mode_of_payment_details(filters) - mopd_values = list(mopd.values())[0] + mopd_values = next(iter(mopd.values())) for mopd_value in mopd_values: if mopd_value[0] == "Credit Card": cc_final_amount = mopd_value[1] diff --git a/erpnext/accounts/report/sales_register/sales_register.py b/erpnext/accounts/report/sales_register/sales_register.py index 1cb72f8d2d6..3e7ac1a818d 100644 --- a/erpnext/accounts/report/sales_register/sales_register.py +++ b/erpnext/accounts/report/sales_register/sales_register.py @@ -129,7 +129,8 @@ def _execute(filters, additional_table_columns=None): if tax_acc not in income_accounts: tax_amount_precision = ( get_field_precision( - frappe.get_meta("Sales Taxes and Charges").get_field("tax_amount"), currency=company_currency + frappe.get_meta("Sales Taxes and Charges").get_field("tax_amount"), + currency=company_currency, ) or 2 ) @@ -357,9 +358,7 @@ def get_account_columns(invoice_list, include_payments): tax_accounts = sales_tax_accounts if include_payments: - advance_taxes_query = get_taxes_query( - invoice_list, "Advance Taxes and Charges", "Payment Entry" - ) + advance_taxes_query = get_taxes_query(invoice_list, "Advance Taxes and Charges", "Payment Entry") advance_tax_accounts = advance_taxes_query.run(as_dict=True, pluck="account_head") tax_accounts = set(tax_accounts + advance_tax_accounts) @@ -438,7 +437,7 @@ def get_invoices(filters, additional_query_columns): si.represents_company, si.company, ) - .where((si.docstatus == 1)) + .where(si.docstatus == 1) .orderby(si.posting_date, si.name, order=Order.desc) ) diff --git a/erpnext/accounts/report/share_balance/share_balance.py b/erpnext/accounts/report/share_balance/share_balance.py index d02f53b0d2b..1d02a996b76 100644 --- a/erpnext/accounts/report/share_balance/share_balance.py +++ b/erpnext/accounts/report/share_balance/share_balance.py @@ -15,7 +15,7 @@ def execute(filters=None): columns = get_columns(filters) - date = filters.get("date") + filters.get("date") data = [] diff --git a/erpnext/accounts/report/share_ledger/share_ledger.py b/erpnext/accounts/report/share_ledger/share_ledger.py index 629528e5cc7..ed65687a2ed 100644 --- a/erpnext/accounts/report/share_ledger/share_ledger.py +++ b/erpnext/accounts/report/share_ledger/share_ledger.py @@ -26,9 +26,9 @@ def execute(filters=None): for transfer in transfers: if transfer.transfer_type == "Transfer": if transfer.from_shareholder == filters.get("shareholder"): - transfer.transfer_type += " to {}".format(transfer.to_shareholder) + transfer.transfer_type += f" to {transfer.to_shareholder}" else: - transfer.transfer_type += " from {}".format(transfer.from_shareholder) + transfer.transfer_type += f" from {transfer.from_shareholder}" row = [ filters.get("shareholder"), transfer.date, @@ -66,13 +66,11 @@ def get_all_transfers(date, shareholder): # if company: # condition = 'AND company = %(company)s ' return frappe.db.sql( - """SELECT * FROM `tabShare Transfer` + f"""SELECT * FROM `tabShare Transfer` WHERE ((DATE(date) <= %(date)s AND from_shareholder = %(shareholder)s {condition}) OR (DATE(date) <= %(date)s AND to_shareholder = %(shareholder)s {condition})) AND docstatus = 1 - ORDER BY date""".format( - condition=condition - ), + ORDER BY date""", {"date": date, "shareholder": shareholder}, as_dict=1, ) diff --git a/erpnext/accounts/report/tax_detail/tax_detail.py b/erpnext/accounts/report/tax_detail/tax_detail.py index ba733c2d185..47b92dd13b0 100644 --- a/erpnext/accounts/report/tax_detail/tax_detail.py +++ b/erpnext/accounts/report/tax_detail/tax_detail.py @@ -34,7 +34,7 @@ def execute(filters=None): fieldstr = get_fieldstr(fieldlist) gl_entries = frappe.db.sql( - """ + f""" select {fieldstr} from `tabGL Entry` ge inner join `tabAccount` a on @@ -52,9 +52,7 @@ def execute(filters=None): ge.posting_date>=%(from_date)s and ge.posting_date<=%(to_date)s order by ge.posting_date, ge.voucher_no - """.format( - fieldstr=fieldstr - ), + """, filters, as_dict=1, ) @@ -94,7 +92,9 @@ def run_report(report_name, data): report[section_name]["subtotal"] += row["amount"] if component["type"] == "section": if component_name == section_name: - frappe.throw(_("A report component cannot refer to its parent section") + ": " + section_name) + frappe.throw( + _("A report component cannot refer to its parent section") + ": " + section_name + ) try: report[section_name]["rows"] += report[component_name]["rows"] report[section_name]["subtotal"] += report[component_name]["subtotal"] diff --git a/erpnext/accounts/report/tax_detail/test_tax_detail.py b/erpnext/accounts/report/tax_detail/test_tax_detail.py index 869f2450218..55ae32a2c6a 100644 --- a/erpnext/accounts/report/tax_detail/test_tax_detail.py +++ b/erpnext/accounts/report/tax_detail/test_tax_detail.py @@ -21,7 +21,7 @@ class TestTaxDetail(unittest.TestCase): from erpnext.accounts.utils import FiscalYearError, get_fiscal_year datapath, _ = os.path.splitext(os.path.realpath(__file__)) - with open(datapath + ".json", "r") as fp: + with open(datapath + ".json") as fp: docs = json.load(fp) now = getdate() @@ -45,8 +45,9 @@ class TestTaxDetail(unittest.TestCase): "year": "_Test Fiscal", "year_end_date": get_year_ending(now), "year_start_date": get_year_start(now), - } - ] + docs + }, + *docs, + ] docs = [ { @@ -56,8 +57,9 @@ class TestTaxDetail(unittest.TestCase): "default_currency": "GBP", "doctype": "Company", "name": "_T", - } - ] + docs + }, + *docs, + ] for doc in docs: try: @@ -109,9 +111,14 @@ class TestTaxDetail(unittest.TestCase): "Box5": {"Box3": {"type": "section"}, "Box4": {"type": "section"}}, "Box6": {"Filter0": {"type": "filter", "filters": {"3": "!=Tax", "4": "Sales"}}}, "Box7": {"Filter0": {"type": "filter", "filters": {"2": "Expense", "3": "!=Tax"}}}, - "Box8": {"Filter0": {"type": "filter", "filters": {"3": "!=Tax", "4": "Sales", "12": "EU"}}}, + "Box8": { + "Filter0": {"type": "filter", "filters": {"3": "!=Tax", "4": "Sales", "12": "EU"}} + }, "Box9": { - "Filter0": {"type": "filter", "filters": {"2": "Expense", "3": "!=Tax", "12": "EU"}} + "Filter0": { + "type": "filter", + "filters": {"2": "Expense", "3": "!=Tax", "12": "EU"}, + } }, }, "show_detail": 1, diff --git a/erpnext/accounts/report/tds_computation_summary/tds_computation_summary.py b/erpnext/accounts/report/tds_computation_summary/tds_computation_summary.py index 82f97f18941..d876d6d14d2 100644 --- a/erpnext/accounts/report/tds_computation_summary/tds_computation_summary.py +++ b/erpnext/accounts/report/tds_computation_summary/tds_computation_summary.py @@ -67,13 +67,13 @@ def group_by_party_and_category(data, filters): }, ) - party_category_wise_map.get((row.get("party"), row.get("section_code")))[ - "total_amount" - ] += row.get("total_amount", 0.0) + party_category_wise_map.get((row.get("party"), row.get("section_code")))["total_amount"] += row.get( + "total_amount", 0.0 + ) - party_category_wise_map.get((row.get("party"), row.get("section_code")))[ - "tax_amount" - ] += row.get("tax_amount", 0.0) + party_category_wise_map.get((row.get("party"), row.get("section_code")))["tax_amount"] += row.get( + "tax_amount", 0.0 + ) final_result = get_final_result(party_category_wise_map) @@ -82,7 +82,7 @@ def group_by_party_and_category(data, filters): def get_final_result(party_category_wise_map): out = [] - for key, value in party_category_wise_map.items(): + for _key, value in party_category_wise_map.items(): out.append(value) return out diff --git a/erpnext/accounts/report/tds_payable_monthly/tds_payable_monthly.py b/erpnext/accounts/report/tds_payable_monthly/tds_payable_monthly.py index c0963150b1f..fc5e8452e1d 100644 --- a/erpnext/accounts/report/tds_payable_monthly/tds_payable_monthly.py +++ b/erpnext/accounts/report/tds_payable_monthly/tds_payable_monthly.py @@ -37,9 +37,7 @@ def validate_filters(filters): frappe.throw(_("From Date must be before To Date")) -def get_result( - filters, tds_docs, tds_accounts, tax_category_map, journal_entry_party_map, net_total_map -): +def get_result(filters, tds_docs, tds_accounts, tax_category_map, journal_entry_party_map, net_total_map): party_map = get_party_pan_map(filters.get("party_type")) tax_rate_map = get_tax_rate_map(filters) gle_map = get_gle_map(tds_docs) @@ -92,9 +90,9 @@ def get_result( party_type = "customer_type" row = { - "pan" - if frappe.db.has_column(filters.party_type, "pan") - else "tax_id": party_map.get(party, {}).get("pan"), + "pan" if frappe.db.has_column(filters.party_type, "pan") else "tax_id": party_map.get( + party, {} + ).get("pan"), "party": party_map.get(party, {}).get("name"), } @@ -157,7 +155,7 @@ def get_gle_map(documents): ) for d in gle: - if not d.voucher_no in gle_map: + if d.voucher_no not in gle_map: gle_map[d.voucher_no] = [d] else: gle_map[d.voucher_no].append(d) @@ -281,7 +279,7 @@ def get_tds_docs(filters): journal_entries = [] tax_category_map = frappe._dict() net_total_map = frappe._dict() - or_filters = frappe._dict() + frappe._dict() journal_entry_party_map = frappe._dict() bank_accounts = frappe.get_all("Account", {"is_group": 0, "account_type": "Bank"}, pluck="name") @@ -344,7 +342,7 @@ def get_tds_docs_query(filters, bank_accounts, tds_accounts): query = ( frappe.qb.from_(gle) .select("voucher_no", "voucher_type", "against", "party") - .where((gle.is_cancelled == 0)) + .where(gle.is_cancelled == 0) ) if filters.get("from_date"): diff --git a/erpnext/accounts/report/trial_balance/trial_balance.py b/erpnext/accounts/report/trial_balance/trial_balance.py index 8b7f0bbc006..e65f479f056 100644 --- a/erpnext/accounts/report/trial_balance/trial_balance.py +++ b/erpnext/accounts/report/trial_balance/trial_balance.py @@ -120,9 +120,7 @@ def get_data(filters): ignore_opening_entries=True, ) - calculate_values( - accounts, gl_entries_by_account, opening_balances, filters.get("show_net_values") - ) + calculate_values(accounts, gl_entries_by_account, opening_balances, filters.get("show_net_values")) accumulate_values_into_parents(accounts, accounts_by_name) data = prepare_data(accounts, filters, parent_children_map, company_currency) @@ -170,9 +168,7 @@ def get_rootwise_opening_balances(filters, report_type): ) # Report getting generate from the mid of a fiscal year - if getdate(last_period_closing_voucher[0].posting_date) < getdate( - add_days(filters.from_date, -1) - ): + if getdate(last_period_closing_voucher[0].posting_date) < getdate(add_days(filters.from_date, -1)): start_date = add_days(last_period_closing_voucher[0].posting_date, 1) gle += get_opening_balance( "GL Entry", filters, report_type, accounting_dimensions, start_date=start_date @@ -253,9 +249,7 @@ def get_opening_balance( if doctype == "Account Closing Balance": opening_balance = opening_balance.where(closing_balance.is_period_closing_voucher_entry == 0) else: - opening_balance = opening_balance.where( - closing_balance.voucher_type != "Period Closing Voucher" - ) + opening_balance = opening_balance.where(closing_balance.voucher_type != "Period Closing Voucher") if filters.cost_center: lft, rgt = frappe.db.get_value("Cost Center", filters.cost_center, ["lft", "rgt"]) @@ -388,7 +382,7 @@ def prepare_data(accounts, filters, parent_children_map, company_currency): "to_date": filters.to_date, "currency": company_currency, "account_name": ( - "{} - {}".format(d.account_number, d.account_name) if d.account_number else d.account_name + f"{d.account_number} - {d.account_name}" if d.account_number else d.account_name ), } diff --git a/erpnext/accounts/report/trial_balance_for_party/trial_balance_for_party.py b/erpnext/accounts/report/trial_balance_for_party/trial_balance_for_party.py index ee223484d47..dd1a12514e2 100644 --- a/erpnext/accounts/report/trial_balance_for_party/trial_balance_for_party.py +++ b/erpnext/accounts/report/trial_balance_for_party/trial_balance_for_party.py @@ -22,7 +22,7 @@ def execute(filters=None): def get_data(filters, show_party_name): if filters.get("party_type") in ("Customer", "Supplier", "Employee", "Member"): - party_name_field = "{0}_name".format(frappe.scrub(filters.get("party_type"))) + party_name_field = "{}_name".format(frappe.scrub(filters.get("party_type"))) elif filters.get("party_type") == "Shareholder": party_name_field = "title" else: @@ -65,9 +65,7 @@ def get_data(filters, show_party_name): row.update({"debit": debit, "credit": credit}) # closing - closing_debit, closing_credit = toggle_debit_credit( - opening_debit + debit, opening_credit + credit - ) + closing_debit, closing_credit = toggle_debit_credit(opening_debit + debit, opening_credit + credit) row.update({"closing_debit": closing_debit, "closing_credit": closing_credit}) # totals @@ -92,13 +90,12 @@ def get_data(filters, show_party_name): def get_opening_balances(filters): - account_filter = "" if filters.get("account"): account_filter = "and account = %s" % (frappe.db.escape(filters.get("account"))) gle = frappe.db.sql( - """ + f""" select party, sum(debit) as opening_debit, sum(credit) as opening_credit from `tabGL Entry` where company=%(company)s @@ -106,9 +103,7 @@ def get_opening_balances(filters): and ifnull(party_type, '') = %(party_type)s and ifnull(party, '') != '' and (posting_date < %(from_date)s or (ifnull(is_opening, 'No') = 'Yes' and posting_date <= %(to_date)s)) {account_filter} - group by party""".format( - account_filter=account_filter - ), + group by party""", { "company": filters.company, "from_date": filters.from_date, @@ -127,13 +122,12 @@ def get_opening_balances(filters): def get_balances_within_period(filters): - account_filter = "" if filters.get("account"): account_filter = "and account = %s" % (frappe.db.escape(filters.get("account"))) gle = frappe.db.sql( - """ + f""" select party, sum(debit) as debit, sum(credit) as credit from `tabGL Entry` where company=%(company)s @@ -142,9 +136,7 @@ def get_balances_within_period(filters): and posting_date >= %(from_date)s and posting_date <= %(to_date)s and ifnull(is_opening, 'No') = 'No' {account_filter} - group by party""".format( - account_filter=account_filter - ), + group by party""", { "company": filters.company, "from_date": filters.from_date, diff --git a/erpnext/accounts/report/utils.py b/erpnext/accounts/report/utils.py index 795cab900c1..3fa62b583a1 100644 --- a/erpnext/accounts/report/utils.py +++ b/erpnext/accounts/report/utils.py @@ -78,10 +78,10 @@ def get_rate_as_at(date, from_currency, to_currency): :return: Retrieved exchange rate """ - rate = __exchange_rates.get("{0}-{1}@{2}".format(from_currency, to_currency, date)) + rate = __exchange_rates.get(f"{from_currency}-{to_currency}@{date}") if not rate: rate = get_exchange_rate(from_currency, to_currency, date) or 1 - __exchange_rates["{0}-{1}@{2}".format(from_currency, to_currency, date)] = rate + __exchange_rates[f"{from_currency}-{to_currency}@{date}"] = rate return rate @@ -136,9 +136,7 @@ def get_appropriate_company(filters): @frappe.whitelist() -def get_invoiced_item_gross_margin( - sales_invoice=None, item_code=None, company=None, with_item_data=False -): +def get_invoiced_item_gross_margin(sales_invoice=None, item_code=None, company=None, with_item_data=False): from erpnext.accounts.report.gross_profit.gross_profit import GrossProfitGenerator sales_invoice = sales_invoice or frappe.form_dict.get("sales_invoice") diff --git a/erpnext/accounts/report/voucher_wise_balance/voucher_wise_balance.py b/erpnext/accounts/report/voucher_wise_balance/voucher_wise_balance.py index bd9e9fccadc..1918165c6db 100644 --- a/erpnext/accounts/report/voucher_wise_balance/voucher_wise_balance.py +++ b/erpnext/accounts/report/voucher_wise_balance/voucher_wise_balance.py @@ -43,9 +43,7 @@ def get_data(filters): gle = frappe.qb.DocType("GL Entry") query = ( frappe.qb.from_(gle) - .select( - gle.voucher_type, gle.voucher_no, Sum(gle.debit).as_("debit"), Sum(gle.credit).as_("credit") - ) + .select(gle.voucher_type, gle.voucher_no, Sum(gle.debit).as_("debit"), Sum(gle.credit).as_("credit")) .where(gle.is_cancelled == 0) .groupby(gle.voucher_no) ) diff --git a/erpnext/accounts/test/test_reports.py b/erpnext/accounts/test/test_reports.py index 3f06c30adb6..9496a1aa664 100644 --- a/erpnext/accounts/test/test_reports.py +++ b/erpnext/accounts/test/test_reports.py @@ -1,5 +1,4 @@ import unittest -from typing import List, Tuple from erpnext.tests.utils import ReportFilters, ReportName, execute_script_report @@ -12,7 +11,7 @@ DEFAULT_FILTERS = { } -REPORT_FILTER_TEST_CASES: List[Tuple[ReportName, ReportFilters]] = [ +REPORT_FILTER_TEST_CASES: list[tuple[ReportName, ReportFilters]] = [ ("General Ledger", {"group_by": "Group by Voucher (Consolidated)"}), ("General Ledger", {"group_by": "Group by Voucher (Consolidated)", "include_dimensions": 1}), ("Accounts Payable", {"range1": 30, "range2": 60, "range3": 90, "range4": 120}), diff --git a/erpnext/accounts/test/test_utils.py b/erpnext/accounts/test/test_utils.py index 660cb62d2c5..59cbc11794f 100644 --- a/erpnext/accounts/test/test_utils.py +++ b/erpnext/accounts/test/test_utils.py @@ -19,7 +19,7 @@ from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry class TestUtils(unittest.TestCase): @classmethod def setUpClass(cls): - super(TestUtils, cls).setUpClass() + super().setUpClass() make_test_objects("Address", ADDRESS_RECORDS) @classmethod @@ -35,7 +35,6 @@ class TestUtils(unittest.TestCase): self.assertEqual(address, "_Test Shipping Address 2 Title-Shipping") def test_get_voucher_wise_gl_entry(self): - pr = make_purchase_receipt( item_code="_Test Item", posting_date="2021-02-01", @@ -143,12 +142,8 @@ class TestUtils(unittest.TestCase): frappe.db.set_default("supp_master_name", "Auto Name") # Configure Autoname in Supplier DocType - make_property_setter( - "Supplier", None, "naming_rule", "Expression", "Data", for_doctype="Doctype" - ) - make_property_setter( - "Supplier", None, "autoname", "SUP-.FY.-.#####", "Data", for_doctype="Doctype" - ) + make_property_setter("Supplier", None, "naming_rule", "Expression", "Data", for_doctype="Doctype") + make_property_setter("Supplier", None, "autoname", "SUP-.FY.-.#####", "Data", for_doctype="Doctype") fiscal_year = get_fiscal_year(nowdate())[0] @@ -170,9 +165,7 @@ ADDRESS_RECORDS = [ "address_title": "_Test Billing Address Title", "city": "Lagos", "country": "Nigeria", - "links": [ - {"link_doctype": "Customer", "link_name": "_Test Customer 2", "doctype": "Dynamic Link"} - ], + "links": [{"link_doctype": "Customer", "link_name": "_Test Customer 2", "doctype": "Dynamic Link"}], }, { "doctype": "Address", @@ -181,9 +174,7 @@ ADDRESS_RECORDS = [ "address_title": "_Test Shipping Address 1 Title", "city": "Lagos", "country": "Nigeria", - "links": [ - {"link_doctype": "Customer", "link_name": "_Test Customer 2", "doctype": "Dynamic Link"} - ], + "links": [{"link_doctype": "Customer", "link_name": "_Test Customer 2", "doctype": "Dynamic Link"}], }, { "doctype": "Address", @@ -193,9 +184,7 @@ ADDRESS_RECORDS = [ "city": "Lagos", "country": "Nigeria", "is_shipping_address": "1", - "links": [ - {"link_doctype": "Customer", "link_name": "_Test Customer 2", "doctype": "Dynamic Link"} - ], + "links": [{"link_doctype": "Customer", "link_name": "_Test Customer 2", "doctype": "Dynamic Link"}], }, { "doctype": "Address", @@ -205,8 +194,6 @@ ADDRESS_RECORDS = [ "city": "Lagos", "country": "Nigeria", "is_shipping_address": "1", - "links": [ - {"link_doctype": "Customer", "link_name": "_Test Customer 1", "doctype": "Dynamic Link"} - ], + "links": [{"link_doctype": "Customer", "link_name": "_Test Customer 1", "doctype": "Dynamic Link"}], }, ] diff --git a/erpnext/accounts/utils.py b/erpnext/accounts/utils.py index a32c25fbb70..d966074b2ae 100644 --- a/erpnext/accounts/utils.py +++ b/erpnext/accounts/utils.py @@ -3,7 +3,7 @@ from json import loads -from typing import TYPE_CHECKING, List, Optional, Tuple +from typing import TYPE_CHECKING, Optional import frappe import frappe.defaults @@ -31,7 +31,7 @@ from pypika.terms import ExistsCriterion import erpnext # imported to enable erpnext.accounts.utils.get_account_currency -from erpnext.accounts.doctype.account.account import get_account_currency # noqa +from erpnext.accounts.doctype.account.account import get_account_currency from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import get_dimensions from erpnext.stock import get_warehouse_account_map from erpnext.stock.utils import get_stock_value_on @@ -80,9 +80,7 @@ def get_fiscal_years( FY = DocType("Fiscal Year") query = ( - frappe.qb.from_(FY) - .select(FY.name, FY.year_start_date, FY.year_end_date) - .where(FY.disabled == 0) + frappe.qb.from_(FY).select(FY.name, FY.year_start_date, FY.year_end_date).where(FY.disabled == 0) ) if fiscal_year: @@ -129,9 +127,7 @@ def get_fiscal_years( else: return ((fy.name, fy.year_start_date, fy.year_end_date),) - error_msg = _("""{0} {1} is not in any active Fiscal Year""").format( - label, formatdate(transaction_date) - ) + error_msg = _("""{0} {1} is not in any active Fiscal Year""").format(label, formatdate(transaction_date)) if company: error_msg = _("""{0} for {1}""").format(error_msg, frappe.bold(company)) @@ -207,12 +203,12 @@ def get_balance_on( acc = frappe.get_doc("Account", account) try: - year_start_date = get_fiscal_year(date, company=company, verbose=0)[1] + get_fiscal_year(date, company=company, verbose=0)[1] except FiscalYearError: if getdate(date) > getdate(nowdate()): # if fiscal year not found and the date is greater than today # get fiscal year for today's date and its corresponding year start date - year_start_date = get_fiscal_year(nowdate(), verbose=1)[1] + get_fiscal_year(nowdate(), verbose=1)[1] else: # this indicates that it is a date older than any existing fiscal year. # hence, assuming balance as 0.0 @@ -227,29 +223,26 @@ def get_balance_on( cc = frappe.get_doc("Cost Center", cost_center) if cc.is_group: cond.append( - """ exists ( + f""" exists ( select 1 from `tabCost Center` cc where cc.name = gle.cost_center - and cc.lft >= %s and cc.rgt <= %s + and cc.lft >= {cc.lft} and cc.rgt <= {cc.rgt} )""" - % (cc.lft, cc.rgt) ) else: - cond.append("""gle.cost_center = %s """ % (frappe.db.escape(cost_center, percent=False),)) + cond.append(f"""gle.cost_center = {frappe.db.escape(cost_center, percent=False)} """) if account: - if not (frappe.flags.ignore_account_permission or ignore_account_permission): acc.check_permission("read") # different filter for group and ledger - improved performance if acc.is_group: cond.append( - """exists ( + f"""exists ( select name from `tabAccount` ac where ac.name = gle.account - and ac.lft >= %s and ac.rgt <= %s + and ac.lft >= {acc.lft} and ac.rgt <= {acc.rgt} )""" - % (acc.lft, acc.rgt) ) # If group and currency same as company, @@ -257,12 +250,11 @@ def get_balance_on( if acc.account_currency == frappe.get_cached_value("Company", acc.company, "default_currency"): in_account_currency = False else: - cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),)) + cond.append(f"""gle.account = {frappe.db.escape(account, percent=False)} """) if party_type and party: cond.append( - """gle.party_type = %s and gle.party = %s """ - % (frappe.db.escape(party_type), frappe.db.escape(party, percent=False)) + f"""gle.party_type = {frappe.db.escape(party_type)} and gle.party = {frappe.db.escape(party, percent=False)} """ ) if company: @@ -275,11 +267,9 @@ def get_balance_on( select_field = "sum(debit) - sum(credit)" bal = frappe.db.sql( """ - SELECT {0} + SELECT {} FROM `tabGL Entry` gle - WHERE {1}""".format( - select_field, " and ".join(cond) - ) + WHERE {}""".format(select_field, " and ".join(cond)) )[0][0] # if bal is None, return 0 @@ -314,30 +304,25 @@ def get_count_on(account, fieldname, date): # for pl accounts, get balance within a fiscal year if acc.report_type == "Profit and Loss": - cond.append( - "posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date - ) + cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date) # different filter for group and ledger - improved performance if acc.is_group: cond.append( - """exists ( + f"""exists ( select name from `tabAccount` ac where ac.name = gle.account - and ac.lft >= %s and ac.rgt <= %s + and ac.lft >= {acc.lft} and ac.rgt <= {acc.rgt} )""" - % (acc.lft, acc.rgt) ) else: - cond.append("""gle.account = %s """ % (frappe.db.escape(account, percent=False),)) + cond.append(f"""gle.account = {frappe.db.escape(account, percent=False)} """) entries = frappe.db.sql( """ SELECT name, posting_date, account, party_type, party,debit,credit, voucher_type, voucher_no, against_voucher_type, against_voucher FROM `tabGL Entry` gle - WHERE {0}""".format( - " and ".join(cond) - ), + WHERE {}""".format(" and ".join(cond)), as_dict=True, ) @@ -360,13 +345,11 @@ def get_count_on(account, fieldname, date): or (gle.against_voucher == gle.voucher_no and gle.get(dr_or_cr) > 0) ): payment_amount = frappe.db.sql( - """ - SELECT {0} + f""" + SELECT {select_fields} FROM `tabGL Entry` gle WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s - and party = %(party)s and name != %(name)s""".format( - select_fields - ), + and party = %(party)s and name != %(name)s""", {"date": date, "voucher_no": gle.voucher_no, "party": gle.party, "name": gle.name}, )[0][0] @@ -421,7 +404,7 @@ def add_cc(args=None): args = make_tree_args(**args) if args.parent_cost_center == args.company: - args.parent_cost_center = "{0} - {1}".format( + args.parent_cost_center = "{} - {}".format( args.parent_cost_center, frappe.get_cached_value("Company", args.company, "abbr") ) @@ -437,7 +420,7 @@ def add_cc(args=None): def _build_dimensions_dict_for_exc_gain_loss( - entry: dict | object = None, active_dimensions: list = None + entry: dict | object = None, active_dimensions: list | None = None ): dimensions_dict = frappe._dict() if entry and active_dimensions: @@ -501,7 +484,11 @@ def reconcile_against_document( # Only update outstanding for newly linked vouchers for entry in entries: update_voucher_outstanding( - entry.against_voucher_type, entry.against_voucher, entry.account, entry.party_type, entry.party + entry.against_voucher_type, + entry.against_voucher, + entry.account, + entry.party_type, + entry.party, ) frappe.flags.ignore_party_validation = False @@ -525,9 +512,7 @@ def check_if_advance_entry_modified(args): and t2.party_type = %(party_type)s and t2.party = %(party)s and (t2.reference_type is null or t2.reference_type in ('', 'Sales Order', 'Purchase Order')) and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s - and t1.docstatus=1 """.format( - dr_or_cr=args.get("dr_or_cr") - ), + and t1.docstatus=1 """.format(dr_or_cr=args.get("dr_or_cr")), args, ) else: @@ -542,12 +527,10 @@ def check_if_advance_entry_modified(args): where t1.name = t2.parent and t1.docstatus = 1 and t1.name = %(voucher_no)s and t2.name = %(voucher_detail_no)s - and t1.party_type = %(party_type)s and t1.party = %(party)s and t1.{0} = %(account)s + and t1.party_type = %(party_type)s and t1.party = %(party)s and t1.{} = %(account)s and t2.reference_doctype in ('', 'Sales Order', 'Purchase Order') and t2.allocated_amount = %(unreconciled_amount)s - """.format( - party_account_field - ), + """.format(party_account_field), args, ) else: @@ -571,9 +554,7 @@ def check_if_advance_entry_modified(args): def validate_allocated_amount(args): - precision = args.get("precision") or frappe.db.get_single_value( - "System Settings", "currency_precision" - ) + precision = args.get("precision") or frappe.db.get_single_value("System Settings", "currency_precision") if args.get("allocated_amount") < 0: throw(_("Allocated amount cannot be negative")) elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision): @@ -708,7 +689,7 @@ def update_reference_in_payment_entry( def cancel_exchange_gain_loss_journal( - parent_doc: dict | object, referenced_dt: str = None, referenced_dn: str = None + parent_doc: dict | object, referenced_dt: str | None = None, referenced_dn: str | None = None ) -> None: """ Cancel Exchange Gain/Loss for Sales/Purchase Invoice, if they have any. @@ -751,7 +732,7 @@ def cancel_exchange_gain_loss_journal( def update_accounting_ledgers_after_reference_removal( - ref_type: str = None, ref_no: str = None, payment_name: str = None + ref_type: str | None = None, ref_no: str | None = None, payment_name: str | None = None ): # General Ledger gle = qb.DocType("GL Entry") @@ -777,9 +758,7 @@ def update_accounting_ledgers_after_reference_removal( .set(ple.modified, now()) .set(ple.modified_by, frappe.session.user) .where( - (ple.against_voucher_type == ref_type) - & (ple.against_voucher_no == ref_no) - & (ple.delinked == 0) + (ple.against_voucher_type == ref_type) & (ple.against_voucher_no == ref_no) & (ple.delinked == 0) ) ) @@ -796,7 +775,7 @@ def remove_ref_from_advance_section(ref_doc: object = None): qb.from_(adv_type).delete().where(adv_type.parent == ref_doc.name).run() -def unlink_ref_doc_from_payment_entries(ref_doc: object = None, payment_name: str = None): +def unlink_ref_doc_from_payment_entries(ref_doc: object = None, payment_name: str | None = None): remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name, payment_name) remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name, payment_name) update_accounting_ledgers_after_reference_removal(ref_doc.doctype, ref_doc.name, payment_name) @@ -804,7 +783,7 @@ def unlink_ref_doc_from_payment_entries(ref_doc: object = None, payment_name: st def remove_ref_doc_link_from_jv( - ref_type: str = None, ref_no: str = None, payment_name: str = None + ref_type: str | None = None, ref_no: str | None = None, payment_name: str | None = None ): jea = qb.DocType("Journal Entry Account") @@ -844,7 +823,7 @@ def convert_to_list(result): def remove_ref_doc_link_from_pe( - ref_type: str = None, ref_no: str = None, payment_name: str = None + ref_type: str | None = None, ref_no: str | None = None, payment_name: str | None = None ): per = qb.DocType("Payment Entry Reference") pay = qb.DocType("Payment Entry") @@ -852,9 +831,7 @@ def remove_ref_doc_link_from_pe( linked_pe = ( qb.from_(per) .select(per.parent) - .where( - (per.reference_doctype == ref_type) & (per.reference_name == ref_no) & (per.docstatus.lt(2)) - ) + .where((per.reference_doctype == ref_type) & (per.reference_name == ref_no) & (per.docstatus.lt(2))) .run(as_list=1) ) linked_pe = convert_to_list(linked_pe) @@ -867,9 +844,7 @@ def remove_ref_doc_link_from_pe( .set(per.allocated_amount, 0) .set(per.modified, now()) .set(per.modified_by, frappe.session.user) - .where( - (per.docstatus.lt(2) & (per.reference_doctype == ref_type) & (per.reference_name == ref_no)) - ) + .where(per.docstatus.lt(2) & (per.reference_doctype == ref_type) & (per.reference_name == ref_no)) ) if payment_name: @@ -883,7 +858,7 @@ def remove_ref_doc_link_from_pe( pe_doc.set_amounts() pe_doc.clear_unallocated_reference_document_rows() pe_doc.validate_payment_type_with_outstanding() - except Exception as e: + except Exception: msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name) msg += "
" msg += _("Please cancel payment entry manually first") @@ -893,9 +868,7 @@ def remove_ref_doc_link_from_pe( pay.base_total_allocated_amount, pe_doc.base_total_allocated_amount ).set(pay.unallocated_amount, pe_doc.unallocated_amount).set(pay.modified, now()).set( pay.modified_by, frappe.session.user - ).where( - pay.name == pe - ).run() + ).where(pay.name == pe).run() frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe))) @@ -929,9 +902,10 @@ def fix_total_debit_credit(): dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit" frappe.db.sql( - """update `tabGL Entry` set %s = %s + %s - where voucher_type = %s and voucher_no = %s and %s > 0 limit 1""" - % (dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr), + """update `tabGL Entry` set {} = {} + {} + where voucher_type = {} and voucher_no = {} and {} > 0 limit 1""".format( + dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr + ), (d.diff, d.voucher_type, d.voucher_no), ) @@ -956,20 +930,22 @@ def get_stock_rbnb_difference(posting_date, company): """ select sum(pr_item.valuation_rate * pr_item.qty * pr_item.conversion_factor) from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr - where pr.name = pr_item.parent and pr.docstatus=1 and pr.company=%s - and pr.posting_date <= %s and pr_item.item_code in (%s)""" - % ("%s", "%s", ", ".join(["%s"] * len(stock_items))), - tuple([company, posting_date] + stock_items), + where pr.name = pr_item.parent and pr.docstatus=1 and pr.company={} + and pr.posting_date <= {} and pr_item.item_code in ({})""".format( + "%s", "%s", ", ".join(["%s"] * len(stock_items)) + ), + tuple([company, posting_date, *stock_items]), )[0][0] pi_valuation_amount = frappe.db.sql( """ select sum(pi_item.valuation_rate * pi_item.qty * pi_item.conversion_factor) from `tabPurchase Invoice Item` pi_item, `tabPurchase Invoice` pi - where pi.name = pi_item.parent and pi.docstatus=1 and pi.company=%s - and pi.posting_date <= %s and pi_item.item_code in (%s)""" - % ("%s", "%s", ", ".join(["%s"] * len(stock_items))), - tuple([company, posting_date] + stock_items), + where pi.name = pi_item.parent and pi.docstatus=1 and pi.company={} + and pi.posting_date <= {} and pi_item.item_code in ({})""".format( + "%s", "%s", ", ".join(["%s"] * len(stock_items)) + ), + tuple([company, posting_date, *stock_items]), )[0][0] # Balance should be @@ -1014,15 +990,12 @@ def get_outstanding_invoices( limit=None, # passed by reconciliation tool voucher_no=None, # filter passed by reconciliation tool ): - ple = qb.DocType("Payment Ledger Entry") outstanding_invoices = [] precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2 if account: - root_type, account_type = frappe.get_cached_value( - "Account", account, ["root_type", "account_type"] - ) + root_type, account_type = frappe.get_cached_value("Account", account, ["root_type", "account_type"]) party_account_type = "Receivable" if root_type == "Asset" else "Payable" party_account_type = account_type or party_account_type else: @@ -1076,15 +1049,11 @@ def get_outstanding_invoices( ) ) - outstanding_invoices = sorted( - outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate()) - ) + outstanding_invoices = sorted(outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate())) return outstanding_invoices -def get_account_name( - account_type=None, root_type=None, is_group=None, account_currency=None, company=None -): +def get_account_name(account_type=None, root_type=None, is_group=None, account_currency=None, company=None): """return account based on matching conditions""" return frappe.db.get_value( "Account", @@ -1113,7 +1082,7 @@ def get_children(doctype, parent, company, is_root=False): fields = ["name as value", "is_group as expandable"] filters = [["docstatus", "<", 2]] - filters.append(['ifnull(`{0}`,"")'.format(parent_fieldname), "=", "" if is_root else parent]) + filters.append([f'ifnull(`{parent_fieldname}`,"")', "=", "" if is_root else parent]) if is_root: fields += ["root_type", "report_type", "account_currency"] if doctype == "Account" else [] @@ -1133,7 +1102,6 @@ def get_children(doctype, parent, company, is_root=False): @frappe.whitelist() def get_account_balances(accounts, company): - if isinstance(accounts, str): accounts = loads(accounts) @@ -1144,9 +1112,7 @@ def get_account_balances(accounts, company): for account in accounts: account["company_currency"] = company_currency - account["balance"] = flt( - get_balance_on(account["value"], in_account_currency=False, company=company) - ) + account["balance"] = flt(get_balance_on(account["value"], in_account_currency=False, company=company)) if account["account_currency"] and account["account_currency"] != company_currency: account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company)) @@ -1296,20 +1262,17 @@ def update_gl_entries_after( warehouse_account=None, company=None, ): - stock_vouchers = get_future_stock_vouchers( - posting_date, posting_time, for_warehouses, for_items, company - ) + stock_vouchers = get_future_stock_vouchers(posting_date, posting_time, for_warehouses, for_items, company) repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account) def repost_gle_for_stock_vouchers( - stock_vouchers: List[Tuple[str, str]], + stock_vouchers: list[tuple[str, str]], posting_date: str, - company: Optional[str] = None, + company: str | None = None, warehouse_account=None, repost_doc: Optional["RepostItemValuation"] = None, ): - from erpnext.accounts.general_ledger import toggle_debit_credit_if_negative if not stock_vouchers: @@ -1355,16 +1318,12 @@ def repost_gle_for_stock_vouchers( def _delete_pl_entries(voucher_type, voucher_no): ple = qb.DocType("Payment Ledger Entry") - qb.from_(ple).delete().where( - (ple.voucher_type == voucher_type) & (ple.voucher_no == voucher_no) - ).run() + qb.from_(ple).delete().where((ple.voucher_type == voucher_type) & (ple.voucher_no == voucher_no)).run() def _delete_gl_entries(voucher_type, voucher_no): gle = qb.DocType("GL Entry") - qb.from_(gle).delete().where( - (gle.voucher_type == voucher_type) & (gle.voucher_no == voucher_no) - ).run() + qb.from_(gle).delete().where((gle.voucher_type == voucher_type) & (gle.voucher_no == voucher_no)).run() def _delete_accounting_ledger_entries(voucher_type, voucher_no): @@ -1375,9 +1334,7 @@ def _delete_accounting_ledger_entries(voucher_type, voucher_no): _delete_pl_entries(voucher_type, voucher_no) -def sort_stock_vouchers_by_posting_date( - stock_vouchers: List[Tuple[str, str]] -) -> List[Tuple[str, str]]: +def sort_stock_vouchers_by_posting_date(stock_vouchers: list[tuple[str, str]]) -> list[tuple[str, str]]: sle = frappe.qb.DocType("Stock Ledger Entry") voucher_nos = [v[1] for v in stock_vouchers] @@ -1398,10 +1355,7 @@ def sort_stock_vouchers_by_posting_date( return sorted_vouchers -def get_future_stock_vouchers( - posting_date, posting_time, for_warehouses=None, for_items=None, company=None -): - +def get_future_stock_vouchers(posting_date, posting_time, for_warehouses=None, for_items=None, company=None): values = [] condition = "" if for_items: @@ -1417,16 +1371,14 @@ def get_future_stock_vouchers( values.append(company) future_stock_vouchers = frappe.db.sql( - """select distinct sle.voucher_type, sle.voucher_no + f"""select distinct sle.voucher_type, sle.voucher_no from `tabStock Ledger Entry` sle where timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s) and is_cancelled = 0 {condition} - order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""".format( - condition=condition - ), - tuple([posting_date, posting_time] + values), + order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""", + tuple([posting_date, posting_time, *values]), as_dict=True, ) @@ -1453,9 +1405,8 @@ def get_voucherwise_gl_entries(future_stock_vouchers, posting_date): select name, account, credit, debit, cost_center, project, voucher_type, voucher_no from `tabGL Entry` where - posting_date >= %s and voucher_no in (%s)""" - % ("%s", ", ".join(["%s"] * len(voucher_nos))), - tuple([posting_date] + voucher_nos), + posting_date >= {} and voucher_no in ({})""".format("%s", ", ".join(["%s"] * len(voucher_nos))), + tuple([posting_date, *voucher_nos]), as_dict=1, ) @@ -1494,16 +1445,16 @@ def compare_existing_and_expected_gle(existing_gle, expected_gle, precision): def get_stock_accounts(company, voucher_type=None, voucher_no=None): stock_accounts = [ d.name - for d in frappe.db.get_all( - "Account", {"account_type": "Stock", "company": company, "is_group": 0} - ) + for d in frappe.db.get_all("Account", {"account_type": "Stock", "company": company, "is_group": 0}) ] if voucher_type and voucher_no: if voucher_type == "Journal Entry": stock_accounts = [ d.account for d in frappe.db.get_all( - "Journal Entry Account", {"parent": voucher_no, "account": ["in", stock_accounts]}, "account" + "Journal Entry Account", + {"parent": voucher_no, "account": ["in", stock_accounts]}, + "account", ) ] @@ -1512,7 +1463,11 @@ def get_stock_accounts(company, voucher_type=None, voucher_no=None): d.account for d in frappe.db.get_all( "GL Entry", - {"voucher_type": voucher_type, "voucher_no": voucher_no, "account": ["in", stock_accounts]}, + { + "voucher_type": voucher_type, + "voucher_no": voucher_no, + "account": ["in", stock_accounts], + }, "account", ) ] @@ -1543,9 +1498,7 @@ def get_stock_and_account_balance(account=None, posting_date=None, company=None) def get_journal_entry(account, stock_adjustment_account, amount): - db_or_cr_warehouse_account = ( - "credit_in_account_currency" if amount < 0 else "debit_in_account_currency" - ) + db_or_cr_warehouse_account = "credit_in_account_currency" if amount < 0 else "debit_in_account_currency" db_or_cr_stock_adjustment_account = ( "debit_in_account_currency" if amount < 0 else "credit_in_account_currency" ) @@ -1566,7 +1519,7 @@ def check_and_delete_linked_reports(report): frappe.delete_doc("Desktop Icon", icon) -def create_err_and_its_journals(companies: list = None) -> None: +def create_err_and_its_journals(companies: list | None = None) -> None: if companies: for company in companies: err = frappe.new_doc("Exchange Rate Revaluation") @@ -1623,9 +1576,7 @@ def get_payment_ledger_entries(gl_entries, cancel=0): accounts_with_types = ( qb.from_(account) .select(account.name, account.account_type) - .where( - (account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies))) - ) + .where(account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies))) .run(as_dict=True) ) receivable_or_payable_accounts = [y.name for y in accounts_with_types] @@ -1692,7 +1643,6 @@ def create_payment_ledger_entry( ple_map = get_payment_ledger_entries(gl_entries, cancel=cancel) for entry in ple_map: - ple = frappe.get_doc(entry) if cancel: @@ -1770,7 +1720,7 @@ def delink_original_entry(pl_entry, partial_cancel=False): query.run() -class QueryPaymentLedger(object): +class QueryPaymentLedger: """ Helper Class for Querying Payment Ledger Entry """ @@ -1938,7 +1888,8 @@ class QueryPaymentLedger(object): Table("outstanding").amount_in_account_currency.as_("outstanding_in_account_currency"), (Table("vouchers").amount - Table("outstanding").amount).as_("paid_amount"), ( - Table("vouchers").amount_in_account_currency - Table("outstanding").amount_in_account_currency + Table("vouchers").amount_in_account_currency + - Table("outstanding").amount_in_account_currency ).as_("paid_amount_in_account_currency"), Table("vouchers").due_date, Table("vouchers").currency, diff --git a/erpnext/assets/dashboard_fixtures.py b/erpnext/assets/dashboard_fixtures.py index fc9ba386a38..3b1d14440cf 100644 --- a/erpnext/assets/dashboard_fixtures.py +++ b/erpnext/assets/dashboard_fixtures.py @@ -12,7 +12,6 @@ from erpnext.buying.dashboard_fixtures import get_company_for_dashboards def get_data(): - fiscal_year = _get_fiscal_year(nowdate()) if not fiscal_year: @@ -168,9 +167,7 @@ def get_number_cards(fiscal_year, year_start_date, year_end_date): "is_public": 1, "show_percentage_stats": 1, "stats_time_interval": "Monthly", - "filters_json": json.dumps( - [["Asset", "creation", "between", [year_start_date, year_end_date]]] - ), + "filters_json": json.dumps([["Asset", "creation", "between", [year_start_date, year_end_date]]]), "doctype": "Number Card", }, { diff --git a/erpnext/assets/doctype/asset/asset.py b/erpnext/assets/doctype/asset/asset.py index 95c627735d6..fd00a495030 100644 --- a/erpnext/assets/doctype/asset/asset.py +++ b/erpnext/assets/doctype/asset/asset.py @@ -85,9 +85,7 @@ class Asset(AccountsController): ) if self.is_existing_asset and self.purchase_invoice: - frappe.throw( - _("Purchase Invoice cannot be made against an existing asset {0}").format(self.name) - ) + frappe.throw(_("Purchase Invoice cannot be made against an existing asset {0}").format(self.name)) def prepare_depreciation_data( self, @@ -207,9 +205,9 @@ class Asset(AccountsController): for d in self.finance_books: if d.depreciation_start_date == self.available_for_use_date: frappe.throw( - _("Row #{}: Depreciation Posting Date should not be equal to Available for Use Date.").format( - d.idx - ), + _( + "Row #{}: Depreciation Posting Date should not be equal to Available for Use Date." + ).format(d.idx), title=_("Incorrect Date"), ) @@ -218,9 +216,7 @@ class Asset(AccountsController): self.asset_category = frappe.get_cached_value("Item", self.item_code, "asset_category") if self.item_code and not self.get("finance_books"): - finance_books = get_item_details( - self.item_code, self.asset_category, self.gross_purchase_amount - ) + finance_books = get_item_details(self.item_code, self.asset_category, self.gross_purchase_amount) self.set("finance_books", finance_books) def validate_finance_books(self): @@ -270,7 +266,9 @@ class Asset(AccountsController): and not frappe.db.get_value("Purchase Invoice", self.purchase_invoice, "update_stock") ): frappe.throw( - _("Update stock must be enabled for the purchase invoice {0}").format(self.purchase_invoice) + _("Update stock must be enabled for the purchase invoice {0}").format( + self.purchase_invoice + ) ) if not self.calculate_depreciation: @@ -284,9 +282,7 @@ class Asset(AccountsController): if self.is_existing_asset: return - if self.available_for_use_date and getdate(self.available_for_use_date) < getdate( - self.purchase_date - ): + if self.available_for_use_date and getdate(self.available_for_use_date) < getdate(self.purchase_date): frappe.throw(_("Available-for-use Date should be after purchase date")) def validate_gross_and_purchase_amount(self): @@ -309,7 +305,7 @@ class Asset(AccountsController): posting_date, posting_time = frappe.db.get_value( reference_doctype, reference_docname, ["posting_date", "posting_time"] ) - transaction_date = get_datetime("{} {}".format(posting_date, posting_time)) + transaction_date = get_datetime(f"{posting_date} {posting_time}") assets = [ { "asset": self.name, @@ -347,9 +343,7 @@ class Asset(AccountsController): start = self.clear_depreciation_schedule() for finance_book in self.get("finance_books"): - self._make_depreciation_schedule( - finance_book, start, date_of_disposal, value_after_depreciation - ) + self._make_depreciation_schedule(finance_book, start, date_of_disposal, value_after_depreciation) if len(self.get("finance_books")) > 1 and any(start): self.sort_depreciation_schedule() @@ -467,7 +461,10 @@ class Asset(AccountsController): from_date = get_last_day( add_months( getdate(self.available_for_use_date), - ((self.number_of_depreciations_booked - 1) * finance_book.frequency_of_depreciation), + ( + (self.number_of_depreciations_booked - 1) + * finance_book.frequency_of_depreciation + ), ) ) else: @@ -489,7 +486,8 @@ class Asset(AccountsController): # In case of increase_in_asset_life, the self.to_date is already set on asset_repair submission self.to_date = add_months( self.available_for_use_date, - (n + self.number_of_depreciations_booked) * cint(finance_book.frequency_of_depreciation), + (n + self.number_of_depreciations_booked) + * cint(finance_book.frequency_of_depreciation), ) depreciation_amount_without_pro_rata = depreciation_amount @@ -519,9 +517,7 @@ class Asset(AccountsController): if ( n == cint(final_number_of_depreciations) - 1 and flt(value_after_depreciation) != flt(finance_book.expected_value_after_useful_life) - ) or flt(value_after_depreciation) < flt( - finance_book.expected_value_after_useful_life - ): + ) or flt(value_after_depreciation) < flt(finance_book.expected_value_after_useful_life): depreciation_amount += flt(value_after_depreciation) - flt( finance_book.expected_value_after_useful_life ) @@ -672,7 +668,8 @@ class Asset(AccountsController): if not row.depreciation_start_date: if not self.available_for_use_date: frappe.throw( - _("Row {0}: Depreciation Start Date is required").format(row.idx), title=_("Invalid Schedule") + _("Row {0}: Depreciation Start Date is required").format(row.idx), + title=_("Invalid Schedule"), ) row.depreciation_start_date = get_last_day(self.available_for_use_date) @@ -702,9 +699,7 @@ class Asset(AccountsController): title=_("Invalid Schedule"), ) - if row.depreciation_start_date and getdate(row.depreciation_start_date) < getdate( - self.purchase_date - ): + if row.depreciation_start_date and getdate(row.depreciation_start_date) < getdate(self.purchase_date): frappe.throw( _("Depreciation Row {0}: Next Depreciation Date cannot be before Purchase Date").format( row.idx @@ -900,11 +895,14 @@ class Asset(AccountsController): if self.calculate_depreciation: idx = self.get_default_finance_book_idx() or 0 - expected_value_after_useful_life = self.finance_books[idx].expected_value_after_useful_life + expected_value_after_useful_life = self.finance_books[ + idx + ].expected_value_after_useful_life value_after_depreciation = self.finance_books[idx].value_after_depreciation if ( - flt(value_after_depreciation) <= expected_value_after_useful_life or self.is_fully_depreciated + flt(value_after_depreciation) <= expected_value_after_useful_life + or self.is_fully_depreciated ): status = "Fully Depreciated" elif flt(value_after_depreciation) < flt(self.gross_purchase_amount): @@ -1016,7 +1014,6 @@ class Asset(AccountsController): and self.purchase_receipt_amount and getdate(self.available_for_use_date) <= getdate() ): - gl_entries.append( self.get_gl_dict( { @@ -1055,9 +1052,7 @@ class Asset(AccountsController): @frappe.whitelist() def get_manual_depreciation_entries(self): - (_, _, depreciation_expense_account) = get_depreciation_accounts( - self.asset_category, self.company - ) + (_, _, depreciation_expense_account) = get_depreciation_accounts(self.asset_category, self.company) gle = frappe.qb.DocType("GL Entry") @@ -1084,7 +1079,8 @@ class Asset(AccountsController): if args.get("depreciation_method") == "Double Declining Balance": return 200.0 / ( ( - flt(args.get("total_number_of_depreciations"), 2) * flt(args.get("frequency_of_depreciation")) + flt(args.get("total_number_of_depreciations"), 2) + * flt(args.get("frequency_of_depreciation")) ) / 12 ) @@ -1146,9 +1142,7 @@ def update_maintenance_status(): asset = frappe.get_doc("Asset", asset.name) if frappe.db.exists("Asset Repair", {"asset_name": asset.name, "repair_status": "Pending"}): asset.set_status("Out of Order") - elif frappe.db.exists( - "Asset Maintenance Task", {"parent": asset.name, "next_due_date": today()} - ): + elif frappe.db.exists("Asset Maintenance Task", {"parent": asset.name, "next_due_date": today()}): asset.set_status("In Maintenance") else: asset.set_status() @@ -1232,9 +1226,7 @@ def create_asset_capitalization(asset): @frappe.whitelist() def create_asset_value_adjustment(asset, asset_category, company): asset_value_adjustment = frappe.new_doc("Asset Value Adjustment") - asset_value_adjustment.update( - {"asset": asset, "company": company, "asset_category": asset_category} - ) + asset_value_adjustment.update({"asset": asset, "company": company, "asset_category": asset_category}) return asset_value_adjustment @@ -1291,18 +1283,14 @@ def get_asset_account(account_name, asset=None, asset_category=None, company=Non ) if not asset and not account: - account = get_asset_category_account( - account_name, asset_category=asset_category, company=company - ) + account = get_asset_category_account(account_name, asset_category=asset_category, company=company) if not account: account = frappe.get_cached_value("Company", company, account_name) if not account: if not asset_category: - frappe.throw( - _("Set {0} in company {1}").format(account_name.replace("_", " ").title(), company) - ) + frappe.throw(_("Set {0} in company {1}").format(account_name.replace("_", " ").title(), company)) else: frappe.throw( _("Set {0} in asset category {1} or company {2}").format( @@ -1331,7 +1319,7 @@ def make_journal_entry(asset_name): je.voucher_type = "Depreciation Entry" je.naming_series = depreciation_series je.company = asset.company - je.remark = "Depreciation Entry against asset {0}".format(asset_name) + je.remark = f"Depreciation Entry against asset {asset_name}" je.append( "accounts", @@ -1433,9 +1421,7 @@ def get_depreciation_amount( ) -def get_straight_line_or_manual_depr_amount( - asset, row, schedule_idx, number_of_pending_depreciations -): +def get_straight_line_or_manual_depr_amount(asset, row, schedule_idx, number_of_pending_depreciations): if row.shift_based: return get_shift_depr_amount(asset, row, schedule_idx) @@ -1487,7 +1473,9 @@ def get_straight_line_or_manual_depr_amount( ) from_date = add_days( get_last_day( - add_months(row.depreciation_start_date, (schedule_idx - 1) * row.frequency_of_depreciation) + add_months( + row.depreciation_start_date, (schedule_idx - 1) * row.frequency_of_depreciation + ) ), 1, ) @@ -1500,7 +1488,6 @@ def get_straight_line_or_manual_depr_amount( # if the Depreciation Schedule is being prepared for the first time else: if row.daily_prorata_based: - amount = ( flt(asset.gross_purchase_amount) - flt(asset.opening_accumulated_depreciation) @@ -1516,7 +1503,10 @@ def get_straight_line_or_manual_depr_amount( ) ), add_days( - get_last_day(add_months(row.depreciation_start_date, -1 * row.frequency_of_depreciation)), 1 + get_last_day( + add_months(row.depreciation_start_date, -1 * row.frequency_of_depreciation) + ), + 1, ), ) + 1 @@ -1528,7 +1518,9 @@ def get_straight_line_or_manual_depr_amount( ) from_date = add_days( get_last_day( - add_months(row.depreciation_start_date, (schedule_idx - 1) * row.frequency_of_depreciation) + add_months( + row.depreciation_start_date, (schedule_idx - 1) * row.frequency_of_depreciation + ) ), 1, ) @@ -1688,9 +1680,7 @@ def update_existing_asset(asset, remaining_qty): processed_finance_books.append(int(term.finance_book_id)) depreciation_amount = flt((term.depreciation_amount * remaining_qty) / asset.asset_quantity) - frappe.db.set_value( - "Depreciation Schedule", term.name, "depreciation_amount", depreciation_amount - ) + frappe.db.set_value("Depreciation Schedule", term.name, "depreciation_amount", depreciation_amount) accumulated_depreciation += depreciation_amount frappe.db.set_value( "Depreciation Schedule", term.name, "accumulated_depreciation_amount", accumulated_depreciation diff --git a/erpnext/assets/doctype/asset/depreciation.py b/erpnext/assets/doctype/asset/depreciation.py index 7953ed2fe2b..f7417cce76c 100644 --- a/erpnext/assets/doctype/asset/depreciation.py +++ b/erpnext/assets/doctype/asset/depreciation.py @@ -57,7 +57,10 @@ def post_depreciation_entries(date=None): ) not in credit_and_debit_accounts_for_asset_category_and_company: credit_and_debit_accounts_for_asset_category_and_company.update( { - (asset_category, asset_company): get_credit_and_debit_accounts_for_asset_category_and_company( + ( + asset_category, + asset_company, + ): get_credit_and_debit_accounts_for_asset_category_and_company( asset_category, asset_company ), } @@ -120,9 +123,7 @@ def get_acc_frozen_upto(): if not acc_frozen_upto: return - frozen_accounts_modifier = frappe.db.get_single_value( - "Accounts Settings", "frozen_accounts_modifier" - ) + frozen_accounts_modifier = frappe.db.get_single_value("Accounts Settings", "frozen_accounts_modifier") if frozen_accounts_modifier not in frappe.get_roles() or frappe.session.user == "Administrator": return getdate(acc_frozen_upto) @@ -245,9 +246,7 @@ def _make_journal_entry_for_depreciation( je.posting_date = depr_schedule.schedule_date je.company = asset.company je.finance_book = depr_schedule.finance_book - je.remark = "Depreciation Entry against {0} worth {1}".format( - asset.name, depr_schedule.depreciation_amount - ) + je.remark = f"Depreciation Entry against {asset.name} worth {depr_schedule.depreciation_amount}" credit_entry = { "account": credit_account, @@ -329,11 +328,7 @@ def get_depreciation_accounts(asset_category, company): if not depreciation_expense_account: depreciation_expense_account = accounts[1] - if ( - not fixed_asset_account - or not accumulated_depreciation_account - or not depreciation_expense_account - ): + if not fixed_asset_account or not accumulated_depreciation_account or not depreciation_expense_account: frappe.throw( _("Please set Depreciation related Accounts in Asset Category {0} or Company {1}").format( asset_category, company @@ -411,25 +406,21 @@ def scrap_asset(asset_name): if asset.docstatus != 1: frappe.throw(_("Asset {0} must be submitted").format(asset.name)) elif asset.status in ("Cancelled", "Sold", "Scrapped", "Capitalized", "Decapitalized"): - frappe.throw( - _("Asset {0} cannot be scrapped, as it is already {1}").format(asset.name, asset.status) - ) + frappe.throw(_("Asset {0} cannot be scrapped, as it is already {1}").format(asset.name, asset.status)) date = today() depreciate_asset(asset, date) asset.reload() - depreciation_series = frappe.get_cached_value( - "Company", asset.company, "series_for_depreciation_entry" - ) + depreciation_series = frappe.get_cached_value("Company", asset.company, "series_for_depreciation_entry") je = frappe.new_doc("Journal Entry") je.voucher_type = "Journal Entry" je.naming_series = depreciation_series je.posting_date = date je.company = asset.company - je.remark = "Scrap Entry for asset {0}".format(asset_name) + je.remark = f"Scrap Entry for asset {asset_name}" for entry in get_gl_entries_on_asset_disposal(asset, date): entry.update({"reference_type": "Asset", "reference_name": asset_name}) @@ -523,7 +514,6 @@ def reverse_depreciation_entry_made_after_disposal(asset, date): if not disposal_was_made_on_original_schedule_date( asset, schedule, row, date ) or disposal_happens_in_the_future(date): - reverse_journal_entry = make_reverse_journal_entry(schedule.journal_entry) reverse_journal_entry.posting_date = nowdate() @@ -714,7 +704,6 @@ def get_asset_details(asset, finance_book=None): def get_profit_gl_entries( asset, profit_amount, gl_entries, disposal_account, depreciation_cost_center, date=None ): - if not date: date = getdate() @@ -740,9 +729,7 @@ def get_disposal_account_and_cost_center(company): ) if not disposal_account: - frappe.throw( - _("Please set 'Gain/Loss Account on Asset Disposal' in Company {0}").format(company) - ) + frappe.throw(_("Please set 'Gain/Loss Account on Asset Disposal' in Company {0}").format(company)) if not depreciation_cost_center: frappe.throw(_("Please set 'Asset Depreciation Cost Center' in Company {0}").format(company)) @@ -755,7 +742,7 @@ def get_value_after_depreciation_on_disposal_date(asset, disposal_date, finance_ if asset_doc.available_for_use_date > getdate(disposal_date): frappe.throw( - "Disposal date {0} cannot be before available for use date {1} of the asset.".format( + "Disposal date {} cannot be before available for use date {} of the asset.".format( disposal_date, asset_doc.available_for_use_date ) ) @@ -772,9 +759,7 @@ def get_value_after_depreciation_on_disposal_date(asset, disposal_date, finance_ finance_book_id = fb.idx break - asset_schedules = [ - sch for sch in asset_doc.schedules if cint(sch.finance_book_id) == finance_book_id - ] + asset_schedules = [sch for sch in asset_doc.schedules if cint(sch.finance_book_id) == finance_book_id] accumulated_depr_amount = asset_schedules[-1].accumulated_depreciation_amount return flt( diff --git a/erpnext/assets/doctype/asset/test_asset.py b/erpnext/assets/doctype/asset/test_asset.py index ea5b95aaf02..00a53aa80d2 100644 --- a/erpnext/assets/doctype/asset/test_asset.py +++ b/erpnext/assets/doctype/asset/test_asset.py @@ -102,9 +102,7 @@ class TestAsset(AssetSetup): self.assertRaises(frappe.ValidationError, asset.save) def test_purchase_asset(self): - pr = make_purchase_receipt( - item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location" - ) + pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location") asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, "name") asset = frappe.get_doc("Asset", asset_name) @@ -209,7 +207,7 @@ class TestAsset(AssetSetup): asset.gross_purchase_amount - asset.finance_books[0].value_after_depreciation, asset.precision("gross_purchase_amount"), ) - self.assertEquals(accumulated_depr_amount, 18000.0) + self.assertEqual(accumulated_depr_amount, 18000.0) scrap_asset(asset.name) asset.load_from_db() @@ -226,7 +224,7 @@ class TestAsset(AssetSetup): original_schedule_date=get_last_day(nowdate()), ) pro_rata_amount = flt(pro_rata_amount, asset.precision("gross_purchase_amount")) - self.assertEquals( + self.assertEqual( accumulated_depr_amount, flt(18000.0 + pro_rata_amount, asset.precision("gross_purchase_amount")), ) @@ -263,7 +261,7 @@ class TestAsset(AssetSetup): ) this_month_depr_amount = 9000.0 if is_last_day_of_the_month(date) else 0 - self.assertEquals(accumulated_depr_amount, 18000.0 + this_month_depr_amount) + self.assertEqual(accumulated_depr_amount, 18000.0 + this_month_depr_amount) def test_gle_made_by_asset_sale(self): date = nowdate() @@ -467,9 +465,7 @@ class TestAsset(AssetSetup): self.assertEqual(jv.accounts[3].reference_name, new_asset.name) def test_expense_head(self): - pr = make_purchase_receipt( - item_code="Macbook Pro", qty=2, rate=200000.0, location="Test Location" - ) + pr = make_purchase_receipt(item_code="Macbook Pro", qty=2, rate=200000.0, location="Test Location") doc = make_invoice(pr.name) self.assertEqual("Asset Received But Not Billed - _TC", doc.items[0].expense_account) @@ -579,9 +575,7 @@ class TestAsset(AssetSetup): self.assertFalse(gle) # case 1 -- PR with cwip disabled, Asset with cwip enabled - pr = make_purchase_receipt( - item_code="Macbook Pro", qty=1, rate=200000.0, location="Test Location" - ) + pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=200000.0, location="Test Location") frappe.db.set_value("Asset Category", "Computers", "enable_cwip_accounting", 1) frappe.db.set_value("Asset Category Account", name, "capital_work_in_progress_account", cwip_acc) asset = frappe.db.get_value("Asset", {"purchase_receipt": pr.name, "docstatus": 0}, "name") @@ -593,9 +587,7 @@ class TestAsset(AssetSetup): self.assertFalse(gle) # case 2 -- PR with cwip enabled, Asset with cwip disabled - pr = make_purchase_receipt( - item_code="Macbook Pro", qty=1, rate=200000.0, location="Test Location" - ) + pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=200000.0, location="Test Location") frappe.db.set_value("Asset Category", "Computers", "enable_cwip_accounting", 0) asset = frappe.db.get_value("Asset", {"purchase_receipt": pr.name, "docstatus": 0}, "name") asset_doc = frappe.get_doc("Asset", asset) @@ -1207,8 +1199,7 @@ class TestDepreciationBasics(AssetSetup): je = frappe.get_doc("Journal Entry", asset.schedules[0].journal_entry) accounting_entries = [ - {"account": entry.account, "debit": entry.debit, "credit": entry.credit} - for entry in je.accounts + {"account": entry.account, "debit": entry.debit, "credit": entry.credit} for entry in je.accounts ] for entry in accounting_entries: @@ -1243,8 +1234,7 @@ class TestDepreciationBasics(AssetSetup): je = frappe.get_doc("Journal Entry", asset.schedules[0].journal_entry) accounting_entries = [ - {"account": entry.account, "debit": entry.debit, "credit": entry.credit} - for entry in je.accounts + {"account": entry.account, "debit": entry.debit, "credit": entry.credit} for entry in je.accounts ] for entry in accounting_entries: @@ -1468,13 +1458,13 @@ class TestDepreciationBasics(AssetSetup): asset.finance_books[0].expected_value_after_useful_life = 100 asset.save() asset.reload() - self.assertEquals(asset.finance_books[0].value_after_depreciation, 98000.0) + self.assertEqual(asset.finance_books[0].value_after_depreciation, 98000.0) # changing expected_value_after_useful_life shouldn't affect value_after_depreciation asset.finance_books[0].expected_value_after_useful_life = 200 asset.save() asset.reload() - self.assertEquals(asset.finance_books[0].value_after_depreciation, 98000.0) + self.assertEqual(asset.finance_books[0].value_after_depreciation, 98000.0) def test_asset_cost_center(self): asset = create_asset(is_existing_asset=1, do_not_save=1) diff --git a/erpnext/assets/doctype/asset_capitalization/asset_capitalization.py b/erpnext/assets/doctype/asset_capitalization/asset_capitalization.py index 76a660d6a9a..bfeeb75a642 100644 --- a/erpnext/assets/doctype/asset_capitalization/asset_capitalization.py +++ b/erpnext/assets/doctype/asset_capitalization/asset_capitalization.py @@ -86,7 +86,7 @@ class AssetCapitalization(StockController): def on_trash(self): frappe.db.set_value("Asset", self.target_asset, "capitalized_in", None) - super(AssetCapitalization, self).on_trash() + super().on_trash() def cancel_target_asset(self): if self.entry_type == "Capitalization" and self.target_asset: @@ -179,7 +179,9 @@ class AssetCapitalization(StockController): if target_asset.item_code != self.target_item_code: frappe.throw( - _("Asset {0} does not belong to Item {1}").format(self.target_asset, self.target_item_code) + _("Asset {0} does not belong to Item {1}").format( + self.target_asset, self.target_item_code + ) ) if target_asset.status in ("Scrapped", "Sold", "Capitalized", "Decapitalized"): @@ -194,7 +196,9 @@ class AssetCapitalization(StockController): if target_asset.company != self.company: frappe.throw( - _("Target Asset {0} does not belong to company {1}").format(target_asset.name, self.company) + _("Target Asset {0} does not belong to company {1}").format( + target_asset.name, self.company + ) ) def validate_consumed_stock_item(self): @@ -224,13 +228,17 @@ class AssetCapitalization(StockController): if asset.status in ("Draft", "Scrapped", "Sold", "Capitalized", "Decapitalized"): frappe.throw( - _("Row #{0}: Consumed Asset {1} cannot be {2}").format(d.idx, asset.name, asset.status) + _("Row #{0}: Consumed Asset {1} cannot be {2}").format( + d.idx, asset.name, asset.status + ) ) if asset.docstatus == 0: frappe.throw(_("Row #{0}: Consumed Asset {1} cannot be Draft").format(d.idx, asset.name)) elif asset.docstatus == 2: - frappe.throw(_("Row #{0}: Consumed Asset {1} cannot be cancelled").format(d.idx, asset.name)) + frappe.throw( + _("Row #{0}: Consumed Asset {1} cannot be cancelled").format(d.idx, asset.name) + ) if asset.company != self.company: frappe.throw( @@ -387,9 +395,7 @@ class AssetCapitalization(StockController): elif self.docstatus == 2: make_reverse_gl_entries(voucher_type=self.doctype, voucher_no=self.name) - def get_gl_entries( - self, warehouse_account=None, default_expense_account=None, default_cost_center=None - ): + def get_gl_entries(self, warehouse_account=None, default_expense_account=None, default_cost_center=None): # Stock GL Entries gl_entries = [] @@ -403,15 +409,9 @@ class AssetCapitalization(StockController): target_account = self.get_target_account() target_against = set() - self.get_gl_entries_for_consumed_stock_items( - gl_entries, target_account, target_against, precision - ) - self.get_gl_entries_for_consumed_asset_items( - gl_entries, target_account, target_against, precision - ) - self.get_gl_entries_for_consumed_service_items( - gl_entries, target_account, target_against, precision - ) + self.get_gl_entries_for_consumed_stock_items(gl_entries, target_account, target_against, precision) + self.get_gl_entries_for_consumed_asset_items(gl_entries, target_account, target_against, precision) + self.get_gl_entries_for_consumed_service_items(gl_entries, target_account, target_against, precision) self.get_gl_entries_for_target_item(gl_entries, target_against, precision) @@ -423,9 +423,7 @@ class AssetCapitalization(StockController): else: return self.warehouse_account[self.target_warehouse]["account"] - def get_gl_entries_for_consumed_stock_items( - self, gl_entries, target_account, target_against, precision - ): + def get_gl_entries_for_consumed_stock_items(self, gl_entries, target_account, target_against, precision): # Consumed Stock Items for item_row in self.stock_items: sle_list = self.sle_map.get(item_row.name) @@ -454,9 +452,7 @@ class AssetCapitalization(StockController): ) ) - def get_gl_entries_for_consumed_asset_items( - self, gl_entries, target_account, target_against, precision - ): + def get_gl_entries_for_consumed_asset_items(self, gl_entries, target_account, target_against, precision): # Consumed Assets for item in self.asset_items: asset = frappe.get_doc("Asset", item.asset) @@ -572,9 +568,9 @@ class AssetCapitalization(StockController): ) frappe.msgprint( - _( - "Asset {0} has been created. Please set the depreciation details if any and submit it." - ).format(get_link_to_form("Asset", asset_doc.name)) + _("Asset {0} has been created. Please set the depreciation details if any and submit it.").format( + get_link_to_form("Asset", asset_doc.name) + ) ) def update_target_asset(self): @@ -594,9 +590,9 @@ class AssetCapitalization(StockController): asset_doc.save() frappe.msgprint( - _( - "Asset {0} has been updated. Please set the depreciation details if any and submit it." - ).format(get_link_to_form("Asset", asset_doc.name)) + _("Asset {0} has been updated. Please set the depreciation details if any and submit it.").format( + get_link_to_form("Asset", asset_doc.name) + ) ) def restore_consumed_asset_items(self): @@ -709,9 +705,7 @@ def get_consumed_stock_item_details(args): item_defaults = get_item_defaults(item.name, args.company) item_group_defaults = get_item_group_defaults(item.name, args.company) brand_defaults = get_brand_defaults(item.name, args.company) - out.cost_center = get_default_cost_center( - args, item_defaults, item_group_defaults, brand_defaults - ) + out.cost_center = get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults) if args.item_code and out.warehouse: incoming_rate_args = frappe._dict( @@ -797,9 +791,7 @@ def get_consumed_asset_details(args): item_defaults = get_item_defaults(item.name, args.company) item_group_defaults = get_item_group_defaults(item.name, args.company) brand_defaults = get_brand_defaults(item.name, args.company) - out.cost_center = get_default_cost_center( - args, item_defaults, item_group_defaults, brand_defaults - ) + out.cost_center = get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults) return out @@ -826,9 +818,7 @@ def get_service_item_details(args): out.expense_account = get_default_expense_account( args, item_defaults, item_group_defaults, brand_defaults ) - out.cost_center = get_default_cost_center( - args, item_defaults, item_group_defaults, brand_defaults - ) + out.cost_center = get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults) return out diff --git a/erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py b/erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py index 59b65ec3fd0..128e2a7fe8b 100644 --- a/erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py +++ b/erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py @@ -346,9 +346,7 @@ class TestAssetCapitalization(unittest.TestCase): consumed_depreciation_schedule = [ d for d in consumed_asset.schedules if getdate(d.schedule_date) == getdate(capitalization_date) ] - self.assertTrue( - consumed_depreciation_schedule and consumed_depreciation_schedule[0].journal_entry - ) + self.assertTrue(consumed_depreciation_schedule and consumed_depreciation_schedule[0].journal_entry) self.assertEqual( consumed_depreciation_schedule[0].depreciation_amount, depreciation_before_disposal_amount ) @@ -371,15 +369,9 @@ class TestAssetCapitalization(unittest.TestCase): def create_asset_capitalization_data(): - create_item( - "Capitalization Target Stock Item", is_stock_item=1, is_fixed_asset=0, is_purchase_item=0 - ) - create_item( - "Capitalization Source Stock Item", is_stock_item=1, is_fixed_asset=0, is_purchase_item=0 - ) - create_item( - "Capitalization Source Service Item", is_stock_item=0, is_fixed_asset=0, is_purchase_item=0 - ) + create_item("Capitalization Target Stock Item", is_stock_item=1, is_fixed_asset=0, is_purchase_item=0) + create_item("Capitalization Source Stock Item", is_stock_item=1, is_fixed_asset=0, is_purchase_item=0) + create_item("Capitalization Source Service Item", is_stock_item=0, is_fixed_asset=0, is_purchase_item=0) def create_asset_capitalization(**args): diff --git a/erpnext/assets/doctype/asset_category/asset_category.py b/erpnext/assets/doctype/asset_category/asset_category.py index 2a204e11477..1beb423ba25 100644 --- a/erpnext/assets/doctype/asset_category/asset_category.py +++ b/erpnext/assets/doctype/asset_category/asset_category.py @@ -38,7 +38,9 @@ class AssetCategory(Document): account_currency = frappe.get_value("Account", d.get(type_of_account), "account_currency") if account_currency != company_currency: invalid_accounts.append( - frappe._dict({"type": type_of_account, "idx": d.idx, "account": d.get(type_of_account)}) + frappe._dict( + {"type": type_of_account, "idx": d.idx, "account": d.get(type_of_account)} + ) ) for d in invalid_accounts: diff --git a/erpnext/assets/doctype/asset_category/test_asset_category.py b/erpnext/assets/doctype/asset_category/test_asset_category.py index 2c926565768..516e27e00fa 100644 --- a/erpnext/assets/doctype/asset_category/test_asset_category.py +++ b/erpnext/assets/doctype/asset_category/test_asset_category.py @@ -31,9 +31,7 @@ class TestAssetCategory(unittest.TestCase): pass def test_cwip_accounting(self): - company_cwip_acc = frappe.db.get_value( - "Company", "_Test Company", "capital_work_in_progress_account" - ) + frappe.db.get_value("Company", "_Test Company", "capital_work_in_progress_account") frappe.db.set_value("Company", "_Test Company", "capital_work_in_progress_account", "") asset_category = frappe.new_doc("Asset Category") diff --git a/erpnext/assets/doctype/asset_maintenance/asset_maintenance.py b/erpnext/assets/doctype/asset_maintenance/asset_maintenance.py index 5c40072086e..7762e63d779 100644 --- a/erpnext/assets/doctype/asset_maintenance/asset_maintenance.py +++ b/erpnext/assets/doctype/asset_maintenance/asset_maintenance.py @@ -70,9 +70,7 @@ def calculate_next_due_date( if not start_date and not last_completion_date: start_date = frappe.utils.now() - if last_completion_date and ( - (start_date and last_completion_date > start_date) or not start_date - ): + if last_completion_date and ((start_date and last_completion_date > start_date) or not start_date): start_date = last_completion_date if periodicity == "Daily": next_due_date = add_days(start_date, 1) diff --git a/erpnext/assets/doctype/asset_maintenance/test_asset_maintenance.py b/erpnext/assets/doctype/asset_maintenance/test_asset_maintenance.py index e40a5519eb2..dcc2f4d32e6 100644 --- a/erpnext/assets/doctype/asset_maintenance/test_asset_maintenance.py +++ b/erpnext/assets/doctype/asset_maintenance/test_asset_maintenance.py @@ -17,9 +17,7 @@ class TestAssetMaintenance(unittest.TestCase): create_maintenance_team() def test_create_asset_maintenance(self): - pr = make_purchase_receipt( - item_code="Photocopier", qty=1, rate=100000.0, location="Test Location" - ) + pr = make_purchase_receipt(item_code="Photocopier", qty=1, rate=100000.0, location="Test Location") asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, "name") asset_doc = frappe.get_doc("Asset", asset_name) @@ -130,8 +128,7 @@ def create_maintenance_team(): def get_maintenance_team(user_list): return [ - {"team_member": user, "full_name": user, "maintenance_role": "Technician"} - for user in user_list[1:] + {"team_member": user, "full_name": user, "maintenance_role": "Technician"} for user in user_list[1:] ] diff --git a/erpnext/assets/doctype/asset_movement/asset_movement.py b/erpnext/assets/doctype/asset_movement/asset_movement.py index b85f7194f98..db9cb02a61e 100644 --- a/erpnext/assets/doctype/asset_movement/asset_movement.py +++ b/erpnext/assets/doctype/asset_movement/asset_movement.py @@ -32,7 +32,9 @@ class AssetMovement(Document): if d.source_location: if current_location != d.source_location: frappe.throw( - _("Asset {0} does not belongs to the location {1}").format(d.asset, d.source_location) + _("Asset {0} does not belongs to the location {1}").format( + d.asset, d.source_location + ) ) else: d.source_location = current_location @@ -57,19 +59,25 @@ class AssetMovement(Document): title=_("Incorrect Movement Purpose"), ) if not d.target_location: - frappe.throw(_("Target Location is required while transferring Asset {0}").format(d.asset)) + frappe.throw( + _("Target Location is required while transferring Asset {0}").format(d.asset) + ) if d.source_location == d.target_location: frappe.throw(_("Source and Target Location cannot be same")) if self.purpose == "Receipt": if not (d.source_location) and not (d.target_location or d.to_employee): frappe.throw( - _("Target Location or To Employee is required while receiving Asset {0}").format(d.asset) + _("Target Location or To Employee is required while receiving Asset {0}").format( + d.asset + ) ) elif d.source_location: if d.from_employee and not d.target_location: frappe.throw( - _("Target Location is required while receiving Asset {0} from an employee").format(d.asset) + _( + "Target Location is required while receiving Asset {0} from an employee" + ).format(d.asset) ) elif d.to_employee and d.target_location: frappe.throw( @@ -109,19 +117,17 @@ class AssetMovement(Document): # latest entry corresponds to current document's location, employee when transaction date > previous dates # In case of cancellation it corresponds to previous latest document's location, employee latest_movement_entry = frappe.db.sql( - """ + f""" SELECT asm_item.target_location, asm_item.to_employee FROM `tabAsset Movement Item` asm_item, `tabAsset Movement` asm WHERE asm_item.parent=asm.name and asm_item.asset=%(asset)s and asm.company=%(company)s and - asm.docstatus=1 and {0} + asm.docstatus=1 and {cond} ORDER BY asm.transaction_date desc limit 1 - """.format( - cond - ), + """, args, ) if latest_movement_entry: diff --git a/erpnext/assets/doctype/asset_movement/test_asset_movement.py b/erpnext/assets/doctype/asset_movement/test_asset_movement.py index 27e7e557f19..52590d2ba86 100644 --- a/erpnext/assets/doctype/asset_movement/test_asset_movement.py +++ b/erpnext/assets/doctype/asset_movement/test_asset_movement.py @@ -20,9 +20,7 @@ class TestAssetMovement(unittest.TestCase): make_location() def test_movement(self): - pr = make_purchase_receipt( - item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location" - ) + pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location") asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, "name") asset = frappe.get_doc("Asset", asset_name) @@ -51,7 +49,11 @@ class TestAssetMovement(unittest.TestCase): purpose="Transfer", company=asset.company, assets=[ - {"asset": asset.name, "source_location": "Test Location", "target_location": "Test Location 2"} + { + "asset": asset.name, + "source_location": "Test Location", + "target_location": "Test Location 2", + } ], reference_doctype="Purchase Receipt", reference_name=pr.name, @@ -62,7 +64,11 @@ class TestAssetMovement(unittest.TestCase): purpose="Transfer", company=asset.company, assets=[ - {"asset": asset.name, "source_location": "Test Location 2", "target_location": "Test Location"} + { + "asset": asset.name, + "source_location": "Test Location 2", + "target_location": "Test Location", + } ], reference_doctype="Purchase Receipt", reference_name=pr.name, @@ -97,9 +103,7 @@ class TestAssetMovement(unittest.TestCase): self.assertEqual(frappe.db.get_value("Asset", asset.name, "location"), "Test Location") def test_last_movement_cancellation(self): - pr = make_purchase_receipt( - item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location" - ) + pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location") asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, "name") asset = frappe.get_doc("Asset", asset_name) @@ -129,7 +133,11 @@ class TestAssetMovement(unittest.TestCase): purpose="Transfer", company=asset.company, assets=[ - {"asset": asset.name, "source_location": "Test Location", "target_location": "Test Location 2"} + { + "asset": asset.name, + "source_location": "Test Location", + "target_location": "Test Location 2", + } ], reference_doctype="Purchase Receipt", reference_name=pr.name, @@ -167,6 +175,4 @@ def create_asset_movement(**args): def make_location(): for location in ["Pune", "Mumbai", "Nagpur"]: if not frappe.db.exists("Location", location): - frappe.get_doc({"doctype": "Location", "location_name": location}).insert( - ignore_permissions=True - ) + frappe.get_doc({"doctype": "Location", "location_name": location}).insert(ignore_permissions=True) diff --git a/erpnext/assets/doctype/asset_repair/asset_repair.py b/erpnext/assets/doctype/asset_repair/asset_repair.py index b348e13ca83..da933c96057 100644 --- a/erpnext/assets/doctype/asset_repair/asset_repair.py +++ b/erpnext/assets/doctype/asset_repair/asset_repair.py @@ -98,9 +98,7 @@ class AssetRepair(AccountsController): def check_for_stock_items_and_warehouse(self): if not self.get("stock_items"): - frappe.throw( - _("Please enter Stock Items consumed during the Repair."), title=_("Missing Items") - ) + frappe.throw(_("Please enter Stock Items consumed during the Repair."), title=_("Missing Items")) if not self.warehouse: frappe.throw( _("Please enter Warehouse from which Stock Items consumed during the Repair were taken."), @@ -173,9 +171,7 @@ class AssetRepair(AccountsController): def get_gl_entries(self): gl_entries = [] - fixed_asset_account = get_asset_account( - "fixed_asset_account", asset=self.asset, company=self.company - ) + fixed_asset_account = get_asset_account("fixed_asset_account", asset=self.asset, company=self.company) self.get_gl_entries_for_repair_cost(gl_entries, fixed_asset_account) self.get_gl_entries_for_consumed_items(gl_entries, fixed_asset_account) diff --git a/erpnext/assets/doctype/asset_repair/test_asset_repair.py b/erpnext/assets/doctype/asset_repair/test_asset_repair.py index 3adb3516908..274c1768179 100644 --- a/erpnext/assets/doctype/asset_repair/test_asset_repair.py +++ b/erpnext/assets/doctype/asset_repair/test_asset_repair.py @@ -193,9 +193,7 @@ class TestAssetRepair(unittest.TestCase): self.assertEqual(expected_values[d.account][1], d.credit) def test_gl_entries_with_periodical_inventory(self): - frappe.db.set_value( - "Company", "_Test Company", "default_expense_account", "Cost of Goods Sold - _TC" - ) + frappe.db.set_value("Company", "_Test Company", "default_expense_account", "Cost of Goods Sold - _TC") asset_repair = create_asset_repair( capitalize_repair_cost=1, stock_consumption=1, @@ -275,9 +273,7 @@ def create_asset_repair(**args): if args.stock_consumption: asset_repair.stock_consumption = 1 - asset_repair.warehouse = args.warehouse or create_warehouse( - "Test Warehouse", company=asset.company - ) + asset_repair.warehouse = args.warehouse or create_warehouse("Test Warehouse", company=asset.company) asset_repair.append( "stock_items", { diff --git a/erpnext/assets/doctype/asset_shift_allocation/asset_shift_allocation.py b/erpnext/assets/doctype/asset_shift_allocation/asset_shift_allocation.py index d9797b0c24c..e255c827f14 100644 --- a/erpnext/assets/doctype/asset_shift_allocation/asset_shift_allocation.py +++ b/erpnext/assets/doctype/asset_shift_allocation/asset_shift_allocation.py @@ -108,9 +108,7 @@ class AssetShiftAllocation(Document): def allocate_shift_diff_in_depr_schedule(self): asset_shift_factors_map = get_asset_shift_factors_map() - reverse_asset_shift_factors_map = { - asset_shift_factors_map[k]: k for k in asset_shift_factors_map - } + reverse_asset_shift_factors_map = {asset_shift_factors_map[k]: k for k in asset_shift_factors_map} original_shift_factors_sum = sum( flt(asset_shift_factors_map.get(schedule.shift)) for schedule in self.asset_doc.schedules @@ -139,9 +137,9 @@ class AssetShiftAllocation(Document): ) diff = 0 except Exception: - frappe.throw(_("Could not auto update shifts. Shift with shift factor {0} needed.")).format( - shift_factor - diff - ) + frappe.throw( + _("Could not auto update shifts. Shift with shift factor {0} needed.") + ).format(shift_factor - diff) elif diff < 0: shift_factors = list(asset_shift_factors_map.values()) desc_shift_factors = sorted(shift_factors, reverse=True) @@ -202,9 +200,9 @@ class AssetShiftAllocation(Document): ) diff = 0 except Exception: - frappe.throw(_("Could not auto update shifts. Shift with shift factor {0} needed.")).format( - shift_factor + diff - ) + frappe.throw( + _("Could not auto update shifts. Shift with shift factor {0} needed.") + ).format(shift_factor + diff) def update_asset_schedule(self): self.asset_doc.flags.shift_allocation = True @@ -239,9 +237,7 @@ def find_subsets_with_sum(numbers, k, target_sum, current_subset, result): return # Include the current number in the subset - find_subsets_with_sum( - numbers, k - 1, target_sum - numbers[0], current_subset + [numbers[0]], result - ) + find_subsets_with_sum(numbers, k - 1, target_sum - numbers[0], [*current_subset, numbers[0]], result) # Exclude the current number from the subset find_subsets_with_sum(numbers[1:], k, target_sum, current_subset, result) diff --git a/erpnext/assets/doctype/asset_shift_factor/asset_shift_factor.py b/erpnext/assets/doctype/asset_shift_factor/asset_shift_factor.py index 4c275ce092c..d9bc2283f5b 100644 --- a/erpnext/assets/doctype/asset_shift_factor/asset_shift_factor.py +++ b/erpnext/assets/doctype/asset_shift_factor/asset_shift_factor.py @@ -12,9 +12,7 @@ class AssetShiftFactor(Document): def validate_default(self): if self.default: - existing_default_shift_factor = frappe.db.get_value( - "Asset Shift Factor", {"default": 1}, "name" - ) + existing_default_shift_factor = frappe.db.get_value("Asset Shift Factor", {"default": 1}, "name") if existing_default_shift_factor: frappe.throw( diff --git a/erpnext/assets/doctype/asset_value_adjustment/asset_value_adjustment.py b/erpnext/assets/doctype/asset_value_adjustment/asset_value_adjustment.py index 29e7a9bdfd6..fca9bc33365 100644 --- a/erpnext/assets/doctype/asset_value_adjustment/asset_value_adjustment.py +++ b/erpnext/assets/doctype/asset_value_adjustment/asset_value_adjustment.py @@ -61,7 +61,7 @@ class AssetValueAdjustment(Document): je.naming_series = depreciation_series je.posting_date = self.date je.company = self.company - je.remark = "Depreciation Entry against {0} worth {1}".format(self.asset, self.difference_amount) + je.remark = f"Depreciation Entry against {self.asset} worth {self.difference_amount}" je.finance_book = self.finance_book credit_entry = { diff --git a/erpnext/assets/doctype/asset_value_adjustment/test_asset_value_adjustment.py b/erpnext/assets/doctype/asset_value_adjustment/test_asset_value_adjustment.py index 8fdcd0c14df..7661e70fd17 100644 --- a/erpnext/assets/doctype/asset_value_adjustment/test_asset_value_adjustment.py +++ b/erpnext/assets/doctype/asset_value_adjustment/test_asset_value_adjustment.py @@ -20,9 +20,7 @@ class TestAssetValueAdjustment(unittest.TestCase): ) def test_current_asset_value(self): - pr = make_purchase_receipt( - item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location" - ) + pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location") asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, "name") asset_doc = frappe.get_doc("Asset", asset_name) @@ -49,9 +47,7 @@ class TestAssetValueAdjustment(unittest.TestCase): self.assertEqual(current_value, 100000.0) def test_asset_depreciation_value_adjustment(self): - pr = make_purchase_receipt( - item_code="Macbook Pro", qty=1, rate=120000.0, location="Test Location" - ) + pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=120000.0, location="Test Location") asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, "name") asset_doc = frappe.get_doc("Asset", asset_name) diff --git a/erpnext/assets/doctype/location/location.py b/erpnext/assets/doctype/location/location.py index 5bff3dd8c99..a4376a685d0 100644 --- a/erpnext/assets/doctype/location/location.py +++ b/erpnext/assets/doctype/location/location.py @@ -195,17 +195,15 @@ def get_children(doctype, parent=None, location=None, is_root=False): parent = "" return frappe.db.sql( - """ + f""" select name as value, is_group as expandable from `tabLocation` comp where - ifnull(parent_location, "")={parent} - """.format( - parent=frappe.db.escape(parent) - ), + ifnull(parent_location, "")={frappe.db.escape(parent)} + """, as_dict=1, ) diff --git a/erpnext/assets/doctype/location/test_location.py b/erpnext/assets/doctype/location/test_location.py index b8563cb0a29..3b5af61fd44 100644 --- a/erpnext/assets/doctype/location/test_location.py +++ b/erpnext/assets/doctype/location/test_location.py @@ -31,9 +31,7 @@ class TestLocation(unittest.TestCase): ordered_test_location_features = sorted( test_location_features, key=lambda x: x["properties"]["feature_of"] ) - ordered_formatted_locations = sorted( - formatted_locations, key=lambda x: x["properties"]["feature_of"] - ) + ordered_formatted_locations = sorted(formatted_locations, key=lambda x: x["properties"]["feature_of"]) self.assertEqual(ordered_formatted_locations, ordered_test_location_features) self.assertEqual(area, test_location.get("area")) diff --git a/erpnext/assets/report/fixed_asset_register/fixed_asset_register.py b/erpnext/assets/report/fixed_asset_register/fixed_asset_register.py index 4150494e22f..4ff04c80434 100644 --- a/erpnext/assets/report/fixed_asset_register/fixed_asset_register.py +++ b/erpnext/assets/report/fixed_asset_register/fixed_asset_register.py @@ -122,11 +122,7 @@ def get_data(filters): assets_record = frappe.db.get_all("Asset", filters=conditions, fields=fields) for asset in assets_record: - if ( - assets_linked_to_fb - and asset.calculate_depreciation - and asset.asset_id not in assets_linked_to_fb - ): + if assets_linked_to_fb and asset.calculate_depreciation and asset.asset_id not in assets_linked_to_fb: continue asset_value = get_asset_value_after_depreciation( @@ -241,9 +237,7 @@ def get_assets_linked_to_fb(filters): def get_asset_depreciation_amount_map(filters, finance_book): - start_date = ( - filters.from_date if filters.filter_based_on == "Date Range" else filters.year_start_date - ) + start_date = filters.from_date if filters.filter_based_on == "Date Range" else filters.year_start_date end_date = filters.to_date if filters.filter_based_on == "Date Range" else filters.year_end_date asset = frappe.qb.DocType("Asset") @@ -260,9 +254,7 @@ def get_asset_depreciation_amount_map(filters, finance_book): .join(company) .on(company.name == asset.company) .select(asset.name.as_("asset"), Sum(gle.debit).as_("depreciation_amount")) - .where( - gle.account == IfNull(aca.depreciation_expense_account, company.depreciation_expense_account) - ) + .where(gle.account == IfNull(aca.depreciation_expense_account, company.depreciation_expense_account)) .where(gle.debit != 0) .where(gle.is_cancelled == 0) .where(company.name == filters.company) @@ -281,9 +273,7 @@ def get_asset_depreciation_amount_map(filters, finance_book): else: query = query.where(asset.status.isin(["Sold", "Scrapped", "Capitalized", "Decapitalized"])) if finance_book: - query = query.where( - (gle.finance_book.isin([cstr(finance_book), ""])) | (gle.finance_book.isnull()) - ) + query = query.where((gle.finance_book.isin([cstr(finance_book), ""])) | (gle.finance_book.isnull())) else: query = query.where((gle.finance_book.isin([""])) | (gle.finance_book.isnull())) if filters.filter_based_on in ("Date Range", "Fiscal Year"): diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.py b/erpnext/buying/doctype/purchase_order/purchase_order.py index 9d4846056ea..58d7440211c 100644 --- a/erpnext/buying/doctype/purchase_order/purchase_order.py +++ b/erpnext/buying/doctype/purchase_order/purchase_order.py @@ -34,7 +34,7 @@ form_grid_templates = {"items": "templates/form_grid/item_grid.html"} class PurchaseOrder(BuyingController): def __init__(self, *args, **kwargs): - super(PurchaseOrder, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.status_updater = [ { "source_dt": "Purchase Order Item", @@ -54,7 +54,7 @@ class PurchaseOrder(BuyingController): self.set_onload("supplier_tds", supplier_tds) def validate(self): - super(PurchaseOrder, self).validate() + super().validate() self.set_status() @@ -90,7 +90,7 @@ class PurchaseOrder(BuyingController): if self.is_subcontracted: mri_compare_fields = [["project", "="]] - super(PurchaseOrder, self).validate_with_previous_doc( + super().validate_with_previous_doc( { "Supplier Quotation": { "ref_dn_field": "supplier_quotation", @@ -185,9 +185,7 @@ class PurchaseOrder(BuyingController): itemwise_min_order_qty = frappe._dict( frappe.db.sql( """select name, min_order_qty - from tabItem where name in ({0})""".format( - ", ".join(["%s"] * len(items)) - ), + from tabItem where name in ({})""".format(", ".join(["%s"] * len(items))), items, ) ) @@ -233,7 +231,9 @@ class PurchaseOrder(BuyingController): ) elif not frappe.get_value("Item", item.fg_item, "default_bom"): frappe.throw( - _("Row #{0}: Default BOM not found for FG Item {1}").format(item.idx, item.fg_item) + _("Row #{0}: Default BOM not found for FG Item {1}").format( + item.idx, item.fg_item + ) ) if not item.fg_item_qty: frappe.throw(_("Row #{0}: Finished Good Item Qty can not be zero").format(item.idx)) @@ -267,8 +267,9 @@ class PurchaseOrder(BuyingController): d.rate = d.base_rate / conversion_rate d.last_purchase_rate = d.rate else: - - item_last_purchase_rate = frappe.get_cached_value("Item", d.item_code, "last_purchase_rate") + item_last_purchase_rate = frappe.get_cached_value( + "Item", d.item_code, "last_purchase_rate" + ) if item_last_purchase_rate: d.base_price_list_rate = ( d.base_rate @@ -303,7 +304,7 @@ class PurchaseOrder(BuyingController): def check_modified_date(self): mod_db = frappe.db.sql("select modified from `tabPurchase Order` where name = %s", self.name) - date_diff = frappe.db.sql("select '%s' - '%s' " % (mod_db[0][0], cstr(self.modified))) + date_diff = frappe.db.sql(f"select '{mod_db[0][0]}' - '{cstr(self.modified)}' ") if date_diff and date_diff[0][0]: msgprint( @@ -322,7 +323,7 @@ class PurchaseOrder(BuyingController): clear_doctype_notifications(self) def on_submit(self): - super(PurchaseOrder, self).on_submit() + super().on_submit() if self.is_against_so(): self.update_status_updater() @@ -345,7 +346,7 @@ class PurchaseOrder(BuyingController): def on_cancel(self): self.ignore_linked_doctypes = ("GL Entry", "Payment Ledger Entry") - super(PurchaseOrder, self).on_cancel() + super().on_cancel() if self.is_against_so(): self.update_status_updater() @@ -485,7 +486,9 @@ def close_or_unclose_purchase_orders(names, status): po = frappe.get_doc("Purchase Order", name) if po.docstatus == 1: if status == "Closed": - if po.status not in ("Cancelled", "Closed") and (po.per_received < 100 or po.per_billed < 100): + if po.status not in ("Cancelled", "Closed") and ( + po.per_received < 100 or po.per_billed < 100 + ): po.update_status(status) else: if po.status == "Closed": @@ -661,7 +664,6 @@ def make_subcontracting_order(source_name, target_doc=None): def get_mapped_subcontracting_order(source_name, target_doc=None): - if target_doc and isinstance(target_doc, str): target_doc = json.loads(target_doc) for key in ["service_items", "items", "supplied_items"]: diff --git a/erpnext/buying/doctype/purchase_order/test_purchase_order.py b/erpnext/buying/doctype/purchase_order/test_purchase_order.py index 3a498ee271b..a95be2969f5 100644 --- a/erpnext/buying/doctype/purchase_order/test_purchase_order.py +++ b/erpnext/buying/doctype/purchase_order/test_purchase_order.py @@ -11,11 +11,13 @@ from frappe.utils.data import today from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry from erpnext.accounts.party import get_due_date_from_template -from erpnext.buying.doctype.purchase_order.purchase_order import make_inter_company_sales_order +from erpnext.buying.doctype.purchase_order.purchase_order import ( + make_inter_company_sales_order, + make_purchase_receipt, +) from erpnext.buying.doctype.purchase_order.purchase_order import ( make_purchase_invoice as make_pi_from_po, ) -from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt from erpnext.controllers.accounts_controller import InvalidQtyError, update_child_qty_rate from erpnext.manufacturing.doctype.blanket_order.test_blanket_order import make_blanket_order from erpnext.stock.doctype.item.test_item import make_item @@ -190,7 +192,7 @@ class TestPurchaseOrder(FrappeTestCase): po.items[0].qty = 4 po.save() po.submit() - pr = make_pr_against_po(po.name, 2) + make_pr_against_po(po.name, 2) po.load_from_db() existing_ordered_qty = get_ordered_qty() @@ -220,7 +222,7 @@ class TestPurchaseOrder(FrappeTestCase): po.items[0].qty = 4 po.save() po.submit() - pr = make_pr_against_po(po.name, 2) + make_pr_against_po(po.name, 2) po.reload() first_item_of_po = po.get("items")[0] @@ -461,9 +463,7 @@ class TestPurchaseOrder(FrappeTestCase): make_purchase_receipt as make_purchase_receipt_return, ) - pr1 = make_purchase_receipt_return( - is_return=1, return_against=pr.name, qty=-3, do_not_submit=True - ) + pr1 = make_purchase_receipt_return(is_return=1, return_against=pr.name, qty=-3, do_not_submit=True) pr1.items[0].purchase_order = po.name pr1.items[0].purchase_order_item = po.items[0].name pr1.submit() @@ -544,9 +544,7 @@ class TestPurchaseOrder(FrappeTestCase): self.assertEqual(po.payment_schedule[0].payment_amount, 2500.0) self.assertEqual(getdate(po.payment_schedule[0].due_date), getdate(po.transaction_date)) self.assertEqual(po.payment_schedule[1].payment_amount, 2500.0) - self.assertEqual( - getdate(po.payment_schedule[1].due_date), add_days(getdate(po.transaction_date), 30) - ) + self.assertEqual(getdate(po.payment_schedule[1].due_date), add_days(getdate(po.transaction_date), 30)) pi = make_pi_from_po(po.name) pi.save() @@ -556,9 +554,7 @@ class TestPurchaseOrder(FrappeTestCase): self.assertEqual(pi.payment_schedule[0].payment_amount, 2500.0) self.assertEqual(getdate(pi.payment_schedule[0].due_date), getdate(po.transaction_date)) self.assertEqual(pi.payment_schedule[1].payment_amount, 2500.0) - self.assertEqual( - getdate(pi.payment_schedule[1].due_date), add_days(getdate(po.transaction_date), 30) - ) + self.assertEqual(getdate(pi.payment_schedule[1].due_date), add_days(getdate(po.transaction_date), 30)) automatically_fetch_payment_terms(enable=0) def test_warehouse_company_validation(self): @@ -702,9 +698,9 @@ class TestPurchaseOrder(FrappeTestCase): raise Exception def test_default_payment_terms(self): - due_date = get_due_date_from_template( - "_Test Payment Term Template 1", "2023-02-03", None - ).strftime("%Y-%m-%d") + due_date = get_due_date_from_template("_Test Payment Term Template 1", "2023-02-03", None).strftime( + "%Y-%m-%d" + ) self.assertEqual(due_date, "2023-03-31") def test_terms_are_not_copied_if_automatically_fetch_payment_terms_is_unchecked(self): @@ -802,7 +798,7 @@ class TestPurchaseOrder(FrappeTestCase): Second Purchase Order should not add on to Blanket Orders Ordered Quantity. """ - bo = make_blanket_order(blanket_order_type="Purchasing", quantity=10, rate=10) + make_blanket_order(blanket_order_type="Purchasing", quantity=10, rate=10) po = create_purchase_order(item_code="_Test Item", qty=5, against_blanket_order=1) po_doc = frappe.get_doc("Purchase Order", po.get("name")) @@ -1101,15 +1097,11 @@ def create_pr_against_po(po, received_qty=4): def get_ordered_qty(item_code="_Test Item", warehouse="_Test Warehouse - _TC"): - return flt( - frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, "ordered_qty") - ) + return flt(frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, "ordered_qty")) def get_requested_qty(item_code="_Test Item", warehouse="_Test Warehouse - _TC"): - return flt( - frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, "indented_qty") - ) + return flt(frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, "indented_qty")) test_dependencies = ["BOM", "Item Price"] diff --git a/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py b/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py index 8226aa32c0e..73882d39cec 100644 --- a/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py +++ b/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py @@ -3,7 +3,6 @@ import json -from typing import Optional import frappe from frappe import _ @@ -27,7 +26,7 @@ class RequestforQuotation(BuyingController): self.validate_duplicate_supplier() self.validate_supplier_list() validate_for_items(self) - super(RequestforQuotation, self).set_qty_as_per_stock_uom() + super().set_qty_as_per_stock_uom() self.update_email_id() if self.docstatus < 1: @@ -253,7 +252,7 @@ class RequestforQuotation(BuyingController): def update_rfq_supplier_status(self, sup_name=None): for supplier in self.suppliers: - if sup_name == None or supplier.supplier == sup_name: + if sup_name is None or supplier.supplier == sup_name: quote_status = _("Received") for item in self.items: sqi_count = frappe.db.sql( @@ -284,9 +283,7 @@ def send_supplier_emails(rfq_name): def check_portal_enabled(reference_doctype): - if not frappe.db.get_value( - "Portal Menu Item", {"reference_doctype": reference_doctype}, "enabled" - ): + if not frappe.db.get_value("Portal Menu Item", {"reference_doctype": reference_doctype}, "enabled"): frappe.throw( _( "The Access to Request for Quotation From Portal is Disabled. To Allow Access, Enable it in Portal Settings." @@ -415,9 +412,9 @@ def create_rfq_items(sq_doc, supplier, data): def get_pdf( name: str, supplier: str, - print_format: Optional[str] = None, - language: Optional[str] = None, - letterhead: Optional[str] = None, + print_format: str | None = None, + language: str | None = None, + letterhead: str | None = None, ): doc = frappe.get_doc("Request for Quotation", name) if supplier: @@ -492,9 +489,7 @@ def get_item_from_material_requests_based_on_supplier(source_name, target_doc=No @frappe.whitelist() def get_supplier_tag(): filters = {"document_type": "Supplier"} - tags = list( - set(tag.tag for tag in frappe.get_all("Tag Link", filters=filters, fields=["tag"]) if tag) - ) + tags = list(set(tag.tag for tag in frappe.get_all("Tag Link", filters=filters, fields=["tag"]) if tag)) return tags @@ -507,7 +502,7 @@ def get_rfq_containing_supplier(doctype, txt, searchfield, start, page_len, filt conditions += "and rfq.name like '%%" + txt + "%%' " if filters.get("transaction_date"): - conditions += "and rfq.transaction_date = '{0}'".format(filters.get("transaction_date")) + conditions += "and rfq.transaction_date = '{}'".format(filters.get("transaction_date")) rfq_data = frappe.db.sql( f""" diff --git a/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py b/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py index 42fa1d923e1..da2a9d8a391 100644 --- a/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py +++ b/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py @@ -64,9 +64,7 @@ class TestRequestforQuotation(FrappeTestCase): rfq = make_request_for_quotation(supplier_data=supplier_wt_appos) - sq = make_supplier_quotation_from_rfq( - rfq.name, for_supplier=supplier_wt_appos[0].get("supplier") - ) + sq = make_supplier_quotation_from_rfq(rfq.name, for_supplier=supplier_wt_appos[0].get("supplier")) sq.submit() frappe.form_dict.name = rfq.name @@ -97,9 +95,7 @@ class TestRequestforQuotation(FrappeTestCase): row = item.append("uoms", {"uom": "Kg", "conversion_factor": 2}) row.db_update() - rfq = make_request_for_quotation( - item_code="_Test Multi UOM RFQ Item", uom="Kg", conversion_factor=2 - ) + rfq = make_request_for_quotation(item_code="_Test Multi UOM RFQ Item", uom="Kg", conversion_factor=2) rfq.get("items")[0].rate = 100 rfq.supplier = rfq.suppliers[0].supplier diff --git a/erpnext/buying/doctype/supplier/supplier.py b/erpnext/buying/doctype/supplier/supplier.py index 91061c8fe8b..2774f1aeffb 100644 --- a/erpnext/buying/doctype/supplier/supplier.py +++ b/erpnext/buying/doctype/supplier/supplier.py @@ -11,9 +11,8 @@ from frappe.contacts.address_and_contact import ( ) from frappe.model.naming import set_name_by_naming_series, set_name_from_naming_options -from erpnext.accounts.party import ( # noqa +from erpnext.accounts.party import ( get_dashboard_info, - get_timeline_data, validate_party_accounts, ) from erpnext.utilities.transaction_base import TransactionBase @@ -154,6 +153,6 @@ def get_supplier_primary_contact(doctype, txt, searchfield, start, page_len, fil .where( (dynamic_link.link_name == supplier) & (dynamic_link.link_doctype == "Supplier") - & (contact.name.like("%{0}%".format(txt))) + & (contact.name.like(f"%{txt}%")) ) ).run(as_dict=False) diff --git a/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py b/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py index e27fbe8aaa2..492a73c3a85 100644 --- a/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py +++ b/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py @@ -15,7 +15,7 @@ form_grid_templates = {"items": "templates/form_grid/item_grid.html"} class SupplierQuotation(BuyingController): def validate(self): - super(SupplierQuotation, self).validate() + super().validate() if not self.status: self.status = "Draft" @@ -41,7 +41,7 @@ class SupplierQuotation(BuyingController): pass def validate_with_previous_doc(self): - super(SupplierQuotation, self).validate_with_previous_doc( + super().validate_with_previous_doc( { "Material Request": { "ref_dn_field": "prevdoc_docname", diff --git a/erpnext/buying/doctype/supplier_scorecard/supplier_scorecard.py b/erpnext/buying/doctype/supplier_scorecard/supplier_scorecard.py index 58da8512951..8b2026aec72 100644 --- a/erpnext/buying/doctype/supplier_scorecard/supplier_scorecard.py +++ b/erpnext/buying/doctype/supplier_scorecard/supplier_scorecard.py @@ -34,7 +34,11 @@ class SupplierScorecard(Document): for c2 in self.standings: if c1 != c2: if c1.max_grade > c2.min_grade and c1.min_grade < c2.max_grade: - throw(_("Overlap in scoring between {0} and {1}").format(c1.standing_name, c2.standing_name)) + throw( + _("Overlap in scoring between {0} and {1}").format( + c1.standing_name, c2.standing_name + ) + ) if c2.min_grade == score: score = c2.max_grade if score < 100: @@ -45,7 +49,6 @@ class SupplierScorecard(Document): ) def validate_criteria_weights(self): - weight = 0 for c in self.criteria: weight += c.weight @@ -164,7 +167,6 @@ def refresh_scorecards(): @frappe.whitelist() def make_all_scorecards(docname): - sc = frappe.get_doc("Supplier Scorecard", docname) supplier = frappe.get_doc("Supplier", sc.supplier) diff --git a/erpnext/buying/doctype/supplier_scorecard_criteria/supplier_scorecard_criteria.py b/erpnext/buying/doctype/supplier_scorecard_criteria/supplier_scorecard_criteria.py index ab7d4879c43..7433ffff793 100644 --- a/erpnext/buying/doctype/supplier_scorecard_criteria/supplier_scorecard_criteria.py +++ b/erpnext/buying/doctype/supplier_scorecard_criteria/supplier_scorecard_criteria.py @@ -29,8 +29,8 @@ class SupplierScorecardCriteria(Document): regex = r"\{(.*?)\}" mylist = re.finditer(regex, test_formula, re.MULTILINE | re.DOTALL) - for dummy1, match in enumerate(mylist): - for dummy2 in range(0, len(match.groups())): + for _dummy1, match in enumerate(mylist): + for _dummy2 in range(0, len(match.groups())): test_formula = test_formula.replace("{" + match.group(1) + "}", "0") try: @@ -64,8 +64,8 @@ def _get_variables(criteria): regex = r"\{(.*?)\}" mylist = re.finditer(regex, criteria.formula, re.MULTILINE | re.DOTALL) - for dummy1, match in enumerate(mylist): - for dummy2 in range(0, len(match.groups())): + for _dummy1, match in enumerate(mylist): + for _dummy2 in range(0, len(match.groups())): try: var = frappe.db.sql( """ @@ -80,6 +80,8 @@ def _get_variables(criteria): )[0] my_variables.append(var) except Exception: - frappe.throw(_("Unable to find variable:") + " " + str(match.group(1)), InvalidFormulaVariable) + frappe.throw( + _("Unable to find variable:") + " " + str(match.group(1)), InvalidFormulaVariable + ) return my_variables diff --git a/erpnext/buying/doctype/supplier_scorecard_period/supplier_scorecard_period.py b/erpnext/buying/doctype/supplier_scorecard_period/supplier_scorecard_period.py index a8b76db0931..c54c6aadd6a 100644 --- a/erpnext/buying/doctype/supplier_scorecard_period/supplier_scorecard_period.py +++ b/erpnext/buying/doctype/supplier_scorecard_period/supplier_scorecard_period.py @@ -21,7 +21,6 @@ class SupplierScorecardPeriod(Document): self.calculate_score() def validate_criteria_weights(self): - weight = 0 for c in self.criteria: weight += c.weight @@ -44,14 +43,17 @@ class SupplierScorecardPeriod(Document): crit.score = min( crit.max_score, max( - 0, frappe.safe_eval(self.get_eval_statement(crit.formula), None, {"max": max, "min": min}) + 0, + frappe.safe_eval( + self.get_eval_statement(crit.formula), None, {"max": max, "min": min} + ), ), ) except Exception: frappe.throw( - _("Could not solve criteria score function for {0}. Make sure the formula is valid.").format( - crit.criteria_name - ), + _( + "Could not solve criteria score function for {0}. Make sure the formula is valid." + ).format(crit.criteria_name), frappe.ValidationError, ) crit.score = 0 @@ -82,7 +84,7 @@ class SupplierScorecardPeriod(Document): if var.value: if var.param_name in my_eval_statement: my_eval_statement = my_eval_statement.replace( - "{" + var.param_name + "}", "{:.2f}".format(var.value) + "{" + var.param_name + "}", f"{var.value:.2f}" ) else: if var.param_name in my_eval_statement: diff --git a/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py b/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py index 9b53421319d..ebceb7f655a 100644 --- a/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py +++ b/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py @@ -2,17 +2,8 @@ # For license information, please see license.txt -from datetime import datetime - -import frappe from frappe.tests.utils import FrappeTestCase -from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt -from erpnext.buying.report.procurement_tracker.procurement_tracker import execute -from erpnext.stock.doctype.material_request.material_request import make_purchase_order -from erpnext.stock.doctype.material_request.test_material_request import make_material_request -from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse - class TestProcurementTracker(FrappeTestCase): pass diff --git a/erpnext/buying/report/purchase_order_analysis/purchase_order_analysis.py b/erpnext/buying/report/purchase_order_analysis/purchase_order_analysis.py index b6e46302ffe..b23c3f50b9a 100644 --- a/erpnext/buying/report/purchase_order_analysis/purchase_order_analysis.py +++ b/erpnext/buying/report/purchase_order_analysis/purchase_order_analysis.py @@ -68,9 +68,7 @@ def get_data(filters): po.company, po_item.name, ) - .where( - (po_item.parent == po.name) & (po.status.notin(("Stopped", "Closed"))) & (po.docstatus == 1) - ) + .where((po_item.parent == po.name) & (po.status.notin(("Stopped", "Closed"))) & (po.docstatus == 1)) .groupby(po_item.name) .orderby(po.transaction_date) ) @@ -80,9 +78,7 @@ def get_data(filters): query = query.where(po[field] == filters.get(field)) if filters.get("from_date") and filters.get("to_date"): - query = query.where( - po.transaction_date.between(filters.get("from_date"), filters.get("to_date")) - ) + query = query.where(po.transaction_date.between(filters.get("from_date"), filters.get("to_date"))) if filters.get("status"): query = query.where(po.status.isin(filters.get("status"))) @@ -114,7 +110,7 @@ def prepare_data(data, filters): if filters.get("group_by_po"): po_name = row["purchase_order"] - if not po_name in purchase_order_map: + if po_name not in purchase_order_map: # create an entry row_copy = copy.deepcopy(row) purchase_order_map[po_name] = row_copy diff --git a/erpnext/buying/report/requested_items_to_order_and_receive/requested_items_to_order_and_receive.py b/erpnext/buying/report/requested_items_to_order_and_receive/requested_items_to_order_and_receive.py index 07187352eb7..55189a722a3 100644 --- a/erpnext/buying/report/requested_items_to_order_and_receive/requested_items_to_order_and_receive.py +++ b/erpnext/buying/report/requested_items_to_order_and_receive/requested_items_to_order_and_receive.py @@ -57,9 +57,7 @@ def get_data(filters): "qty_to_receive" ), Sum(Coalesce(mr_item.received_qty, 0)).as_("received_qty"), - (Sum(Coalesce(mr_item.stock_qty, 0)) - Sum(Coalesce(mr_item.ordered_qty, 0))).as_( - "qty_to_order" - ), + (Sum(Coalesce(mr_item.stock_qty, 0)) - Sum(Coalesce(mr_item.ordered_qty, 0))).as_("qty_to_order"), mr_item.item_name, mr_item.description, mr.company, @@ -110,7 +108,7 @@ def prepare_data(data, filters): for row in data: # item wise map for charts - if not row["item_code"] in item_qty_map: + if row["item_code"] not in item_qty_map: item_qty_map[row["item_code"]] = { "qty": flt(row["stock_qty"], precision), "stock_qty": flt(row["stock_qty"], precision), @@ -127,7 +125,7 @@ def prepare_data(data, filters): if filters.get("group_by_mr"): # consolidated material request map for group by filter - if not row["material_request"] in material_request_map: + if row["material_request"] not in material_request_map: # create an entry with mr as key row_copy = copy.deepcopy(row) material_request_map[row["material_request"]] = row_copy diff --git a/erpnext/buying/report/subcontract_order_summary/subcontract_order_summary.py b/erpnext/buying/report/subcontract_order_summary/subcontract_order_summary.py index 0213051aeb7..130cadaabc1 100644 --- a/erpnext/buying/report/subcontract_order_summary/subcontract_order_summary.py +++ b/erpnext/buying/report/subcontract_order_summary/subcontract_order_summary.py @@ -112,7 +112,7 @@ def prepare_subcontracted_data(orders, supplied_items): def get_subcontracted_data(order_details, data): - for key, details in order_details.items(): + for _key, details in order_details.items(): res = details.order_item for index, row in enumerate(details.supplied_items): if index != 0: diff --git a/erpnext/buying/report/subcontracted_item_to_be_received/test_subcontracted_item_to_be_received.py b/erpnext/buying/report/subcontracted_item_to_be_received/test_subcontracted_item_to_be_received.py index d13d9701f31..d90be66af94 100644 --- a/erpnext/buying/report/subcontracted_item_to_be_received/test_subcontracted_item_to_be_received.py +++ b/erpnext/buying/report/subcontracted_item_to_be_received/test_subcontracted_item_to_be_received.py @@ -62,7 +62,9 @@ class TestSubcontractedItemToBeReceived(FrappeTestCase): "from_date": frappe.utils.get_datetime( frappe.utils.add_to_date(sco.transaction_date, days=-10) ), - "to_date": frappe.utils.get_datetime(frappe.utils.add_to_date(sco.transaction_date, days=10)), + "to_date": frappe.utils.get_datetime( + frappe.utils.add_to_date(sco.transaction_date, days=10) + ), } ) ) diff --git a/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/test_subcontracted_raw_materials_to_be_transferred.py b/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/test_subcontracted_raw_materials_to_be_transferred.py index 160295776b1..7b4ec5c2f39 100644 --- a/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/test_subcontracted_raw_materials_to_be_transferred.py +++ b/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/test_subcontracted_raw_materials_to_be_transferred.py @@ -48,7 +48,9 @@ class TestSubcontractedItemToBeTransferred(FrappeTestCase): "from_date": frappe.utils.get_datetime( frappe.utils.add_to_date(sco.transaction_date, days=-10) ), - "to_date": frappe.utils.get_datetime(frappe.utils.add_to_date(sco.transaction_date, days=10)), + "to_date": frappe.utils.get_datetime( + frappe.utils.add_to_date(sco.transaction_date, days=10) + ), } ) ) diff --git a/erpnext/buying/report/supplier_quotation_comparison/supplier_quotation_comparison.py b/erpnext/buying/report/supplier_quotation_comparison/supplier_quotation_comparison.py index 01ff28d8103..684cd3a0f9e 100644 --- a/erpnext/buying/report/supplier_quotation_comparison/supplier_quotation_comparison.py +++ b/erpnext/buying/report/supplier_quotation_comparison/supplier_quotation_comparison.py @@ -82,18 +82,14 @@ def prepare_data(supplier_quotation_data, filters): group_wise_map = defaultdict(list) supplier_qty_price_map = {} - group_by_field = ( - "supplier_name" if filters.get("group_by") == "Group by Supplier" else "item_code" - ) + group_by_field = "supplier_name" if filters.get("group_by") == "Group by Supplier" else "item_code" company_currency = frappe.db.get_default("currency") float_precision = cint(frappe.db.get_default("float_precision")) or 2 for data in supplier_quotation_data: group = data.get(group_by_field) # get item or supplier value for this row - supplier_currency = frappe.db.get_value( - "Supplier", data.get("supplier_name"), "default_currency" - ) + supplier_currency = frappe.db.get_value("Supplier", data.get("supplier_name"), "default_currency") if supplier_currency: exchange_rate = get_exchange_rate(supplier_currency, company_currency) @@ -126,7 +122,7 @@ def prepare_data(supplier_quotation_data, filters): # map for chart preparation of the form {'supplier1': {'qty': 'price'}} supplier = data.get("supplier_name") if filters.get("item_code"): - if not supplier in supplier_qty_price_map: + if supplier not in supplier_qty_price_map: supplier_qty_price_map[supplier] = {} supplier_qty_price_map[supplier][row["qty"]] = row["price"] @@ -169,7 +165,7 @@ def prepare_chart_data(suppliers, qty_list, supplier_qty_price_map): for supplier in suppliers: entry = supplier_qty_price_map[supplier] for qty in qty_list: - if not qty in data_points_map: + if qty not in data_points_map: data_points_map[qty] = [] if qty in entry: data_points_map[qty].append(entry[qty]) diff --git a/erpnext/buying/utils.py b/erpnext/buying/utils.py index e904af0dce3..1d708b36980 100644 --- a/erpnext/buying/utils.py +++ b/erpnext/buying/utils.py @@ -3,7 +3,6 @@ import json -from typing import Dict import frappe from frappe import _ @@ -87,7 +86,7 @@ def set_stock_levels(row) -> None: row.set(field, qty_data[field]) -def validate_item_and_get_basic_data(row) -> Dict: +def validate_item_and_get_basic_data(row) -> dict: item = frappe.db.get_values( "Item", filters={"name": row.item_code}, @@ -101,12 +100,7 @@ def validate_item_and_get_basic_data(row) -> Dict: def validate_stock_item_warehouse(row, item) -> None: - if ( - item.is_stock_item == 1 - and row.qty - and not row.warehouse - and not row.get("delivered_by_supplier") - ): + if item.is_stock_item == 1 and row.qty and not row.warehouse and not row.get("delivered_by_supplier"): frappe.throw( _("Row #{1}: Warehouse is mandatory for stock Item {0}").format( frappe.bold(row.item_code), row.idx @@ -118,9 +112,7 @@ def check_on_hold_or_closed_status(doctype, docname) -> None: status = frappe.db.get_value(doctype, docname, "status") if status in ("Closed", "On Hold"): - frappe.throw( - _("{0} {1} status is {2}").format(doctype, docname, status), frappe.InvalidStatusError - ) + frappe.throw(_("{0} {1} status is {2}").format(doctype, docname, status), frappe.InvalidStatusError) @frappe.whitelist() diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py index 534bddcd643..dd4a247e0a1 100644 --- a/erpnext/controllers/accounts_controller.py +++ b/erpnext/controllers/accounts_controller.py @@ -95,7 +95,7 @@ force_item_fields = ( class AccountsController(TransactionBase): def __init__(self, *args, **kwargs): - super(AccountsController, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def get_print_settings(self): print_setting_fields = [] @@ -200,14 +200,13 @@ class AccountsController(TransactionBase): self.validate_return_against_account() if self.doctype in ["Purchase Invoice", "Sales Invoice"]: - if invalid_advances := [ - x for x in self.advances if not x.reference_type or not x.reference_name - ]: + if invalid_advances := [x for x in self.advances if not x.reference_type or not x.reference_name]: frappe.throw( _( "Rows: {0} in {1} section are Invalid. Reference Name should point to a valid Payment Entry or Journal Entry." ).format( - frappe.bold(comma_and([x.idx for x in invalid_advances])), frappe.bold(_("Advance Payments")) + frappe.bold(comma_and([x.idx for x in invalid_advances])), + frappe.bold(_("Advance Payments")), ) ) @@ -352,9 +351,7 @@ class AccountsController(TransactionBase): ) def validate_return_against_account(self): - if ( - self.doctype in ["Sales Invoice", "Purchase Invoice"] and self.is_return and self.return_against - ): + if self.doctype in ["Sales Invoice", "Purchase Invoice"] and self.is_return and self.return_against: cr_dr_account_field = "debit_to" if self.doctype == "Sales Invoice" else "credit_to" cr_dr_account_label = "Debit To" if self.doctype == "Sales Invoice" else "Credit To" cr_dr_account = self.get(cr_dr_account_field) @@ -387,11 +384,7 @@ class AccountsController(TransactionBase): item.set(field_map.get(self.doctype), default_deferred_account) def validate_auto_repeat_subscription_dates(self): - if ( - self.get("from_date") - and self.get("to_date") - and getdate(self.from_date) > getdate(self.to_date) - ): + if self.get("from_date") and self.get("to_date") and getdate(self.from_date) > getdate(self.to_date): frappe.throw(_("To Date cannot be before From Date"), title=_("Invalid Auto Repeat Date")) def validate_deferred_start_and_end_date(self): @@ -399,11 +392,15 @@ class AccountsController(TransactionBase): if d.get("enable_deferred_revenue") or d.get("enable_deferred_expense"): if not (d.service_start_date and d.service_end_date): frappe.throw( - _("Row #{0}: Service Start and End Date is required for deferred accounting").format(d.idx) + _("Row #{0}: Service Start and End Date is required for deferred accounting").format( + d.idx + ) ) elif getdate(d.service_start_date) > getdate(d.service_end_date): frappe.throw( - _("Row #{0}: Service Start Date cannot be greater than Service End Date").format(d.idx) + _("Row #{0}: Service Start Date cannot be greater than Service End Date").format( + d.idx + ) ) elif getdate(self.posting_date) > getdate(d.service_end_date): frappe.throw( @@ -462,7 +459,9 @@ class AccountsController(TransactionBase): if not self.cash_bank_account: # show message that the amount is not paid frappe.throw( - _("Note: Payment Entry will not be created since 'Cash or Bank Account' was not specified") + _( + "Note: Payment Entry will not be created since 'Cash or Bank Account' was not specified" + ) ) if cint(self.is_return) and self.grand_total > self.paid_amount: @@ -506,7 +505,11 @@ class AccountsController(TransactionBase): if date_field and self.get(date_field): validate_fiscal_year( - self.get(date_field), self.fiscal_year, self.company, self.meta.get_label(date_field), self + self.get(date_field), + self.fiscal_year, + self.company, + self.meta.get_label(date_field), + self, ) def validate_party_accounts(self): @@ -576,7 +579,9 @@ class AccountsController(TransactionBase): if tax_updated: frappe.msgprint( - _("Disabled tax included prices since this {} is an internal transfer").format(self.doctype), + _("Disabled tax included prices since this {} is an internal transfer").format( + self.doctype + ), alert=1, ) @@ -667,7 +672,7 @@ class AccountsController(TransactionBase): parent_dict[fieldname] = self.get(fieldname) if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]: - document_type = "{} Item".format(self.doctype) + document_type = f"{self.doctype} Item" parent_dict.update({"document_type": document_type}) # party_name field used for customer in quotation @@ -708,7 +713,9 @@ class AccountsController(TransactionBase): if item.get(fieldname) is None or fieldname in force_item_fields: item.set(fieldname, value) - elif fieldname in ["cost_center", "conversion_factor"] and not item.get(fieldname): + elif fieldname in ["cost_center", "conversion_factor"] and not item.get( + fieldname + ): item.set(fieldname, value) elif fieldname == "serial_no": @@ -744,7 +751,8 @@ class AccountsController(TransactionBase): # Items add via promotional scheme may not have cost center set if hasattr(item, "cost_center") and not item.get("cost_center"): item.set( - "cost_center", self.get("cost_center") or erpnext.get_default_cost_center(self.company) + "cost_center", + self.get("cost_center") or erpnext.get_default_cost_center(self.company), ) if ret.get("pricing_rules"): @@ -871,9 +879,7 @@ class AccountsController(TransactionBase): if self.taxes_and_charges and frappe.get_cached_value( taxes_and_charges_doctype, self.taxes_and_charges, "disabled" ): - frappe.throw( - _("{0} '{1}' is disabled").format(taxes_and_charges_doctype, self.taxes_and_charges) - ) + frappe.throw(_("{0} '{1}' is disabled").format(taxes_and_charges_doctype, self.taxes_and_charges)) def validate_tax_account_company(self): for d in self.get("taxes"): @@ -998,9 +1004,8 @@ class AccountsController(TransactionBase): self.set(parentfield, self.get(parentfield, {"allocated_amount": ["not in", [0, None, ""]]})) frappe.db.sql( - """delete from `tab%s` where parentfield=%s and parent = %s - and allocated_amount = 0""" - % (childtype, "%s", "%s"), + """delete from `tab{}` where parentfield={} and parent = {} + and allocated_amount = 0""".format(childtype, "%s", "%s"), (parentfield, self.name), ) @@ -1088,9 +1093,7 @@ class AccountsController(TransactionBase): return res def is_inclusive_tax(self): - is_inclusive = cint( - frappe.db.get_single_value("Accounts Settings", "show_inclusive_tax_in_print") - ) + is_inclusive = cint(frappe.db.get_single_value("Accounts Settings", "show_inclusive_tax_in_print")) if is_inclusive: is_inclusive = 0 @@ -1133,7 +1136,6 @@ class AccountsController(TransactionBase): for d in self.get("advances"): advance_exchange_rate = d.ref_exchange_rate if d.allocated_amount and self.conversion_rate != advance_exchange_rate: - base_allocated_amount_in_ref_rate = advance_exchange_rate * d.allocated_amount base_allocated_amount_in_inv_rate = self.conversion_rate * d.allocated_amount difference = base_allocated_amount_in_ref_rate - base_allocated_amount_in_inv_rate @@ -1179,7 +1181,7 @@ class AccountsController(TransactionBase): return False def make_exchange_gain_loss_journal( - self, args: dict = None, dimensions_dict: dict = None + self, args: dict | None = None, dimensions_dict: dict | None = None ) -> None: """ Make Exchange Gain/Loss journal for Invoices and Payments @@ -1199,7 +1201,6 @@ class AccountsController(TransactionBase): flt(arg.get("difference_amount", 0), precision) != 0 or flt(arg.get("exchange_gain_loss", 0), precision) != 0 ) and arg.get("difference_account"): - party_account = arg.get("account") gain_loss_account = arg.get("difference_account") difference_amount = arg.get("difference_amount") or arg.get("exchange_gain_loss") @@ -1250,8 +1251,8 @@ class AccountsController(TransactionBase): gain_loss_to_book = [x for x in self.references if x.exchange_gain_loss != 0] booked = [] if gain_loss_to_book: - vtypes = [x.reference_doctype for x in gain_loss_to_book] - vnames = [x.reference_name for x in gain_loss_to_book] + [x.reference_doctype for x in gain_loss_to_book] + [x.reference_name for x in gain_loss_to_book] je = qb.DocType("Journal Entry") jea = qb.DocType("Journal Entry Account") parents = ( @@ -1391,7 +1392,9 @@ class AccountsController(TransactionBase): "allocated_amount": flt(d.allocated_amount), "precision": d.precision("advance_amount"), "exchange_rate": ( - self.conversion_rate if self.party_account_currency != self.company_currency else 1 + self.conversion_rate + if self.party_account_currency != self.company_currency + else 1 ), "grand_total": ( self.base_grand_total @@ -1574,9 +1577,12 @@ class AccountsController(TransactionBase): "account": item.discount_account, "against": supplier_or_customer, dr_or_cr: flt( - discount_amount * self.get("conversion_rate"), item.precision("discount_amount") + discount_amount * self.get("conversion_rate"), + item.precision("discount_amount"), + ), + dr_or_cr + "_in_account_currency": flt( + discount_amount, item.precision("discount_amount") ), - dr_or_cr + "_in_account_currency": flt(discount_amount, item.precision("discount_amount")), "cost_center": item.cost_center, "project": item.project, }, @@ -1592,10 +1598,12 @@ class AccountsController(TransactionBase): "account": income_or_expense_account, "against": supplier_or_customer, rev_dr_cr: flt( - discount_amount * self.get("conversion_rate"), item.precision("discount_amount") + discount_amount * self.get("conversion_rate"), + item.precision("discount_amount"), + ), + rev_dr_cr + "_in_account_currency": flt( + discount_amount, item.precision("discount_amount") ), - rev_dr_cr - + "_in_account_currency": flt(discount_amount, item.precision("discount_amount")), "cost_center": item.cost_center, "project": item.project or self.project, }, @@ -1635,9 +1643,7 @@ class AccountsController(TransactionBase): total_overbilled_amt = 0.0 reference_names = [d.get(item_ref_dn) for d in self.get("items") if d.get(item_ref_dn)] - reference_details = self.get_billing_reference_details( - reference_names, ref_dt + " Item", based_on - ) + reference_details = self.get_billing_reference_details(reference_names, ref_dt + " Item", based_on) for item in self.get("items"): if not item.get(item_ref_dn): @@ -1823,17 +1829,13 @@ class AccountsController(TransactionBase): def raise_missing_debit_credit_account_error(self, party_type, party): """Raise an error if debit to/credit to account does not exist.""" - db_or_cr = ( - frappe.bold("Debit To") if self.doctype == "Sales Invoice" else frappe.bold("Credit To") - ) + db_or_cr = frappe.bold("Debit To") if self.doctype == "Sales Invoice" else frappe.bold("Credit To") rec_or_pay = "Receivable" if self.doctype == "Sales Invoice" else "Payable" link_to_party = frappe.utils.get_link_to_form(party_type, party) link_to_company = frappe.utils.get_link_to_form("Company", self.company) - message = _("{0} Account not found against Customer {1}.").format( - db_or_cr, frappe.bold(party) or "" - ) + message = _("{0} Account not found against Customer {1}.").format(db_or_cr, frappe.bold(party) or "") message += "
" + _("Please set one of the following:") + "
" message += ( "