refactor(treewide): formatting and ruff fixes, + manually enabled F401
Signed-off-by: Akhil Narang <me@akhilnarang.dev>
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 3b83c7c..d90e09e 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -95,7 +95,7 @@
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 = []
@@ -214,14 +214,13 @@
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")),
)
)
@@ -387,9 +386,7 @@
frappe.delete_doc("Batch", row.name)
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)
@@ -422,11 +419,7 @@
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):
@@ -434,11 +427,15 @@
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(
@@ -497,7 +494,9 @@
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:
@@ -541,7 +540,11 @@
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):
@@ -611,7 +614,9 @@
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,
)
@@ -704,7 +709,7 @@
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
@@ -743,7 +748,9 @@
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":
@@ -779,7 +786,8 @@
# 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"):
@@ -904,7 +912,7 @@
if isinstance(item_tax_rate, str):
item_tax_rate = parse_json(item_tax_rate)
- for account_head, rate in item_tax_rate.items():
+ for account_head, _rate in item_tax_rate.items():
row = self.get_tax_row(account_head)
if not row:
@@ -932,9 +940,7 @@
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"):
@@ -1108,9 +1114,8 @@
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),
)
@@ -1206,9 +1211,7 @@
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
@@ -1251,7 +1254,6 @@
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
@@ -1324,7 +1326,7 @@
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
@@ -1344,7 +1346,6 @@
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")
@@ -1395,8 +1396,8 @@
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 = (
@@ -1509,7 +1510,9 @@
"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
@@ -1670,9 +1673,12 @@
"account": item.discount_account,
"against": self.customer,
"debit": flt(
- discount_amount * self.get("conversion_rate"), item.precision("discount_amount")
+ discount_amount * self.get("conversion_rate"),
+ item.precision("discount_amount"),
),
- "debit_in_account_currency": flt(discount_amount, item.precision("discount_amount")),
+ "debit_in_account_currency": flt(
+ discount_amount, item.precision("discount_amount")
+ ),
"cost_center": item.cost_center,
"project": item.project,
},
@@ -1688,9 +1694,12 @@
"account": income_account,
"against": self.customer,
"credit": flt(
- discount_amount * self.get("conversion_rate"), item.precision("discount_amount")
+ discount_amount * self.get("conversion_rate"),
+ item.precision("discount_amount"),
),
- "credit_in_account_currency": flt(discount_amount, item.precision("discount_amount")),
+ "credit_in_account_currency": flt(
+ discount_amount, item.precision("discount_amount")
+ ),
"cost_center": item.cost_center,
"project": item.project or self.project,
},
@@ -1730,9 +1739,7 @@
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):
@@ -1919,9 +1926,7 @@
self.set_advance_payment_status(advance_paid, order_total)
- def set_advance_payment_status(
- self, advance_paid: float | None = None, order_total: float | None = None
- ):
+ def set_advance_payment_status(self, advance_paid: float | None = None, order_total: float | None = None):
new_status = None
# if money is paid set the paid states
if advance_paid:
@@ -1957,17 +1962,13 @@
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 += "<br>" + _("Please set one of the following:") + "<br>"
message += (
"<br><ul><li>"
@@ -2020,7 +2021,6 @@
and party_account_currency != self.company_currency
and self.currency != party_account_currency
):
-
frappe.throw(
_("Accounting Entry for {0}: {1} can only be made in currency: {2}").format(
party_type, party, party_account_currency
@@ -2041,9 +2041,7 @@
party_type, party = self.get_party()
party_gle_currency = get_party_gle_currency(party_type, party, self.company)
- party_account = (
- self.get("debit_to") if self.doctype == "Sales Invoice" else self.get("credit_to")
- )
+ party_account = self.get("debit_to") if self.doctype == "Sales Invoice" else self.get("credit_to")
party_account_currency = get_account_currency(party_account)
allow_multi_currency_invoices_against_single_party_account = frappe.db.get_singles_value(
"Accounts Settings", "allow_multi_currency_invoices_against_single_party_account"
@@ -2066,10 +2064,8 @@
consider_for_total_advance = True
if adv.reference_name == linked_doc_name:
frappe.db.sql(
- """delete from `tab{0} Advance`
- where name = %s""".format(
- self.doctype
- ),
+ f"""delete from `tab{self.doctype} Advance`
+ where name = %s""",
adv.name,
)
consider_for_total_advance = False
@@ -2281,7 +2277,9 @@
for d in self.get("payment_schedule"):
if self.doctype == "Sales Order" and getdate(d.due_date) < getdate(self.transaction_date):
frappe.throw(
- _("Row {0}: Due Date in the Payment Terms table cannot be before Posting Date").format(d.idx)
+ _("Row {0}: Due Date in the Payment Terms table cannot be before Posting Date").format(
+ d.idx
+ )
)
elif d.due_date in dates:
li.append(_("{0} in row {1}").format(d.due_date, d.idx))
@@ -2289,9 +2287,7 @@
if li:
duplicates = "<br>" + "<br>".join(li)
- frappe.throw(
- _("Rows with duplicate due dates in other rows were found: {0}").format(duplicates)
- )
+ frappe.throw(_("Rows with duplicate due dates in other rows were found: {0}").format(duplicates))
def validate_payment_schedule_amount(self):
if (self.doctype == "Sales Invoice" and self.is_pos) or self.get("is_opening") == "Yes":
@@ -2414,7 +2410,7 @@
jv.voucher_type = "Journal Entry"
jv.posting_date = self.posting_date
jv.company = self.company
- jv.remark = "Adjustment for {} {}".format(self.doctype, self.name)
+ jv.remark = f"Adjustment for {self.doctype} {self.name}"
reconcilation_entry = frappe._dict()
advance_entry = frappe._dict()
@@ -2424,9 +2420,7 @@
reconcilation_entry.party = secondary_party
reconcilation_entry.reference_type = self.doctype
reconcilation_entry.reference_name = self.name
- reconcilation_entry.cost_center = self.cost_center or erpnext.get_default_cost_center(
- self.company
- )
+ reconcilation_entry.cost_center = self.cost_center or erpnext.get_default_cost_center(self.company)
advance_entry.account = primary_account
advance_entry.party_type = primary_party_type
@@ -2472,7 +2466,7 @@
def check_if_fields_updated(self, fields_to_check, child_tables):
# Check if any field affecting accounting entry is altered
doc_before_update = self.get_doc_before_save()
- accounting_dimensions = get_accounting_dimensions() + ["cost_center", "project"]
+ accounting_dimensions = [*get_accounting_dimensions(), "cost_center", "project"]
# Parent Level Accounts excluding party account
fields_to_check += accounting_dimensions
@@ -2505,9 +2499,7 @@
@frappe.whitelist()
def get_tax_rate(account_head):
- return frappe.get_cached_value(
- "Account", account_head, ["tax_rate", "account_name"], as_dict=True
- )
+ return frappe.get_cached_value("Account", account_head, ["tax_rate", "account_name"], as_dict=True)
@frappe.whitelist()
@@ -2537,7 +2529,7 @@
tax_master = frappe.get_doc(master_doctype, master_name)
taxes_and_charges = []
- for i, tax in enumerate(tax_master.get("taxes")):
+ for _i, tax in enumerate(tax_master.get("taxes")):
tax = tax.as_dict()
for fieldname in default_fields + child_table_fields:
@@ -2656,9 +2648,7 @@
):
if (not conversion_rate) and (account_currency != company_currency):
frappe.throw(
- _("Account: {0} with currency: {1} can not be selected").format(
- gl_dict.account, account_currency
- )
+ _("Account: {0} with currency: {1} can not be selected").format(gl_dict.account, account_currency)
)
gl_dict["account_currency"] = (
@@ -2668,9 +2658,7 @@
# set debit/credit in account currency if not provided
if flt(gl_dict.debit) and not flt(gl_dict.debit_in_account_currency):
gl_dict.debit_in_account_currency = (
- gl_dict.debit
- if account_currency == company_currency
- else flt(gl_dict.debit / conversion_rate, 2)
+ gl_dict.debit if account_currency == company_currency else flt(gl_dict.debit / conversion_rate, 2)
)
if flt(gl_dict.credit) and not flt(gl_dict.credit_in_account_currency):
@@ -2755,7 +2743,6 @@
limit=None,
condition=None,
):
-
payment_entries = []
payment_entry = frappe.qb.DocType("Payment Entry")
@@ -2851,7 +2838,7 @@
if condition.get("to_payment_date"):
common_filter_conditions.append(payment_entry.posting_date.lte(condition["to_payment_date"]))
- if condition.get("get_payments") == True:
+ if condition.get("get_payments") is True:
if condition.get("cost_center"):
common_filter_conditions.append(payment_entry.cost_center == condition["cost_center"])
@@ -2943,9 +2930,7 @@
schedule = []
for d in terms_doc.get("terms"):
- term_details = get_payment_term_details(
- d, posting_date, grand_total, base_grand_total, bill_date
- )
+ term_details = get_payment_term_details(d, posting_date, grand_total, base_grand_total, bill_date)
schedule.append(term_details)
return schedule
@@ -3063,9 +3048,7 @@
tax_row.db_insert()
-def set_order_defaults(
- parent_doctype, parent_doctype_name, child_doctype, child_docname, trans_item
-):
+def set_order_defaults(parent_doctype, parent_doctype_name, child_doctype, child_docname, trans_item):
"""
Returns a Sales/Purchase Order Item child item containing the default values
"""
@@ -3081,9 +3064,7 @@
child_item.stock_uom = item.stock_uom
child_item.uom = trans_item.get("uom") or item.stock_uom
child_item.warehouse = get_item_warehouse(item, p_doc, overwrite_warehouse=True)
- conversion_factor = flt(
- get_conversion_factor(item.item_code, child_item.uom).get("conversion_factor")
- )
+ conversion_factor = flt(get_conversion_factor(item.item_code, child_item.uom).get("conversion_factor"))
child_item.conversion_factor = flt(trans_item.get("conversion_factor")) or conversion_factor
if child_doctype == "Purchase Order Item":
@@ -3230,9 +3211,7 @@
def get_new_child_item(item_row):
child_doctype = "Sales Order Item" if parent_doctype == "Sales Order" else "Purchase Order Item"
- return set_order_defaults(
- parent_doctype, parent_doctype_name, child_doctype, child_docname, item_row
- )
+ return set_order_defaults(parent_doctype, parent_doctype_name, child_doctype, child_docname, item_row)
def validate_quantity(child_item, new_data):
if not flt(new_data.get("qty")):
@@ -3246,9 +3225,7 @@
if parent_doctype == "Sales Order" and flt(new_data.get("qty")) < flt(child_item.delivered_qty):
frappe.throw(_("Cannot set quantity less than delivered quantity"))
- if parent_doctype == "Purchase Order" and flt(new_data.get("qty")) < flt(
- child_item.received_qty
- ):
+ if parent_doctype == "Purchase Order" and flt(new_data.get("qty")) < flt(child_item.received_qty):
frappe.throw(_("Cannot set quantity less than received quantity"))
def should_update_supplied_items(doc) -> bool:
@@ -3263,9 +3240,7 @@
item.supplied_qty or item.consumed_qty or item.returned_qty for item in doc.supplied_items
)
- update_supplied_items = (
- any_qty_changed or items_added_or_removed or any_conversion_factor_changed
- )
+ update_supplied_items = any_qty_changed or items_added_or_removed or any_conversion_factor_changed
if update_supplied_items and supplied_items_processed:
frappe.throw(_("Item qty can not be updated as raw materials are already processed."))
@@ -3275,7 +3250,9 @@
if is_new:
if not new_data.get("fg_item"):
frappe.throw(
- _("Finished Good Item is not specified for service item {0}").format(new_data["item_code"])
+ _("Finished Good Item is not specified for service item {0}").format(
+ new_data["item_code"]
+ )
)
else:
is_sub_contracted_item, default_bom = frappe.db.get_value(
@@ -3324,8 +3301,9 @@
prev_rate, new_rate = flt(child_item.get("rate")), flt(d.get("rate"))
prev_qty, new_qty = flt(child_item.get("qty")), flt(d.get("qty"))
prev_fg_qty, new_fg_qty = flt(child_item.get("fg_item_qty")), flt(d.get("fg_item_qty"))
- prev_con_fac, new_con_fac = flt(child_item.get("conversion_factor")), flt(
- d.get("conversion_factor")
+ prev_con_fac, new_con_fac = (
+ flt(child_item.get("conversion_factor")),
+ flt(d.get("conversion_factor")),
)
prev_uom, new_uom = child_item.get("uom"), d.get("uom")
@@ -3417,7 +3395,8 @@
if parent_doctype in sales_doctypes:
child_item.margin_type = "Amount"
child_item.margin_rate_or_amount = flt(
- child_item.rate - child_item.price_list_rate, child_item.precision("margin_rate_or_amount")
+ child_item.rate - child_item.price_list_rate,
+ child_item.precision("margin_rate_or_amount"),
)
child_item.rate_with_margin = child_item.rate
else:
@@ -3519,9 +3498,7 @@
parent.create_stock_reservation_entries()
-def check_if_child_table_updated(
- child_table_before_update, child_table_after_update, fields_to_check
-):
+def check_if_child_table_updated(child_table_before_update, child_table_after_update, fields_to_check):
fields_to_check = list(fields_to_check) + get_accounting_dimensions() + ["cost_center", "project"]
# Check if any field affecting accounting entry is altered
diff --git a/erpnext/controllers/buying_controller.py b/erpnext/controllers/buying_controller.py
index c530727..58bcc8c 100644
--- a/erpnext/controllers/buying_controller.py
+++ b/erpnext/controllers/buying_controller.py
@@ -28,7 +28,7 @@
def validate(self):
self.set_rate_for_standalone_debit_note()
- super(BuyingController, self).validate()
+ super().validate()
if getattr(self, "supplier", None) and not self.supplier_name:
self.supplier_name = frappe.db.get_value("Supplier", self.supplier, "supplier_name")
@@ -45,9 +45,7 @@
if self.doctype == "Purchase Invoice":
self.validate_purchase_receipt_if_update_stock()
- if self.doctype == "Purchase Receipt" or (
- self.doctype == "Purchase Invoice" and self.update_stock
- ):
+ if self.doctype == "Purchase Receipt" or (self.doctype == "Purchase Invoice" and self.update_stock):
# self.validate_purchase_return()
self.validate_rejected_warehouse()
self.validate_accepted_rejected_qty()
@@ -64,12 +62,10 @@
self.set_serial_and_batch_bundle()
def onload(self):
- super(BuyingController, self).onload()
+ super().onload()
self.set_onload(
"backflush_based_on",
- frappe.db.get_single_value(
- "Buying Settings", "backflush_raw_materials_of_subcontract_based_on"
- ),
+ frappe.db.get_single_value("Buying Settings", "backflush_raw_materials_of_subcontract_based_on"),
)
def create_package_for_transfer(self) -> None:
@@ -128,7 +124,7 @@
row.margin_rate_or_amount = 0.0
def set_missing_values(self, for_validate=False):
- super(BuyingController, self).set_missing_values(for_validate)
+ super().set_missing_values(for_validate)
self.set_supplier_from_item_default()
self.set_price_list_currency("Buying")
@@ -188,9 +184,7 @@
if self.doctype not in ["Purchase Receipt", "Purchase Invoice"] or not self.is_return:
return
- purchase_doc_field = (
- "purchase_receipt" if self.doctype == "Purchase Receipt" else "purchase_invoice"
- )
+ purchase_doc_field = "purchase_receipt" if self.doctype == "Purchase Receipt" else "purchase_invoice"
not_cancelled_asset = []
if self.return_against:
not_cancelled_asset = [
@@ -508,7 +502,6 @@
pr_qty = flt(flt(d.qty) * flt(d.conversion_factor), d.precision("stock_qty"))
if pr_qty:
-
if d.from_warehouse and (
(not cint(self.is_return) and self.docstatus == 1)
or (cint(self.is_return) and self.docstatus == 2)
@@ -546,7 +539,9 @@
"serial_and_batch_bundle": (
d.serial_and_batch_bundle
if not self.is_internal_transfer() or self.is_return
- else self.get_package_for_target_warehouse(d, type_of_transaction=type_of_transaction)
+ else self.get_package_for_target_warehouse(
+ d, type_of_transaction=type_of_transaction
+ )
),
},
)
@@ -604,7 +599,9 @@
d,
{
"warehouse": d.rejected_warehouse,
- "actual_qty": flt(flt(d.rejected_qty) * flt(d.conversion_factor), d.precision("stock_qty")),
+ "actual_qty": flt(
+ flt(d.rejected_qty) * flt(d.conversion_factor), d.precision("stock_qty")
+ ),
"incoming_rate": 0.0,
"serial_and_batch_bundle": d.rejected_serial_and_batch_bundle,
},
@@ -670,7 +667,7 @@
update_last_purchase_rate(self, is_submit=1)
def on_cancel(self):
- super(BuyingController, self).on_cancel()
+ super().on_cancel()
if self.get("is_return"):
return
@@ -695,7 +692,9 @@
"doctype": self.doctype,
"company": self.company,
"posting_date": (
- self.schedule_date if self.doctype == "Material Request" else self.transaction_date
+ self.schedule_date
+ if self.doctype == "Material Request"
+ else self.transaction_date
),
}
)
@@ -727,17 +726,21 @@
asset = self.make_asset(d, is_grouped_asset=True)
created_assets.append(asset)
else:
- for qty in range(cint(d.qty)):
+ for _qty in range(cint(d.qty)):
asset = self.make_asset(d)
created_assets.append(asset)
if len(created_assets) > 5:
# dont show asset form links if more than 5 assets are created
messages.append(
- _("{} Assets created for {}").format(len(created_assets), frappe.bold(d.item_code))
+ _("{} Assets created for {}").format(
+ len(created_assets), frappe.bold(d.item_code)
+ )
)
else:
- assets_link = list(map(lambda d: frappe.utils.get_link_to_form("Asset", d), created_assets))
+ assets_link = list(
+ map(lambda d: frappe.utils.get_link_to_form("Asset", d), created_assets)
+ )
assets_link = frappe.bold(",".join(assets_link))
is_plural = "s" if len(created_assets) != 1 else ""
@@ -748,9 +751,9 @@
)
else:
frappe.throw(
- _("Row {}: Asset Naming Series is mandatory for the auto creation for item {}").format(
- d.idx, frappe.bold(d.item_code)
- )
+ _(
+ "Row {}: Asset Naming Series is mandatory for the auto creation for item {}"
+ ).format(d.idx, frappe.bold(d.item_code))
)
else:
messages.append(
@@ -912,11 +915,9 @@
invalid_items = [
d[0]
for d in frappe.db.sql(
- """
- select item_code from tabItem where name in ({0}) and {1}=0
- """.format(
- item_list, fieldname
- ),
+ f"""
+ select item_code from tabItem where name in ({item_list}) and {fieldname}=0
+ """,
as_list=True,
)
]
diff --git a/erpnext/controllers/item_variant.py b/erpnext/controllers/item_variant.py
index 1eee9ea..7a1db6d 100644
--- a/erpnext/controllers/item_variant.py
+++ b/erpnext/controllers/item_variant.py
@@ -64,9 +64,7 @@
variant.flags.ignore_mandatory = True
variant.save()
- if not frappe.db.exists(
- "Item Manufacturer", {"item_code": variant.name, "manufacturer": manufacturer}
- ):
+ if not frappe.db.exists("Item Manufacturer", {"item_code": variant.name, "manufacturer": manufacturer}):
manufacturer_doc = frappe.new_doc("Item Manufacturer")
manufacturer_doc.update(
{
@@ -130,9 +128,7 @@
)
-def validate_item_attribute_value(
- attributes_list, attribute, attribute_value, item, from_variant=True
-):
+def validate_item_attribute_value(attributes_list, attribute, attribute_value, item, from_variant=True):
allow_rename_attribute_value = frappe.db.get_single_value(
"Item Variant Settings", "allow_rename_attribute_value"
)
@@ -179,9 +175,7 @@
def find_variant(template, args, variant_item_code=None):
- possible_variants = [
- i for i in get_item_codes_by_attributes(args, template) if i != variant_item_code
- ]
+ possible_variants = [i for i in get_item_codes_by_attributes(args, template) if i != variant_item_code]
for variant in possible_variants:
variant = frappe.get_doc("Item", variant)
@@ -357,7 +351,9 @@
if variant.attributes:
attributes_description = item.description + " "
for d in variant.attributes:
- attributes_description += "<div>" + d.attribute + ": " + cstr(d.attribute_value) + "</div>"
+ attributes_description += (
+ "<div>" + d.attribute + ": " + cstr(d.attribute_value) + "</div>"
+ )
if attributes_description not in variant.description:
variant.description = attributes_description
@@ -391,8 +387,8 @@
abbreviations.append(abbr_or_value)
if abbreviations:
- variant.item_code = "{0}-{1}".format(template_item_code, "-".join(abbreviations))
- variant.item_name = "{0}-{1}".format(template_item_name, "-".join(abbreviations))
+ variant.item_code = "{}-{}".format(template_item_code, "-".join(abbreviations))
+ variant.item_name = "{}-{}".format(template_item_name, "-".join(abbreviations))
@frappe.whitelist()
diff --git a/erpnext/controllers/print_settings.py b/erpnext/controllers/print_settings.py
index 59f13c6..f997116 100644
--- a/erpnext/controllers/print_settings.py
+++ b/erpnext/controllers/print_settings.py
@@ -40,7 +40,7 @@
def format_columns(display_columns, compact_fields):
- compact_fields = compact_fields + ["image", "item_code", "item_name"]
+ compact_fields = [*compact_fields, "image", "item_code", "item_name"]
final_columns = []
for column in display_columns:
if column not in compact_fields:
diff --git a/erpnext/controllers/queries.py b/erpnext/controllers/queries.py
index 960ebb7..4764629 100644
--- a/erpnext/controllers/queries.py
+++ b/erpnext/controllers/queries.py
@@ -98,7 +98,7 @@
account_type_condition = "AND account_type in %(account_types)s"
accounts = frappe.db.sql(
- """
+ f"""
SELECT name, parent_account
FROM `tabAccount`
WHERE `tabAccount`.docstatus!=2
@@ -108,20 +108,16 @@
AND disabled = %(disabled)s
AND (account_currency = %(currency)s or ifnull(account_currency, '') = '')
AND `{searchfield}` LIKE %(txt)s
- {mcond}
+ {get_match_cond(doctype)}
ORDER BY idx DESC, name
LIMIT %(limit)s offset %(offset)s
- """.format(
- account_type_condition=account_type_condition,
- searchfield=searchfield,
- mcond=get_match_cond(doctype),
- ),
+ """,
dict(
account_types=filters.get("account_type"),
company=filters.get("company"),
disabled=filters.get("disabled", 0),
currency=company_currency,
- txt="%{}%".format(txt),
+ txt=f"%{txt}%",
offset=start,
limit=page_len,
),
@@ -176,7 +172,9 @@
if filters.get("customer") or filters.get("supplier"):
party = filters.get("customer") or filters.get("supplier")
item_rules_list = frappe.get_all(
- "Party Specific Item", filters={"party": party}, fields=["restrict_based_on", "based_on_value"]
+ "Party Specific Item",
+ filters={"party": party},
+ fields=["restrict_based_on", "based_on_value"],
)
filters_dict = {}
@@ -325,11 +323,11 @@
return frappe.db.sql(
"""
- select %(fields)s
+ select {fields}
from `tabDelivery Note`
- where `tabDelivery Note`.`%(key)s` like %(txt)s and
+ where `tabDelivery Note`.`{key}` like {txt} and
`tabDelivery Note`.docstatus = 1
- and status not in ('Stopped', 'Closed') %(fcond)s
+ and status not in ('Stopped', 'Closed') {fcond}
and (
(`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
@@ -338,17 +336,16 @@
and return_against in (select name from `tabDelivery Note` where per_billed < 100)
)
)
- %(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(page_len)s offset %(start)s
- """
- % {
- "fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
- "key": searchfield,
- "fcond": get_filters_cond(doctype, filters, []),
- "mcond": get_match_cond(doctype),
- "start": start,
- "page_len": page_len,
- "txt": "%(txt)s",
- },
+ {mcond} order by `tabDelivery Note`.`{key}` asc limit {page_len} offset {start}
+ """.format(
+ fields=", ".join([f"`tabDelivery Note`.{f}" for f in fields]),
+ key=searchfield,
+ fcond=get_filters_cond(doctype, filters, []),
+ mcond=get_match_cond(doctype),
+ start=start,
+ page_len=page_len,
+ txt="%(txt)s",
+ ),
{"txt": ("%%%s%%" % txt)},
as_dict=as_dict,
)
@@ -362,9 +359,7 @@
searchfields = meta.get_search_fields()
batches = get_batches_from_stock_ledger_entries(searchfields, txt, filters, start, page_len)
- batches.extend(
- get_batches_from_serial_and_batch_bundle(searchfields, txt, filters, start, page_len)
- )
+ batches.extend(get_batches_from_serial_and_batch_bundle(searchfields, txt, filters, start, page_len))
filtered_batches = get_filterd_batches(batches)
@@ -377,7 +372,7 @@
def get_empty_batches(filters, start, page_len, filtered_batches=None, txt=None):
query_filter = {"item": filters.get("item_code")}
if txt:
- query_filter["name"] = ("like", "%{0}%".format(txt))
+ query_filter["name"] = ("like", f"%{txt}%")
exclude_batches = [batch[0] for batch in filtered_batches] if filtered_batches else []
if exclude_batches:
@@ -403,7 +398,7 @@
batches[batch_data[0]][1] += batch_data[1]
filterd_batch = []
- for batch, batch_data in batches.items():
+ for _batch, batch_data in batches.items():
if batch_data[1] > 0:
filterd_batch.append(tuple(batch_data))
@@ -424,7 +419,7 @@
stock_ledger_entry.batch_no,
Sum(stock_ledger_entry.actual_qty).as_("qty"),
)
- .where(((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull())))
+ .where((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull()))
.where(stock_ledger_entry.is_cancelled == 0)
.where(
(stock_ledger_entry.item_code == filters.get("item_code"))
@@ -448,9 +443,9 @@
query = query.select(batch_table[field])
if txt:
- txt_condition = batch_table.name.like("%{0}%".format(txt))
- for field in searchfields + ["name"]:
- txt_condition |= batch_table[field].like("%{0}%".format(txt))
+ txt_condition = batch_table.name.like(f"%{txt}%")
+ for field in [*searchfields, "name"]:
+ txt_condition |= batch_table[field].like(f"%{txt}%")
query = query.where(txt_condition)
@@ -474,7 +469,7 @@
bundle.batch_no,
Sum(bundle.qty).as_("qty"),
)
- .where(((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull())))
+ .where((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull()))
.where(stock_ledger_entry.is_cancelled == 0)
.where(
(stock_ledger_entry.item_code == filters.get("item_code"))
@@ -498,9 +493,9 @@
bundle_query = bundle_query.select(batch_table[field])
if txt:
- txt_condition = batch_table.name.like("%{0}%".format(txt))
- for field in searchfields + ["name"]:
- txt_condition |= batch_table[field].like("%{0}%".format(txt))
+ txt_condition = batch_table.name.like(f"%{txt}%")
+ for field in [*searchfields, "name"]:
+ txt_condition |= batch_table[field].like(f"%{txt}%")
bundle_query = bundle_query.where(txt_condition)
@@ -515,7 +510,7 @@
if isinstance(filters, dict):
for key, val in filters.items():
- if isinstance(val, (list, tuple)):
+ if isinstance(val, list | tuple):
filter_list.append([doctype, key, val[0], val[1]])
else:
filter_list.append([doctype, key, "=", val])
@@ -576,24 +571,20 @@
condition += f"and tabAccount.disabled = {filters.get('disabled', 0)}"
return frappe.db.sql(
- """select tabAccount.name from `tabAccount`
+ f"""select tabAccount.name from `tabAccount`
where (tabAccount.report_type = "Profit and Loss"
or tabAccount.account_type in ("Income Account", "Temporary"))
and tabAccount.is_group=0
- and tabAccount.`{key}` LIKE %(txt)s
- {condition} {match_condition}
- order by idx desc, name""".format(
- condition=condition, match_condition=get_match_cond(doctype), key=searchfield
- ),
+ and tabAccount.`{searchfield}` LIKE %(txt)s
+ {condition} {get_match_cond(doctype)}
+ order by idx desc, name""",
{"txt": "%" + txt + "%", "company": filters.get("company", "")},
)
@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
-def get_filtered_dimensions(
- doctype, txt, searchfield, start, page_len, filters, reference_doctype=None
-):
+def get_filtered_dimensions(doctype, txt, searchfield, start, page_len, filters, reference_doctype=None):
from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import (
get_dimension_filter_map,
)
@@ -659,15 +650,13 @@
condition += "and tabAccount.company = %(company)s"
return frappe.db.sql(
- """select tabAccount.name from `tabAccount`
+ f"""select tabAccount.name from `tabAccount`
where (tabAccount.report_type = "Profit and Loss"
or tabAccount.account_type in ("Expense Account", "Fixed Asset", "Temporary", "Asset Received But Not Billed", "Capital Work in Progress"))
and tabAccount.is_group=0
and tabAccount.docstatus!=2
- and tabAccount.{key} LIKE %(txt)s
- {condition} {match_condition}""".format(
- condition=condition, key=searchfield, match_condition=get_match_cond(doctype)
- ),
+ and tabAccount.{searchfield} LIKE %(txt)s
+ {condition} {get_match_cond(doctype)}""",
{"company": filters.get("company", ""), "txt": "%" + txt + "%"},
)
@@ -706,7 +695,7 @@
mcond=get_match_cond(doctype),
start=start,
page_len=page_len,
- txt=frappe.db.escape("%{0}%".format(txt)),
+ txt=frappe.db.escape(f"%{txt}%"),
)
return frappe.db.sql(query)
@@ -726,9 +715,7 @@
query = """select batch_id from `tabBatch`
where disabled = 0
and (expiry_date >= CURRENT_DATE or expiry_date IS NULL)
- and name like {txt}""".format(
- txt=frappe.db.escape("%{0}%".format(txt))
- )
+ and name like {txt}""".format(txt=frappe.db.escape(f"%{txt}%"))
if filters and filters.get("item"):
query += " and item = {item}".format(item=frappe.db.escape(filters.get("item")))
@@ -762,9 +749,7 @@
select pr.name
from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
where pr.docstatus = 1 and pritem.parent = pr.name
- and pr.name like {txt}""".format(
- txt=frappe.db.escape("%{0}%".format(txt))
- )
+ and pr.name like {txt}""".format(txt=frappe.db.escape(f"%{txt}%"))
if filters and filters.get("item_code"):
query += " and pritem.item_code = {item_code}".format(
@@ -781,9 +766,7 @@
select pi.name
from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
where pi.docstatus = 1 and piitem.parent = pi.name
- and pi.name like {txt}""".format(
- txt=frappe.db.escape("%{0}%".format(txt))
- )
+ and pi.name like {txt}""".format(txt=frappe.db.escape(f"%{txt}%"))
if filters and filters.get("item_code"):
query += " and piitem.item_code = {item_code}".format(
@@ -805,7 +788,6 @@
@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
-
item_doc = frappe.get_cached_doc("Item", filters.get("item_code"))
item_group = filters.get("item_group")
company = filters.get("company")
@@ -817,9 +799,7 @@
item_group = item_group_doc.parent_item_group
if not taxes:
- return frappe.get_all(
- "Item Tax Template", filters={"disabled": 0, "company": company}, as_list=True
- )
+ return frappe.get_all("Item Tax Template", filters={"disabled": 0, "company": company}, as_list=True)
else:
valid_from = filters.get("valid_from")
valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
diff --git a/erpnext/controllers/sales_and_purchase_return.py b/erpnext/controllers/sales_and_purchase_return.py
index 5594816..83f3410 100644
--- a/erpnext/controllers/sales_and_purchase_return.py
+++ b/erpnext/controllers/sales_and_purchase_return.py
@@ -28,9 +28,7 @@
def validate_return_against(doc):
if not frappe.db.exists(doc.doctype, doc.return_against):
- frappe.throw(
- _("Invalid {0}: {1}").format(doc.meta.get_label("return_against"), doc.return_against)
- )
+ frappe.throw(_("Invalid {0}: {1}").format(doc.meta.get_label("return_against"), doc.return_against))
else:
ref_doc = frappe.get_doc(doc.doctype, doc.return_against)
@@ -42,8 +40,8 @@
and ref_doc.docstatus.is_submitted()
):
# validate posting date time
- return_posting_datetime = "%s %s" % (doc.posting_date, doc.get("posting_time") or "00:00:00")
- ref_posting_datetime = "%s %s" % (
+ return_posting_datetime = "{} {}".format(doc.posting_date, doc.get("posting_time") or "00:00:00")
+ ref_posting_datetime = "{} {}".format(
ref_doc.posting_date,
ref_doc.get("posting_time") or "00:00:00",
)
@@ -81,7 +79,7 @@
select_fields += ",rejected_qty, received_qty"
for d in frappe.db.sql(
- """select {0} from `tab{1} Item` where parent = %s""".format(select_fields, doc.doctype),
+ f"""select {select_fields} from `tab{doc.doctype} Item` where parent = %s""",
doc.return_against,
as_dict=1,
):
@@ -229,17 +227,15 @@
sum(abs(child.received_qty) * child.conversion_factor) as received_qty"""
data = frappe.db.sql(
- """
- select {0}
+ f"""
+ select {column}
from
- `tab{1} Item` child, `tab{2}` par
+ `tab{doc.doctype} Item` child, `tab{doc.doctype}` par
where
child.parent = par.name and par.docstatus = 1
and par.is_return = 1 and par.return_against = %s
group by item_code
- """.format(
- column, doc.doctype, doc.doctype
- ),
+ """,
doc.return_against,
as_dict=1,
)
@@ -272,22 +268,22 @@
party_type = "customer"
fields = [
- "sum(abs(`tab{0}`.qty)) as qty".format(child_doctype),
+ f"sum(abs(`tab{child_doctype}`.qty)) as qty",
]
if doctype != "Subcontracting Receipt":
fields += [
- "sum(abs(`tab{0}`.stock_qty)) as stock_qty".format(child_doctype),
+ f"sum(abs(`tab{child_doctype}`.stock_qty)) as stock_qty",
]
if doctype in ("Purchase Receipt", "Purchase Invoice", "Subcontracting Receipt"):
fields += [
- "sum(abs(`tab{0}`.rejected_qty)) as rejected_qty".format(child_doctype),
- "sum(abs(`tab{0}`.received_qty)) as received_qty".format(child_doctype),
+ f"sum(abs(`tab{child_doctype}`.rejected_qty)) as rejected_qty",
+ f"sum(abs(`tab{child_doctype}`.received_qty)) as received_qty",
]
if doctype == "Purchase Receipt":
- fields += ["sum(abs(`tab{0}`.received_stock_qty)) as received_stock_qty".format(child_doctype)]
+ fields += [f"sum(abs(`tab{child_doctype}`.received_stock_qty)) as received_stock_qty"]
# Used retrun against and supplier and is_retrun because there is an index added for it
data = frappe.get_all(
@@ -305,9 +301,7 @@
return data[0]
-def make_return_doc(
- doctype: str, source_name: str, target_doc=None, return_against_rejected_qty=False
-):
+def make_return_doc(doctype: str, source_name: str, target_doc=None, return_against_rejected_qty=False):
from frappe.model.mapper import get_mapped_doc
company = frappe.db.get_value("Delivery Note", source_name, "company")
@@ -648,8 +642,7 @@
"docstatus": ["=", 1],
},
},
- doctype
- + " Item": {
+ doctype + " Item": {
"doctype": doctype + " Item",
"field_map": {"serial_no": "serial_no", "batch_no": "batch_no", "bom": "bom"},
"postprocess": update_item,
@@ -747,19 +740,13 @@
if reference_voucher_detail_no:
filters["voucher_detail_no"] = reference_voucher_detail_no
- if (
- voucher_type in ["Purchase Receipt", "Purchase Invoice"]
- and item_row
- and item_row.get("warehouse")
- ):
+ if voucher_type in ["Purchase Receipt", "Purchase Invoice"] and item_row and item_row.get("warehouse"):
filters["warehouse"] = item_row.get("warehouse")
return filters
-def get_returned_serial_nos(
- child_doc, parent_doc, serial_no_field=None, ignore_voucher_detail_no=None
-):
+def get_returned_serial_nos(child_doc, parent_doc, serial_no_field=None, ignore_voucher_detail_no=None):
from erpnext.stock.doctype.serial_no.serial_no import (
get_serial_nos as get_serial_nos_from_serial_no,
)
@@ -809,9 +796,7 @@
return serial_nos
-def get_returned_batches(
- child_doc, parent_doc, batch_no_field=None, ignore_voucher_detail_no=None
-):
+def get_returned_batches(child_doc, parent_doc, batch_no_field=None, ignore_voucher_detail_no=None):
from erpnext.stock.serial_batch_bundle import get_batches_from_bundle
batches = frappe._dict()
diff --git a/erpnext/controllers/selling_controller.py b/erpnext/controllers/selling_controller.py
index 9d86cb2..89e47b4 100644
--- a/erpnext/controllers/selling_controller.py
+++ b/erpnext/controllers/selling_controller.py
@@ -20,13 +20,13 @@
self.flags.ignore_permlevel_for_fields = ["selling_price_list", "price_list_currency"]
def onload(self):
- super(SellingController, self).onload()
+ super().onload()
if self.doctype in ("Sales Order", "Delivery Note", "Sales Invoice"):
for item in self.get("items") + (self.get("packed_items") or []):
item.update(get_bin_details(item.item_code, item.warehouse, include_child_warehouses=True))
def validate(self):
- super(SellingController, self).validate()
+ super().validate()
self.validate_items()
if not self.get("is_debit_note"):
self.validate_max_discount()
@@ -44,7 +44,7 @@
self.set_serial_and_batch_bundle(table_field)
def set_missing_values(self, for_validate=False):
- super(SellingController, self).set_missing_values(for_validate)
+ super().set_missing_values(for_validate)
# set contact and address details for customer, if they are not mentioned
self.set_missing_lead_customer_details(for_validate=for_validate)
@@ -290,7 +290,10 @@
if flt(item.base_net_rate) < flt(last_valuation_rate_in_sales_uom):
throw_message(
- item.idx, item.item_name, last_valuation_rate_in_sales_uom, "valuation rate (Moving Average)"
+ item.idx,
+ item.item_name,
+ last_valuation_rate_in_sales_uom,
+ "valuation rate (Moving Average)",
)
def get_item_list(self):
@@ -419,7 +422,8 @@
"Cancelled"
]:
frappe.throw(
- _("{0} {1} is cancelled or closed").format(_("Sales Order"), so), frappe.InvalidStatusError
+ _("{0} {1} is cancelled or closed").format(_("Sales Order"), so),
+ frappe.InvalidStatusError,
)
sales_order.update_reserved_qty(so_item_rows)
@@ -623,7 +627,8 @@
if self.doctype in ["Sales Order", "Quotation"]:
for item in self.items:
item.gross_profit = flt(
- ((item.base_rate - flt(item.valuation_rate)) * item.stock_qty), self.precision("amount", item)
+ ((item.base_rate - flt(item.valuation_rate)) * item.stock_qty),
+ self.precision("amount", item),
)
def set_customer_address(self):
@@ -700,9 +705,9 @@
if d.get("target_warehouse") and d.get("warehouse") == d.get("target_warehouse"):
warehouse = frappe.bold(d.get("target_warehouse"))
frappe.throw(
- _("Row {0}: Delivery Warehouse ({1}) and Customer Warehouse ({2}) can not be same").format(
- d.idx, warehouse, warehouse
- )
+ _(
+ "Row {0}: Delivery Warehouse ({1}) and Customer Warehouse ({2}) can not be same"
+ ).format(d.idx, warehouse, warehouse)
)
if not self.get("is_internal_customer") and any(d.get("target_warehouse") for d in items):
@@ -730,14 +735,10 @@
if child.get("use_serial_batch_fields"):
return
- if not frappe.db.get_single_value(
- "Stock Settings", "auto_create_serial_and_batch_bundle_for_outward"
- ):
+ if not frappe.db.get_single_value("Stock Settings", "auto_create_serial_and_batch_bundle_for_outward"):
return
- item_details = frappe.db.get_value(
- "Item", child.item_code, ["has_serial_no", "has_batch_no"], as_dict=1
- )
+ item_details = frappe.db.get_value("Item", child.item_code, ["has_serial_no", "has_batch_no"], as_dict=1)
if not item_details.has_serial_no and not item_details.has_batch_no:
return
diff --git a/erpnext/controllers/status_updater.py b/erpnext/controllers/status_updater.py
index fcbec22..17f072e 100644
--- a/erpnext/controllers/status_updater.py
+++ b/erpnext/controllers/status_updater.py
@@ -257,9 +257,7 @@
"""select item_code, `{target_ref_field}`,
`{target_field}`, parenttype, parent from `tab{target_dt}`
where `{target_ref_field}` < `{target_field}`
- and name=%s and docstatus=1""".format(
- **args
- ),
+ and name=%s and docstatus=1""".format(**args),
args["name"],
as_dict=1,
)
@@ -304,9 +302,7 @@
role_allowed_to_over_bill = frappe.db.get_single_value(
"Accounts Settings", "role_allowed_to_over_bill"
)
- role = (
- role_allowed_to_over_deliver_receive if qty_or_amount == "qty" else role_allowed_to_over_bill
- )
+ role = role_allowed_to_over_deliver_receive if qty_or_amount == "qty" else role_allowed_to_over_bill
overflow_percent = (
(item[args["target_field"]] - item[args["target_ref_field"]]) / item[args["target_ref_field"]]
@@ -417,12 +413,11 @@
args["second_source_extra_cond"] = ""
args["second_source_condition"] = frappe.db.sql(
- """ select ifnull((select sum(%(second_source_field)s)
- from `tab%(second_source_dt)s`
- where `%(second_join_field)s`='%(detail_id)s'
- and (`tab%(second_source_dt)s`.docstatus=1)
- %(second_source_extra_cond)s), 0) """
- % args
+ """ select ifnull((select sum({second_source_field})
+ from `tab{second_source_dt}`
+ where `{second_join_field}`='{detail_id}'
+ and (`tab{second_source_dt}`.docstatus=1)
+ {second_source_extra_cond}), 0) """.format(**args)
)[0][0]
if args["detail_id"]:
@@ -432,11 +427,10 @@
args["source_dt_value"] = (
frappe.db.sql(
"""
- (select ifnull(sum(%(source_field)s), 0)
- from `tab%(source_dt)s` where `%(join_field)s`='%(detail_id)s'
- and (docstatus=1 %(cond)s) %(extra_cond)s)
- """
- % args
+ (select ifnull(sum({source_field}), 0)
+ from `tab{source_dt}` where `{join_field}`='{detail_id}'
+ and (docstatus=1 {cond}) {extra_cond})
+ """.format(**args)
)[0][0]
or 0.0
)
@@ -445,10 +439,9 @@
args["source_dt_value"] += flt(args["second_source_condition"])
frappe.db.sql(
- """update `tab%(target_dt)s`
- set %(target_field)s = %(source_dt_value)s %(update_modified)s
- where name='%(detail_id)s'"""
- % args
+ """update `tab{target_dt}`
+ set {target_field} = {source_dt_value} {update_modified}
+ where name='{detail_id}'""".format(**args)
)
def _update_percent_field_in_targets(self, args, update_modified=True):
@@ -475,26 +468,24 @@
if args.get("target_parent_field"):
frappe.db.sql(
- """update `tab%(target_parent_dt)s`
- set %(target_parent_field)s = round(
+ """update `tab{target_parent_dt}`
+ set {target_parent_field} = round(
ifnull((select
- ifnull(sum(case when abs(%(target_ref_field)s) > abs(%(target_field)s) then abs(%(target_field)s) else abs(%(target_ref_field)s) end), 0)
- / sum(abs(%(target_ref_field)s)) * 100
- from `tab%(target_dt)s` where parent='%(name)s' and parenttype='%(target_parent_dt)s' having sum(abs(%(target_ref_field)s)) > 0), 0), 6)
- %(update_modified)s
- where name='%(name)s'"""
- % args
+ ifnull(sum(case when abs({target_ref_field}) > abs({target_field}) then abs({target_field}) else abs({target_ref_field}) end), 0)
+ / sum(abs({target_ref_field})) * 100
+ from `tab{target_dt}` where parent='{name}' and parenttype='{target_parent_dt}' having sum(abs({target_ref_field})) > 0), 0), 6)
+ {update_modified}
+ where name='{name}'""".format(**args)
)
# update field
if args.get("status_field"):
frappe.db.sql(
- """update `tab%(target_parent_dt)s`
- set %(status_field)s = (case when %(target_parent_field)s<0.001 then 'Not %(keyword)s'
- else case when %(target_parent_field)s>=99.999999 then 'Fully %(keyword)s'
- else 'Partly %(keyword)s' end end)
- where name='%(name)s'"""
- % args
+ """update `tab{target_parent_dt}`
+ set {status_field} = (case when {target_parent_field}<0.001 then 'Not {keyword}'
+ else case when {target_parent_field}>=99.999999 then 'Fully {keyword}'
+ else 'Partly {keyword}' end end)
+ where name='{name}'""".format(**args)
)
if update_modified:
@@ -507,21 +498,19 @@
args["update_modified"] = ""
return
- args["update_modified"] = ", modified = {0}, modified_by = {1}".format(
+ args["update_modified"] = ", modified = {}, modified_by = {}".format(
frappe.db.escape(now()), frappe.db.escape(frappe.session.user)
)
def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
ref_fieldname = frappe.scrub(ref_dt)
- ref_docs = [
- item.get(ref_fieldname) for item in (self.get("items") or []) if item.get(ref_fieldname)
- ]
+ ref_docs = [item.get(ref_fieldname) for item in (self.get("items") or []) if item.get(ref_fieldname)]
if not ref_docs:
return
zero_amount_refdocs = frappe.db.sql_list(
- """
+ f"""
SELECT
name
from
@@ -530,9 +519,7 @@
docstatus = 1
and base_net_total = 0
and name in %(ref_docs)s
- """.format(
- ref_dt=ref_dt
- ),
+ """,
{"ref_docs": ref_docs},
)
@@ -543,9 +530,8 @@
for ref_dn in zero_amount_refdoc:
ref_doc_qty = flt(
frappe.db.sql(
- """select ifnull(sum(qty), 0) from `tab%s Item`
- where parent=%s"""
- % (ref_dt, "%s"),
+ """select ifnull(sum(qty), 0) from `tab{} Item`
+ where parent={}""".format(ref_dt, "%s"),
(ref_dn),
)[0][0]
)
@@ -553,8 +539,7 @@
billed_qty = flt(
frappe.db.sql(
"""select ifnull(sum(qty), 0)
- from `tab%s Item` where %s=%s and docstatus=1"""
- % (self.doctype, ref_fieldname, "%s"),
+ from `tab{} Item` where {}={} and docstatus=1""".format(self.doctype, ref_fieldname, "%s"),
(ref_dn),
)[0][0]
)
@@ -612,13 +597,13 @@
)
if qty_or_amount == "qty" and not qty_allowance:
- if global_qty_allowance == None:
+ if global_qty_allowance is None:
global_qty_allowance = flt(
frappe.get_cached_value("Stock Settings", None, "over_delivery_receipt_allowance")
)
qty_allowance = global_qty_allowance
elif qty_or_amount == "amount" and not over_billing_allowance:
- if global_amount_allowance == None:
+ if global_amount_allowance is None:
global_amount_allowance = flt(
frappe.get_cached_value("Accounts Settings", None, "over_billing_allowance")
)
diff --git a/erpnext/controllers/stock_controller.py b/erpnext/controllers/stock_controller.py
index a1946e8..5f11c59 100644
--- a/erpnext/controllers/stock_controller.py
+++ b/erpnext/controllers/stock_controller.py
@@ -3,7 +3,6 @@
import json
from collections import defaultdict
-from typing import List, Tuple
import frappe
from frappe import _, bold
@@ -45,7 +44,7 @@
class StockController(AccountsController):
def validate(self):
- super(StockController, self).validate()
+ super().validate()
if self.docstatus == 0:
for table_name in ["items", "packed_items", "supplied_items"]:
@@ -289,7 +288,9 @@
throw_error = False
if row.serial_no:
serial_nos = frappe.get_all(
- "Serial and Batch Entry", fields=["serial_no"], filters={"parent": row.serial_and_batch_bundle}
+ "Serial and Batch Entry",
+ fields=["serial_no"],
+ filters={"parent": row.serial_and_batch_bundle},
)
serial_nos = sorted([cstr(d.serial_no) for d in serial_nos])
parsed_serial_nos = get_serial_nos(row.serial_no)
@@ -323,10 +324,7 @@
for row in self.items:
row.use_serial_batch_fields = 1
- 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):
if not warehouse_account:
warehouse_account = get_warehouse_account_map(self.company)
@@ -364,7 +362,9 @@
"project": item_row.project or self.get("project"),
"remarks": self.get("remarks") or _("Accounting Entry for Stock"),
"debit": flt(sle.stock_value_difference, precision),
- "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
+ "is_opening": item_row.get("is_opening")
+ or self.get("is_opening")
+ or "No",
},
warehouse_account[sle.warehouse]["account_currency"],
item=item_row,
@@ -380,7 +380,9 @@
"remarks": self.get("remarks") or _("Accounting Entry for Stock"),
"debit": -1 * flt(sle.stock_value_difference, precision),
"project": item_row.get("project") or self.get("project"),
- "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
+ "is_opening": item_row.get("is_opening")
+ or self.get("is_opening")
+ or "No",
},
item=item_row,
)
@@ -447,9 +449,7 @@
def get_debit_field_precision(self):
if not frappe.flags.debit_field_precision:
- frappe.flags.debit_field_precision = frappe.get_precision(
- "GL Entry", "debit_in_account_currency"
- )
+ frappe.flags.debit_field_precision = frappe.get_precision("GL Entry", "debit_in_account_currency")
return frappe.flags.debit_field_precision
@@ -482,7 +482,7 @@
return details
- def get_items_and_warehouses(self) -> Tuple[List[str], List[str]]:
+ def get_items_and_warehouses(self) -> tuple[list[str], list[str]]:
"""Get list of items and warehouses affected by a transaction"""
if not (hasattr(self, "items") or hasattr(self, "packed_items")):
@@ -763,9 +763,7 @@
if item_codes:
serialized_items = frappe.db.sql_list(
"""select name from `tabItem`
- where has_serial_no=1 and name in ({})""".format(
- ", ".join(["%s"] * len(item_codes))
- ),
+ where has_serial_no=1 and name in ({})""".format(", ".join(["%s"] * len(item_codes))),
tuple(item_codes),
)
@@ -854,16 +852,12 @@
def validate_qi_submission(self, row):
"""Check if QI is submitted on row level, during submission"""
- action = frappe.db.get_single_value(
- "Stock Settings", "action_if_quality_inspection_is_not_submitted"
- )
+ action = frappe.db.get_single_value("Stock Settings", "action_if_quality_inspection_is_not_submitted")
qa_docstatus = frappe.db.get_value("Quality Inspection", row.quality_inspection, "docstatus")
if qa_docstatus != 1:
link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
- msg = (
- f"Row #{row.idx}: Quality Inspection {link} is not submitted for the item: {row.item_code}"
- )
+ msg = f"Row #{row.idx}: Quality Inspection {link} is not submitted for the item: {row.item_code}"
if action == "Stop":
frappe.throw(_(msg), title=_("Inspection Submission"), exc=QualityInspectionNotSubmittedError)
else:
@@ -927,9 +921,7 @@
row.from_warehouse = None
def validate_in_transit_warehouses(self):
- if (
- self.doctype == "Sales Invoice" and self.get("update_stock")
- ) or self.doctype == "Delivery Note":
+ if (self.doctype == "Sales Invoice" and self.get("update_stock")) or self.doctype == "Delivery Note":
for item in self.get("items"):
if not item.target_warehouse:
frappe.throw(
@@ -1098,7 +1090,9 @@
if self.doctype == "Stock Reconciliation":
stock_qty = flt(item.qty)
else:
- stock_qty = flt(item.transfer_qty) if self.doctype == "Stock Entry" else flt(item.stock_qty)
+ stock_qty = (
+ flt(item.transfer_qty) if self.doctype == "Stock Entry" else flt(item.stock_qty)
+ )
rule_name = rule.get("name")
if not rule_map[rule_name]:
@@ -1114,9 +1108,7 @@
frappe.throw(msg=message, title=_("Over Receipt"))
def prepare_over_receipt_message(self, rule, values):
- message = _(
- "{0} qty of Item {1} is being received into Warehouse {2} with capacity {3}."
- ).format(
+ message = _("{0} qty of Item {1} is being received into Warehouse {2} with capacity {3}.").format(
frappe.bold(values["qty_put"]),
frappe.bold(values["item"]),
frappe.bold(values["warehouse"]),
@@ -1167,7 +1159,6 @@
item=None,
posting_date=None,
):
-
gl_entry = {
"account": account,
"cost_center": cost_center,
@@ -1312,9 +1303,7 @@
def get_gl_entries_for_preview(doctype, docname, fields):
- return frappe.get_all(
- "GL Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
- )
+ return frappe.get_all("GL Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields)
def get_columns(raw_columns, fields):
@@ -1439,9 +1428,7 @@
and is_cancelled = 0
GROUP BY
item_code, warehouse
- """.format(
- " or ".join(or_conditions)
- ),
+ """.format(" or ".join(or_conditions)),
args,
as_dict=1,
)
diff --git a/erpnext/controllers/subcontracting_controller.py b/erpnext/controllers/subcontracting_controller.py
index ffc7f91..fc66345 100644
--- a/erpnext/controllers/subcontracting_controller.py
+++ b/erpnext/controllers/subcontracting_controller.py
@@ -21,7 +21,7 @@
class SubcontractingController(StockController):
def __init__(self, *args, **kwargs):
- super(SubcontractingController, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
if self.get("is_old_subcontracting_flow"):
self.subcontract_data = frappe._dict(
{
@@ -53,7 +53,7 @@
self.validate_items()
self.create_raw_materials_supplied()
else:
- super(SubcontractingController, self).validate()
+ super().validate()
def validate_rejected_warehouse(self):
for item in self.get("items"):
@@ -108,14 +108,20 @@
if not is_active:
frappe.throw(
- _("Row {0}: Please select an active BOM for Item {1}.").format(item.idx, item.item_name)
+ _("Row {0}: Please select an active BOM for Item {1}.").format(
+ item.idx, item.item_name
+ )
)
if bom_item != item.item_code:
frappe.throw(
- _("Row {0}: Please select an valid BOM for Item {1}.").format(item.idx, item.item_name)
+ _("Row {0}: Please select an valid BOM for Item {1}.").format(
+ item.idx, item.item_name
+ )
)
else:
- frappe.throw(_("Row {0}: Please select a BOM for Item {1}.").format(item.idx, item.item_name))
+ frappe.throw(
+ _("Row {0}: Please select a BOM for Item {1}.").format(item.idx, item.item_name)
+ )
else:
item.bom = None
@@ -190,7 +196,6 @@
fields=["item_code", "(qty - received_qty) as qty", "parent", "name"],
filters={"docstatus": 1, "parent": ("in", self.subcontract_orders)},
):
-
self.qty_to_be_received[(row.item_code, row.parent)] += row.qty
def __get_transferred_items(self):
@@ -286,9 +291,7 @@
if not receipt_items:
return ([], {}) if return_consumed_items else None
- receipt_items = {
- item.name: item.get(self.subcontract_data.order_field) for item in receipt_items
- }
+ receipt_items = {item.name: item.get(self.subcontract_data.order_field) for item in receipt_items}
consumed_materials = self.__get_consumed_items(doctype, receipt_items.keys())
voucher_nos = [d.voucher_no for d in consumed_materials if d.voucher_no]
@@ -459,9 +462,7 @@
[doctype, "sourced_by_supplier", "=", 0],
]
- return (
- frappe.get_all("BOM", fields=fields, filters=filters, order_by=f"`tab{doctype}`.`idx`") or []
- )
+ return frappe.get_all("BOM", fields=fields, filters=filters, order_by=f"`tab{doctype}`.`idx`") or []
def __update_reserve_warehouse(self, row, item):
if self.doctype == self.subcontract_data.order_doctype:
@@ -476,9 +477,7 @@
if not self.available_materials.get(key):
return
- if (
- not self.available_materials[key]["serial_no"] and not self.available_materials[key]["batch_no"]
- ):
+ if not self.available_materials[key]["serial_no"] and not self.available_materials[key]["batch_no"]:
return
serial_nos = []
@@ -761,7 +760,9 @@
for row in self.get("supplied_items"):
if row.reference_name == name and row.serial_and_batch_bundle:
if row.consumed_qty != abs(
- frappe.get_cached_value("Serial and Batch Bundle", row.serial_and_batch_bundle, "total_qty")
+ frappe.get_cached_value(
+ "Serial and Batch Bundle", row.serial_and_batch_bundle, "total_qty"
+ )
):
return row
@@ -1048,7 +1049,8 @@
if mr_obj.status in ["Stopped", "Cancelled"]:
frappe.throw(
- _("Material Request {0} is cancelled or stopped").format(mr), frappe.InvalidStatusError
+ _("Material Request {0} is cancelled or stopped").format(mr),
+ frappe.InvalidStatusError,
)
mr_obj.update_requested_qty(mr_item_rows)
@@ -1131,8 +1133,10 @@
for fg_item_code in fg_item_code_list:
for rm_item in rm_items:
-
- if rm_item.get("main_item_code") == fg_item_code or rm_item.get("item_code") == fg_item_code:
+ if (
+ rm_item.get("main_item_code") == fg_item_code
+ or rm_item.get("item_code") == fg_item_code
+ ):
rm_item_code = rm_item.get("rm_item_code")
items_dict = {
rm_item_code: {
@@ -1142,15 +1146,22 @@
"description": item_wh.get(rm_item_code, {}).get("description", ""),
"qty": rm_item.get("qty")
or max(rm_item.get("required_qty") - rm_item.get("total_supplied_qty"), 0),
- "from_warehouse": rm_item.get("warehouse") or rm_item.get("reserve_warehouse"),
+ "from_warehouse": rm_item.get("warehouse")
+ or rm_item.get("reserve_warehouse"),
"to_warehouse": subcontract_order.supplier_warehouse,
"stock_uom": rm_item.get("stock_uom"),
"serial_and_batch_bundle": rm_item.get("serial_and_batch_bundle"),
"main_item_code": fg_item_code,
- "allow_alternative_item": item_wh.get(rm_item_code, {}).get("allow_alternative_item"),
+ "allow_alternative_item": item_wh.get(rm_item_code, {}).get(
+ "allow_alternative_item"
+ ),
"use_serial_batch_fields": rm_item.get("use_serial_batch_fields"),
- "serial_no": rm_item.get("serial_no") if rm_item.get("use_serial_batch_fields") else None,
- "batch_no": rm_item.get("batch_no") if rm_item.get("use_serial_batch_fields") else None,
+ "serial_no": rm_item.get("serial_no")
+ if rm_item.get("use_serial_batch_fields")
+ else None,
+ "batch_no": rm_item.get("batch_no")
+ if rm_item.get("use_serial_batch_fields")
+ else None,
}
}
@@ -1164,9 +1175,7 @@
frappe.throw(_("No Items selected for transfer."))
-def add_items_in_ste(
- ste_doc, row, qty, rm_details, rm_detail_field="sco_rm_detail", batch_no=None
-):
+def add_items_in_ste(ste_doc, row, qty, rm_details, rm_detail_field="sco_rm_detail", batch_no=None):
item = ste_doc.append("items", row.item_details)
rm_detail = list(set(row.get(f"{rm_detail_field}s")).intersection(rm_details))
@@ -1211,7 +1220,7 @@
ste_doc.company = order_doc.company
ste_doc.is_return = 1
- for key, value in available_materials.items():
+ for _key, value in available_materials.items():
if not value.qty:
continue
@@ -1228,9 +1237,7 @@
@frappe.whitelist()
-def get_materials_from_supplier(
- subcontract_order, rm_details, order_doctype="Subcontracting Order"
-):
+def get_materials_from_supplier(subcontract_order, rm_details, order_doctype="Subcontracting Order"):
if isinstance(rm_details, str):
rm_details = json.loads(rm_details)
@@ -1244,6 +1251,4 @@
_("Materials are already received against the {0} {1}").format(order_doctype, subcontract_order)
)
- return make_return_stock_entry_for_subcontract(
- doc.available_materials, doc, rm_details, order_doctype
- )
+ return make_return_stock_entry_for_subcontract(doc.available_materials, doc, rm_details, order_doctype)
diff --git a/erpnext/controllers/taxes_and_totals.py b/erpnext/controllers/taxes_and_totals.py
index 69d8caa..d90c14a 100644
--- a/erpnext/controllers/taxes_and_totals.py
+++ b/erpnext/controllers/taxes_and_totals.py
@@ -22,7 +22,7 @@
from erpnext.utilities.regional import temporary_flag
-class calculate_taxes_and_totals(object):
+class calculate_taxes_and_totals:
def __init__(self, doc: Document):
self.doc = doc
frappe.flags.round_off_applicable_accounts = []
@@ -160,7 +160,8 @@
elif item.price_list_rate:
if not item.rate or (item.pricing_rules and item.discount_percentage > 0):
item.rate = flt(
- item.price_list_rate * (1.0 - (item.discount_percentage / 100.0)), item.precision("rate")
+ item.price_list_rate * (1.0 - (item.discount_percentage / 100.0)),
+ item.precision("rate"),
)
item.discount_amount = item.price_list_rate * (item.discount_percentage / 100.0)
@@ -181,7 +182,8 @@
item.rate_with_margin, item.base_rate_with_margin = self.calculate_margin(item)
if flt(item.rate_with_margin) > 0:
item.rate = flt(
- item.rate_with_margin * (1.0 - (item.discount_percentage / 100.0)), item.precision("rate")
+ item.rate_with_margin * (1.0 - (item.discount_percentage / 100.0)),
+ item.precision("rate"),
)
if item.discount_amount and not item.discount_percentage:
@@ -197,7 +199,9 @@
item.net_rate = item.rate
if (
- not item.qty and self.doc.get("is_return") and self.doc.get("doctype") != "Purchase Receipt"
+ not item.qty
+ and self.doc.get("is_return")
+ and self.doc.get("doctype") != "Purchase Receipt"
):
item.amount = flt(-1 * item.rate, item.precision("amount"))
elif not item.qty and self.doc.get("is_debit_note"):
@@ -283,7 +287,9 @@
item.net_amount = flt(amount / (1 + cumulated_tax_fraction), item.precision("net_amount"))
item.net_rate = flt(item.net_amount / item.qty, item.precision("net_rate"))
- item.discount_percentage = flt(item.discount_percentage, item.precision("discount_percentage"))
+ item.discount_percentage = flt(
+ item.discount_percentage, item.precision("discount_percentage")
+ )
self._set_in_company_currency(item, ["net_rate", "net_amount"])
@@ -344,7 +350,6 @@
self.doc.round_floats_in(self.doc, ["total", "base_total", "net_total", "base_net_total"])
def calculate_shipping_charges(self):
-
# Do not apply shipping rule for POS
if self.doc.get("is_pos"):
return
@@ -356,9 +361,7 @@
self._calculate()
def calculate_taxes(self):
- rounding_adjustment_computed = self.doc.get("is_consolidated") and self.doc.get(
- "rounding_adjustment"
- )
+ rounding_adjustment_computed = self.doc.get("is_consolidated") and self.doc.get("rounding_adjustment")
if not rounding_adjustment_computed:
self.doc.rounding_adjustment = 0
@@ -398,7 +401,9 @@
# set tax after discount
tax.tax_amount_after_discount_amount += current_tax_amount
- current_tax_amount = self.get_tax_amount_if_for_valuation_or_deduction(current_tax_amount, tax)
+ current_tax_amount = self.get_tax_amount_if_for_valuation_or_deduction(
+ current_tax_amount, tax
+ )
# note: grand_total_for_current_item contains the contribution of
# item's amount, previously applied tax and the current tax on that item
@@ -462,9 +467,7 @@
if tax.charge_type == "Actual":
# distribute the tax amount proportionally to each item row
actual = flt(tax.tax_amount, tax.precision("tax_amount"))
- current_tax_amount = (
- item.net_amount * actual / self.doc.net_total if self.doc.net_total else 0.0
- )
+ current_tax_amount = item.net_amount * actual / self.doc.net_total if self.doc.net_total else 0.0
elif tax.charge_type == "On Net Total":
current_tax_amount = (tax_rate / 100.0) * item.net_amount
@@ -596,9 +599,7 @@
else self.doc.base_net_total
)
- self._set_in_company_currency(
- self.doc, ["taxes_and_charges_added", "taxes_and_charges_deducted"]
- )
+ self._set_in_company_currency(self.doc, ["taxes_and_charges_added", "taxes_and_charges_deducted"])
self.doc.round_floats_in(self.doc, ["grand_total", "base_grand_total"])
@@ -652,12 +653,11 @@
frappe.throw(_("Please select Apply Discount On"))
self.doc.base_discount_amount = flt(
- self.doc.discount_amount * self.doc.conversion_rate, self.doc.precision("base_discount_amount")
+ self.doc.discount_amount * self.doc.conversion_rate,
+ self.doc.precision("base_discount_amount"),
)
- if self.doc.apply_discount_on == "Grand Total" and self.doc.get(
- "is_cash_or_non_trade_discount"
- ):
+ if self.doc.apply_discount_on == "Grand Total" and self.doc.get("is_cash_or_non_trade_discount"):
self.discount_amount_applied = True
return
@@ -682,12 +682,17 @@
or total_for_discount_amount == self.doc.net_total
) and i == len(self._items) - 1:
discount_amount_loss = flt(
- self.doc.net_total - net_total - self.doc.discount_amount, self.doc.precision("net_total")
+ self.doc.net_total - net_total - self.doc.discount_amount,
+ self.doc.precision("net_total"),
)
- item.net_amount = flt(item.net_amount + discount_amount_loss, item.precision("net_amount"))
+ item.net_amount = flt(
+ item.net_amount + discount_amount_loss, item.precision("net_amount")
+ )
- item.net_rate = flt(item.net_amount / item.qty, item.precision("net_rate")) if item.qty else 0
+ item.net_rate = (
+ flt(item.net_amount / item.qty, item.precision("net_rate")) if item.qty else 0
+ )
self._set_in_company_currency(item, ["net_rate", "net_amount"])
@@ -942,7 +947,9 @@
total_paid_amount = 0
for payment in self.doc.get("payments"):
total_paid_amount += (
- payment.amount if self.doc.party_account_currency == self.doc.currency else payment.base_amount
+ payment.amount
+ if self.doc.party_account_currency == self.doc.currency
+ else payment.base_amount
)
pending_amount = total_amount_to_pay - total_paid_amount
@@ -1016,7 +1023,7 @@
@erpnext.allow_regional
def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
- return [_("Item"), _("Taxable Amount")] + tax_accounts
+ return [_("Item"), _("Taxable Amount"), *tax_accounts]
@erpnext.allow_regional
@@ -1084,7 +1091,7 @@
row["tax_amount"] = flt(row["tax_amount"], precision)
-class init_landed_taxes_and_totals(object):
+class init_landed_taxes_and_totals:
def __init__(self, doc):
self.doc = doc
self.tax_field = "taxes" if self.doc.doctype == "Landed Cost Voucher" else "additional_costs"
diff --git a/erpnext/controllers/tests/test_accounts_controller.py b/erpnext/controllers/tests/test_accounts_controller.py
index 2170628..2105a3e 100644
--- a/erpnext/controllers/tests/test_accounts_controller.py
+++ b/erpnext/controllers/tests/test_accounts_controller.py
@@ -1,18 +1,15 @@
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
-import unittest
import frappe
from frappe import qb
from frappe.query_builder.functions import Sum
-from frappe.tests.utils import FrappeTestCase, change_settings
-from frappe.utils import add_days, flt, getdate, nowdate
+from frappe.tests.utils import FrappeTestCase
+from frappe.utils import add_days, getdate, nowdate
-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.stock.doctype.item.test_item import create_item
@@ -173,9 +170,7 @@
)
return sinv
- def create_payment_entry(
- self, amount=1, source_exc_rate=75, posting_date=nowdate(), customer=None
- ):
+ def create_payment_entry(self, amount=1, source_exc_rate=75, posting_date=nowdate(), customer=None):
"""
Helper function to populate default values in payment entry
"""
@@ -293,9 +288,7 @@
.run(as_dict=True)[0]
)
self.assertEqual(outstanding, current_outstanding.outstanding)
- self.assertEqual(
- outstanding_in_account_currency, current_outstanding.outstanding_in_account_currency
- )
+ self.assertEqual(outstanding_in_account_currency, current_outstanding.outstanding_in_account_currency)
def test_10_payment_against_sales_invoice(self):
# Sales Invoice in Foreign Currency
@@ -401,7 +394,6 @@
adv.reload()
# sales invoice with advance(partial amount)
- rate = 80
rate_in_account_currency = 1
si = self.create_sales_invoice(
qty=2, conversion_rate=80, rate=rate_in_account_currency, do_not_submit=True
@@ -788,7 +780,9 @@
self.assert_ledger_outstanding(si.doctype, si.name, 0.0, 0.0)
# Exchange Gain/Loss Journal should've been created.
- exc_je_for_si = [x for x in self.get_journals_for(si.doctype, si.name) if x.parent != adv.name]
+ exc_je_for_si = [
+ x for x in self.get_journals_for(si.doctype, si.name) if x.parent != adv.name
+ ]
exc_je_for_adv = self.get_journals_for(adv.doctype, adv.name)
self.assertNotEqual(exc_je_for_si, [])
self.assertEqual(len(exc_je_for_si), 1)
@@ -1253,7 +1247,9 @@
with self.subTest(x=x):
self.assertEqual(
[self.cost_center, self.cost_center],
- frappe.db.get_all("Journal Entry Account", filters={"parent": x.parent}, pluck="cost_center"),
+ frappe.db.get_all(
+ "Journal Entry Account", filters={"parent": x.parent}, pluck="cost_center"
+ ),
)
frappe.db.set_value("Company", self.company, "cost_center", cc)
@@ -1382,13 +1378,14 @@
with self.subTest(x=x):
self.assertEqual(
[cr_note.department, cr_note.department],
- frappe.db.get_all("Journal Entry Account", filters={"parent": x.parent}, pluck="department"),
+ frappe.db.get_all(
+ "Journal Entry Account", filters={"parent": x.parent}, pluck="department"
+ ),
)
def test_92_dimension_inhertiance_exc_gain_loss(self):
# Sales Invoice in Foreign Currency
self.setup_dimensions()
- rate = 80
rate_in_account_currency = 1
dpt = "Research & Development"
diff --git a/erpnext/controllers/tests/test_mapper.py b/erpnext/controllers/tests/test_mapper.py
index 919bcda..9dbcf6c 100644
--- a/erpnext/controllers/tests/test_mapper.py
+++ b/erpnext/controllers/tests/test_mapper.py
@@ -29,7 +29,6 @@
self.assertEqual(set(d for d in src_items), set(d.item_code for d in updated_so.items))
def make_quotation(self, item_list, customer):
-
qtn = frappe.get_doc(
{
"doctype": "Quotation",
diff --git a/erpnext/controllers/tests/test_qty_based_taxes.py b/erpnext/controllers/tests/test_qty_based_taxes.py
index 2e9dfd2..e7896b5 100644
--- a/erpnext/controllers/tests/test_qty_based_taxes.py
+++ b/erpnext/controllers/tests/test_qty_based_taxes.py
@@ -25,7 +25,7 @@
"account_name": uuid4(),
"account_type": "Tax",
"company": self.company.name,
- "parent_account": "Duties and Taxes - {self.company.abbr}".format(self=self),
+ "parent_account": f"Duties and Taxes - {self.company.abbr}",
}
).insert()
self.item_group = frappe.get_doc(
diff --git a/erpnext/controllers/tests/test_queries.py b/erpnext/controllers/tests/test_queries.py
index c536d1c..0ef108e 100644
--- a/erpnext/controllers/tests/test_queries.py
+++ b/erpnext/controllers/tests/test_queries.py
@@ -7,13 +7,10 @@
def add_default_params(func, doctype):
- return partial(
- func, doctype=doctype, txt="", searchfield="name", start=0, page_len=20, filters=None
- )
+ return partial(func, doctype=doctype, txt="", searchfield="name", start=0, page_len=20, filters=None)
class TestQueries(unittest.TestCase):
-
# All tests are based on doctype/test_records.json
def assert_nested_in(self, item, container):
diff --git a/erpnext/controllers/tests/test_subcontracting_controller.py b/erpnext/controllers/tests/test_subcontracting_controller.py
index 7374e1e..b0c57e9 100644
--- a/erpnext/controllers/tests/test_subcontracting_controller.py
+++ b/erpnext/controllers/tests/test_subcontracting_controller.py
@@ -16,8 +16,6 @@
from erpnext.manufacturing.doctype.production_plan.test_production_plan import make_bom
from erpnext.stock.doctype.item.test_item import make_item
from erpnext.stock.doctype.serial_and_batch_bundle.test_serial_and_batch_bundle import (
- get_batch_from_bundle,
- get_serial_nos_from_bundle,
make_serial_batch_bundle,
)
from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
@@ -351,7 +349,6 @@
- Create the 3 SCR against the SCO and split Subcontracted Items into two batches.
- Keep the qty as 2 for Subcontracted Item in the SCR.
"""
- from erpnext.stock.serial_batch_bundle import get_batch_nos
set_backflush_based_on("BOM")
service_items = [
@@ -434,7 +431,7 @@
scr1.set_missing_values()
scr1.submit()
- for key, value in get_supplied_items(scr1).items():
+ for _key, value in get_supplied_items(scr1).items():
self.assertEqual(value.qty, 4)
frappe.flags.add_debugger = True
@@ -446,7 +443,7 @@
scr2.set_missing_values()
scr2.submit()
- for key, value in get_supplied_items(scr2).items():
+ for _key, value in get_supplied_items(scr2).items():
self.assertEqual(value.qty, 4)
scr3 = make_subcontracting_receipt(sco.name)
@@ -456,7 +453,7 @@
scr3.set_missing_values()
scr3.submit()
- for key, value in get_supplied_items(scr3).items():
+ for _key, value in get_supplied_items(scr3).items():
self.assertEqual(value.qty, 2)
def test_item_with_batch_based_on_material_transfer(self):
@@ -700,9 +697,7 @@
scr1 = make_subcontracting_receipt(sco.name)
scr1.save()
- bundle = frappe.get_doc(
- "Serial and Batch Bundle", scr1.supplied_items[0].serial_and_batch_bundle
- )
+ bundle = frappe.get_doc("Serial and Batch Bundle", scr1.supplied_items[0].serial_and_batch_bundle)
original_serial_no = ""
for row in bundle.entries:
if row.idx == 1:
@@ -773,7 +768,6 @@
scr1.items[0].qty = 5
scr1.save()
- transferred_batch_no = ""
for key, value in get_supplied_items(scr1).items():
details = itemwise_details.get(key)
self.assertEqual(value.qty, 3)
@@ -1139,9 +1133,7 @@
def update_item_details(child_row, details):
details.qty += (
- child_row.get("qty")
- if child_row.doctype == "Stock Entry Detail"
- else child_row.get("consumed_qty")
+ child_row.get("qty") if child_row.doctype == "Stock Entry Detail" else child_row.get("consumed_qty")
)
details.use_serial_batch_fields = child_row.get("use_serial_batch_fields")
@@ -1152,7 +1144,9 @@
details.serial_no.append(row.serial_no)
if row.batch_no:
- details.batch_no[row.batch_no] += row.qty * (-1 if doc.type_of_transaction == "Outward" else 1)
+ details.batch_no[row.batch_no] += row.qty * (
+ -1 if doc.type_of_transaction == "Outward" else 1
+ )
else:
if child_row.serial_no:
details.serial_no.extend(get_serial_nos(child_row.serial_no))
@@ -1268,7 +1262,9 @@
make_item(item, properties)
-def make_service_item(item, properties={}):
+def make_service_item(item, properties=None):
+ if properties is None:
+ properties = {}
if not frappe.db.exists("Item", item):
properties.update({"is_stock_item": 0})
make_item(item, properties)
@@ -1316,9 +1312,7 @@
def set_backflush_based_on(based_on):
- frappe.db.set_single_value(
- "Buying Settings", "backflush_raw_materials_of_subcontract_based_on", based_on
- )
+ frappe.db.set_single_value("Buying Settings", "backflush_raw_materials_of_subcontract_based_on", based_on)
def get_subcontracting_order(**args):
diff --git a/erpnext/controllers/tests/test_transaction_base.py b/erpnext/controllers/tests/test_transaction_base.py
index 1471543..ab5525a 100644
--- a/erpnext/controllers/tests/test_transaction_base.py
+++ b/erpnext/controllers/tests/test_transaction_base.py
@@ -44,7 +44,10 @@
item_code="_Test Item", qty=1, basic_rate=200, s_warehouse="_Test Warehouse - _TC"
),
frappe._dict(
- item_code="_Test FG Item", qty=4, t_warehouse="_Test Warehouse 1 - _TC", is_finished_item=1
+ item_code="_Test FG Item",
+ qty=4,
+ t_warehouse="_Test Warehouse 1 - _TC",
+ is_finished_item=1,
),
],
)
diff --git a/erpnext/controllers/trends.py b/erpnext/controllers/trends.py
index 1fb722e..18fe776 100644
--- a/erpnext/controllers/trends.py
+++ b/erpnext/controllers/trends.py
@@ -100,12 +100,11 @@
else:
inc = 1
data1 = frappe.db.sql(
- """ select %s from `tab%s` t1, `tab%s Item` t2 %s
- where t2.parent = t1.name and t1.company = %s and %s between %s and %s and
- t1.docstatus = 1 %s %s
- group by %s
- """
- % (
+ """ select {} from `tab{}` t1, `tab{} Item` t2 {}
+ where t2.parent = t1.name and t1.company = {} and {} between {} and {} and
+ t1.docstatus = 1 {} {}
+ group by {}
+ """.format(
query_details,
conditions["trans"],
conditions["trans"],
@@ -130,11 +129,10 @@
# to get distinct value of col specified by group_by in filter
row = frappe.db.sql(
- """select DISTINCT(%s) from `tab%s` t1, `tab%s Item` t2 %s
- where t2.parent = t1.name and t1.company = %s and %s between %s and %s
- and t1.docstatus = 1 and %s = %s %s %s
- """
- % (
+ """select DISTINCT({}) from `tab{}` t1, `tab{} Item` t2 {}
+ where t2.parent = t1.name and t1.company = {} and {} between {} and {}
+ and t1.docstatus = 1 and {} = {} {} {}
+ """.format(
sel_col,
conditions["trans"],
conditions["trans"],
@@ -157,11 +155,10 @@
# get data for group_by filter
row1 = frappe.db.sql(
- """ select %s , %s from `tab%s` t1, `tab%s Item` t2 %s
- where t2.parent = t1.name and t1.company = %s and %s between %s and %s
- and t1.docstatus = 1 and %s = %s and %s = %s %s %s
- """
- % (
+ """ select {} , {} from `tab{}` t1, `tab{} Item` t2 {}
+ where t2.parent = t1.name and t1.company = {} and {} between {} and {}
+ and t1.docstatus = 1 and {} = {} and {} = {} {} {}
+ """.format(
sel_col,
conditions["period_wise_select"],
conditions["trans"],
@@ -190,12 +187,11 @@
data.append(des)
else:
data = frappe.db.sql(
- """ select %s from `tab%s` t1, `tab%s Item` t2 %s
- where t2.parent = t1.name and t1.company = %s and %s between %s and %s and
- t1.docstatus = 1 %s %s
- group by %s
- """
- % (
+ """ select {} from `tab{}` t1, `tab{} Item` t2 {}
+ where t2.parent = t1.name and t1.company = {} and {} between {} and {} and
+ t1.docstatus = 1 {} {}
+ group by {}
+ """.format(
query_details,
conditions["trans"],
conditions["trans"],
@@ -260,13 +256,13 @@
def get_period_wise_query(bet_dates, trans_date, query_details):
- query_details += """SUM(IF(t1.%(trans_date)s BETWEEN '%(sd)s' AND '%(ed)s', t2.stock_qty, NULL)),
- SUM(IF(t1.%(trans_date)s BETWEEN '%(sd)s' AND '%(ed)s', t2.base_net_amount, NULL)),
- """ % {
- "trans_date": trans_date,
- "sd": bet_dates[0],
- "ed": bet_dates[1],
- }
+ query_details += """SUM(IF(t1.{trans_date} BETWEEN '{sd}' AND '{ed}', t2.stock_qty, NULL)),
+ SUM(IF(t1.{trans_date} BETWEEN '{sd}' AND '{ed}', t2.base_net_amount, NULL)),
+ """.format(
+ trans_date=trans_date,
+ sd=bet_dates[0],
+ ed=bet_dates[1],
+ )
return query_details
@@ -282,7 +278,7 @@
increment = {"Monthly": 1, "Quarterly": 3, "Half-Yearly": 6, "Yearly": 12}.get(period)
period_date_ranges = []
- for i in range(1, 13, increment):
+ for _i in range(1, 13, increment):
period_end_date = getdate(year_start_date) + relativedelta(months=increment, days=-1)
if period_end_date > getdate(year_end_date):
period_end_date = year_end_date
@@ -331,9 +327,7 @@
"Territory:Link/Territory:120",
]
based_on_details["based_on_select"] = "t1.customer_name, t1.territory, "
- based_on_details["based_on_group_by"] = (
- "t1.party_name" if trans == "Quotation" else "t1.customer"
- )
+ based_on_details["based_on_group_by"] = "t1.party_name" if trans == "Quotation" else "t1.customer"
based_on_details["addl_tables"] = ""
elif based_on == "Customer Group":
diff --git a/erpnext/controllers/website_list_for_contact.py b/erpnext/controllers/website_list_for_contact.py
index 0a0abda..f5cbf67 100644
--- a/erpnext/controllers/website_list_for_contact.py
+++ b/erpnext/controllers/website_list_for_contact.py
@@ -81,9 +81,7 @@
filters["docstatus"] = ["<", "2"] if doctype in ["Supplier Quotation", "Purchase Invoice"] else 1
if (user != "Guest" and is_website_user()) or doctype == "Request for Quotation":
- parties_doctype = (
- "Request for Quotation Supplier" if doctype == "Request for Quotation" else doctype
- )
+ parties_doctype = "Request for Quotation Supplier" if doctype == "Request for Quotation" else doctype
# find party for this contact
customers, suppliers = get_customers_suppliers(parties_doctype, user)
@@ -303,6 +301,4 @@
return
user_doc.add_roles(role)
- frappe.msgprint(
- _("Added {1} Role to User {0}.").format(frappe.bold(user_doc.name), role), alert=True
- )
+ frappe.msgprint(_("Added {1} Role to User {0}.").format(frappe.bold(user_doc.name), role), alert=True)