refactor(treewide): formatting and ruff fixes, + manually enabled F401

Signed-off-by: Akhil Narang <me@akhilnarang.dev>
This commit is contained in:
Akhil Narang
2024-03-27 11:37:26 +05:30
parent c28d19cf7f
commit 4d34b1ead7
618 changed files with 4188 additions and 6384 deletions

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt

View File

@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import unittest
import frappe
from frappe.core.doctype.user_permission.test_user_permission import create_user

View File

@@ -1,8 +1,6 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import unittest
import frappe
@@ -347,9 +345,7 @@ class TestWebsiteItem(FrappeTestCase):
)
# stock up item
stock_entry = make_stock_entry(
item_code=item_code, target="_Test Warehouse - _TC", qty=2, rate=100
)
stock_entry = make_stock_entry(item_code=item_code, target="_Test Warehouse - _TC", qty=2, rate=100)
# check if stock details are fetched and item is in stock with warehouse set
data = get_product_info_for_website(item_code, skip_quotation_creation=True)
@@ -429,9 +425,7 @@ class TestWebsiteItem(FrappeTestCase):
web_item = create_regular_web_item(item_code)
# price visible to guests
setup_e_commerce_settings(
{"enable_recommendations": 1, "show_price": 1, "hide_price_for_guest": 0}
)
setup_e_commerce_settings({"enable_recommendations": 1, "show_price": 1, "hide_price_for_guest": 0})
# create recommended web item and price for it
recommended_web_item = create_regular_web_item("Test Mobile Phone 1")

View File

@@ -1,9 +1,8 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import json
from typing import TYPE_CHECKING, List, Union
from typing import TYPE_CHECKING, Union
if TYPE_CHECKING:
from erpnext.stock.doctype.item.item import Item
@@ -45,10 +44,10 @@ class WebsiteItem(WebsiteGenerator):
self.name = make_autoname(naming_series, doc=self)
def onload(self):
super(WebsiteItem, self).onload()
super().onload()
def validate(self):
super(WebsiteItem, self).validate()
super().validate()
if not self.item_code:
frappe.throw(_("Item Code is required"), title=_("Mandatory"))
@@ -78,7 +77,7 @@ class WebsiteItem(WebsiteGenerator):
self.update_template_item()
def on_trash(self):
super(WebsiteItem, self).on_trash()
super().on_trash()
delete_item_from_index(self)
self.publish_unpublish_desk_item(publish=False)
@@ -197,7 +196,7 @@ class WebsiteItem(WebsiteGenerator):
}
).save()
except IOError:
except OSError:
self.website_image = None
if file_doc:
@@ -234,9 +233,7 @@ class WebsiteItem(WebsiteGenerator):
context.reviews = context.reviews[:4]
context.wished = False
if frappe.db.exists(
"Wishlist Item", {"item_code": self.item_code, "parent": frappe.session.user}
):
if frappe.db.exists("Wishlist Item", {"item_code": self.item_code, "parent": frappe.session.user}):
context.wished = True
context.user_is_customer = check_if_user_is_customer()
@@ -256,9 +253,7 @@ class WebsiteItem(WebsiteGenerator):
)
# make an attribute-value map for easier access in templates
variant.attribute_map = frappe._dict(
{attr.attribute: attr.value for attr in variant.attributes}
)
variant.attribute_map = frappe._dict({attr.attribute: attr.value for attr in variant.attributes})
for attr in variant.attributes:
values = attribute_values_available.setdefault(attr.attribute, [])
@@ -283,7 +278,6 @@ class WebsiteItem(WebsiteGenerator):
filters={"parent": attr.attribute},
order_by="idx asc",
):
if attr_value.attribute_value in attribute_values_available.get(attr.attribute, []):
values.append(attr_value.attribute_value)
@@ -311,9 +305,7 @@ class WebsiteItem(WebsiteGenerator):
def set_shopping_cart_data(self, context):
from erpnext.e_commerce.shopping_cart.product_info import get_product_info_for_website
context.shopping_cart = get_product_info_for_website(
self.item_code, skip_quotation_creation=True
)
context.shopping_cart = get_product_info_for_website(self.item_code, skip_quotation_creation=True)
@frappe.whitelist()
def copy_specification_from_item_group(self):
@@ -425,7 +417,7 @@ def check_if_user_is_customer(user=None):
@frappe.whitelist()
def make_website_item(doc: "Item", save: bool = True) -> Union["WebsiteItem", List[str]]:
def make_website_item(doc: "Item", save: bool = True) -> Union["WebsiteItem", list[str]]:
"Make Website Item from Item. Used via Form UI or patch."
if not doc:

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import unittest
@@ -42,17 +41,13 @@ class TestWishlist(unittest.TestCase):
# add second item to wishlist
add_to_wishlist("Test Phone Series Y")
wishlist_length = frappe.db.get_value(
"Wishlist Item", {"parent": frappe.session.user}, "count(*)"
)
wishlist_length = frappe.db.get_value("Wishlist Item", {"parent": frappe.session.user}, "count(*)")
self.assertEqual(wishlist_length, 2)
remove_from_wishlist("Test Phone Series X")
remove_from_wishlist("Test Phone Series Y")
wishlist_length = frappe.db.get_value(
"Wishlist Item", {"parent": frappe.session.user}, "count(*)"
)
wishlist_length = frappe.db.get_value("Wishlist Item", {"parent": frappe.session.user}, "count(*)")
self.assertIsNone(frappe.db.exists("Wishlist Item", {"parent": frappe.session.user}))
self.assertEqual(wishlist_length, 0)
@@ -75,9 +70,7 @@ class TestWishlist(unittest.TestCase):
# check wishlist and its content for users
self.assertTrue(frappe.db.exists("Wishlist", {"user": test_user.name}))
self.assertTrue(
frappe.db.exists(
"Wishlist Item", {"item_code": "Test Phone Series X", "parent": test_user.name}
)
frappe.db.exists("Wishlist Item", {"item_code": "Test Phone Series X", "parent": test_user.name})
)
self.assertTrue(frappe.db.exists("Wishlist", {"user": test_user_1.name}))
@@ -97,18 +90,14 @@ class TestWishlist(unittest.TestCase):
)
)
self.assertTrue(
frappe.db.exists(
"Wishlist Item", {"item_code": "Test Phone Series X", "parent": test_user.name}
)
frappe.db.exists("Wishlist Item", {"item_code": "Test Phone Series X", "parent": test_user.name})
)
# remove item for first user
frappe.set_user(test_user.name)
remove_from_wishlist("Test Phone Series X")
self.assertFalse(
frappe.db.exists(
"Wishlist Item", {"item_code": "Test Phone Series X", "parent": test_user.name}
)
frappe.db.exists("Wishlist Item", {"item_code": "Test Phone Series X", "parent": test_user.name})
)
# tear down

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt

View File

@@ -114,9 +114,7 @@ class ProductSearch(FullTextSearch):
def get_all_published_items():
return frappe.get_all(
"Website Item", filters={"variant_of": "", "published": 1}, pluck="item_code"
)
return frappe.get_all("Website Item", filters={"variant_of": "", "published": 1}, pluck="item_code")
def update_index_for_path(path):

View File

@@ -24,9 +24,7 @@ class ProductFiltersBuilder:
# filter valid field filters i.e. those that exist in Website Item
web_item_meta = frappe.get_meta("Website Item", cached=True)
fields = [
web_item_meta.get_field(field) for field in filter_fields if web_item_meta.has_field(field)
]
fields = [web_item_meta.get_field(field) for field in filter_fields if web_item_meta.has_field(field)]
for df in fields:
item_filters, item_or_filters = {"published": 1}, []
@@ -41,14 +39,24 @@ class ProductFiltersBuilder:
item_or_filters.extend(
[
["item_group", "in", include_groups],
["Website Item Group", "item_group", "=", self.item_group], # consider website item groups
[
"Website Item Group",
"item_group",
"=",
self.item_group,
], # consider website item groups
]
)
else:
item_or_filters.extend(
[
["item_group", "=", self.item_group],
["Website Item Group", "item_group", "=", self.item_group], # consider website item groups
[
"Website Item Group",
"item_group",
"=",
self.item_group,
], # consider website item groups
]
)

View File

@@ -56,7 +56,7 @@ class ProductQuery:
"""
# track if discounts included in field filters
self.filter_with_discount = bool(fields.get("discount"))
result, discount_list, website_item_groups, cart_items, count = [], [], [], [], 0
result, discount_list, _website_item_groups, cart_items, count = [], [], [], [], 0
if fields:
self.build_fields_filters(fields)
@@ -215,7 +215,7 @@ class ProductQuery:
search_fields.discard("web_long_description")
# Build or filters for query
search = "%{}%".format(search_term)
search = f"%{search_term}%"
for field in search_fields:
self.or_filters.append([field, "like", search])

View File

@@ -136,9 +136,7 @@ class TestProductDataEngine(unittest.TestCase):
field_filters = {"item_group": "Raw Material"}
engine = ProductQuery()
result = engine.query(
attributes={}, fields=field_filters, search_term=None, start=0, item_group=None
)
result = engine.query(attributes={}, fields=field_filters, search_term=None, start=0, item_group=None)
items = result.get("items")
# check if only 'Raw Material' are fetched in the right order
@@ -229,9 +227,7 @@ class TestProductDataEngine(unittest.TestCase):
frappe.local.shopping_cart_settings = None
engine = ProductQuery()
result = engine.query(
attributes={}, fields=field_filters, search_term=None, start=0, item_group=None
)
result = engine.query(attributes={}, fields=field_filters, search_term=None, start=0, item_group=None)
items = result.get("items")
# check if only product with 10% and below discount are fetched
@@ -293,12 +289,8 @@ class TestProductDataEngine(unittest.TestCase):
),
)
frappe.db.set_value(
"Website Item", {"item_code": "Test 11I Laptop"}, "supplier", "_Test Supplier"
)
frappe.db.set_value(
"Website Item", {"item_code": "Test 12I Laptop"}, "supplier", "_Test Supplier 1"
)
frappe.db.set_value("Website Item", {"item_code": "Test 11I Laptop"}, "supplier", "_Test Supplier")
frappe.db.set_value("Website Item", {"item_code": "Test 12I Laptop"}, "supplier", "_Test Supplier 1")
settings = frappe.get_doc("E Commerce Settings")
settings.append("filter_fields", {"fieldname": "supplier"})
@@ -316,9 +308,7 @@ class TestProductDataEngine(unittest.TestCase):
# test if custom filter works in query
field_filters = {"supplier": "_Test Supplier 1"}
engine = ProductQuery()
result = engine.query(
attributes={}, fields=field_filters, search_term=None, start=0, item_group=None
)
result = engine.query(attributes={}, fields=field_filters, search_term=None, start=0, item_group=None)
items = result.get("items")
# check if only 'Raw Material' are fetched in the right order

View File

@@ -38,7 +38,7 @@ def is_search_module_loaded():
out = cache.execute_command("MODULE LIST")
parsed_output = " ".join(
(" ".join([frappe.as_unicode(s) for s in o if not isinstance(s, int)]) for o in out)
" ".join([frappe.as_unicode(s) for s in o if not isinstance(s, int)]) for o in out
)
return "search" in parsed_output
except Exception:
@@ -58,7 +58,7 @@ def if_redisearch_enabled(function):
def make_key(key):
return "{0}|{1}".format(frappe.conf.db_name, key).encode("utf-8")
return f"{frappe.conf.db_name}|{key}".encode()
@if_redisearch_enabled
@@ -89,7 +89,7 @@ def create_website_items_index():
idx_fields = list(map(to_search_field, idx_fields))
client.create_index(
[TextField("web_item_name", sortable=True)] + idx_fields,
[TextField("web_item_name", sortable=True), *idx_fields],
definition=idx_def,
)
@@ -187,9 +187,7 @@ def define_autocomplete_dictionary():
@if_redisearch_enabled
def create_items_autocomplete_dict(autocompleter):
"Add items as suggestions in Autocompleter."
items = frappe.get_all(
"Website Item", fields=["web_item_name", "item_group"], filters={"published": 1}
)
items = frappe.get_all("Website Item", fields=["web_item_name", "item_group"], filters={"published": 1})
for item in items:
autocompleter.add_suggestions(Suggestion(item.web_item_name))
@@ -248,6 +246,4 @@ def raise_redisearch_error():
log = frappe.log_error("Redisearch Error")
log_link = frappe.utils.get_link_to_form("Error Log", log.name)
frappe.throw(
msg=_("Something went wrong. Check {0}").format(log_link), title=_("Redisearch Error")
)
frappe.throw(msg=_("Something went wrong. Check {0}").format(log_link), title=_("Redisearch Error"))

View File

@@ -150,9 +150,7 @@ def update_cart(item_code, qty, additional_notes=None, with_items=False):
empty_card = True
else:
warehouse = frappe.get_cached_value(
"Website Item", {"item_code": item_code}, "website_warehouse"
)
warehouse = frappe.get_cached_value("Website Item", {"item_code": item_code}, "website_warehouse")
quotation_items = quotation.get("items", {"item_code": item_code})
if not quotation_items:
@@ -243,14 +241,12 @@ def create_lead_for_item_inquiry(lead, subject, message):
lead_doc.add_comment(
"Comment",
text="""
text=f"""
<div>
<h5>{subject}</h5>
<p>{message}</p>
</div>
""".format(
subject=subject, message=message
),
""",
)
return lead_doc
@@ -276,9 +272,7 @@ def update_cart_address(address_type, address_name):
quotation.shipping_address_name = address_name
quotation.shipping_address = address_display
quotation.customer_address = quotation.customer_address or address_name
address_doc = next(
(doc for doc in get_shipping_addresses() if doc["name"] == address_name), None
)
address_doc = next((doc for doc in get_shipping_addresses() if doc["name"] == address_name), None)
apply_cart_settings(quotation=quotation)
quotation.flags.ignore_permissions = True
@@ -300,9 +294,7 @@ def guess_territory():
territory = frappe.db.get_value("Territory", geoip_country)
return (
territory
or frappe.db.get_value("E Commerce Settings", None, "territory")
or get_root_of("Territory")
territory or frappe.db.get_value("E Commerce Settings", None, "territory") or get_root_of("Territory")
)
@@ -591,9 +583,7 @@ def get_debtors_account(cart_settings):
return debtors_account_name
def get_address_docs(
doctype=None, txt=None, filters=None, limit_start=0, limit_page_length=20, party=None
):
def get_address_docs(doctype=None, txt=None, filters=None, limit_start=0, limit_page_length=20, party=None):
if not party:
party = get_party()

View File

@@ -29,9 +29,7 @@ def get_product_info_for_website(item_code, skip_quotation_creation=False):
cart_quotation = _get_cart_quotation()
selling_price_list = (
cart_quotation.get("selling_price_list")
if cart_quotation
else _set_price_list(cart_settings, None)
cart_quotation.get("selling_price_list") if cart_quotation else _set_price_list(cart_settings, None)
)
price = {}

View File

@@ -44,9 +44,7 @@ class TestShoppingCart(unittest.TestCase):
frappe.db.sql("delete from `tabTax Rule`")
def test_get_cart_new_user(self):
self.login_as_customer(
"test_contact_two_customer@example.com", "_Test Contact 2 For _Test Customer"
)
self.login_as_customer("test_contact_two_customer@example.com", "_Test Contact 2 For _Test Customer")
create_address_and_contact(
address_title="_Test Address for Customer 2",
first_name="_Test Contact for Customer 2",
@@ -79,9 +77,7 @@ class TestShoppingCart(unittest.TestCase):
return quotation
def test_add_to_cart(self):
self.login_as_customer(
"test_contact_two_customer@example.com", "_Test Contact 2 For _Test Customer"
)
self.login_as_customer("test_contact_two_customer@example.com", "_Test Contact 2 For _Test Customer")
create_address_and_contact(
address_title="_Test Address for Customer 2",
first_name="_Test Contact for Customer 2",
@@ -140,9 +136,7 @@ class TestShoppingCart(unittest.TestCase):
def test_tax_rule(self):
self.create_tax_rule()
self.login_as_customer(
"test_contact_two_customer@example.com", "_Test Contact 2 For _Test Customer"
)
self.login_as_customer("test_contact_two_customer@example.com", "_Test Contact 2 For _Test Customer")
create_address_and_contact(
address_title="_Test Address for Customer 2",
first_name="_Test Contact for Customer 2",

View File

@@ -6,10 +6,7 @@ from erpnext.e_commerce.doctype.e_commerce_settings.e_commerce_settings import i
def show_cart_count():
if (
is_cart_enabled()
and frappe.db.get_value("User", frappe.session.user, "user_type") == "Website User"
):
if is_cart_enabled() and frappe.db.get_value("User", frappe.session.user, "user_type") == "Website User":
return True
return False

View File

@@ -35,7 +35,7 @@ def get_item_codes_by_attributes(attribute_filters, template_item_code=None):
else:
variant_of_query = ""
query = """
query = f"""
SELECT
t1.parent
FROM
@@ -58,9 +58,7 @@ def get_item_codes_by_attributes(attribute_filters, template_item_code=None):
t1.parent
ORDER BY
NULL
""".format(
attribute_query=attribute_query, variant_of_query=variant_of_query
)
"""
item_codes = set([r[0] for r in frappe.db.sql(query, query_values)]) # nosemgrep
items.append(item_codes)
@@ -175,12 +173,10 @@ def get_next_attribute_and_values(item_code, selected_attributes):
if exact_match and len(exact_match) == 1:
product_id = exact_match[0]
elif filtered_items_count == 1:
product_id = list(filtered_items)[0]
product_id = next(iter(filtered_items))
if product_id:
warehouse = frappe.get_cached_value(
"Website Item", {"item_code": product_id}, "website_warehouse"
)
warehouse = frappe.get_cached_value("Website Item", {"item_code": product_id}, "website_warehouse")
available_qty = 0.0
if warehouse and frappe.get_cached_value("Warehouse", warehouse, "is_group") == 1: