if self.payd_from == "Employee":
# Create or retrieve the individual Customer
customer_doc = self.create_customer(
customer_name=self._full_name,
customer_type="Individual",
email=self.email,
customer_group="Applicants"
)
else:
# Create or retrieve the company Customer
customer_doc = self.create_customer(
customer_name=self.company_name,
customer_type="Company",
email=self.company_email,
customer_group="Companies"
)
customer_name = customer_doc.name
# Now create the Sales Invoice with the correct Customer identifier
sales_invoice_name = self.create_sales_invoice(customer_name)
# Proceed to create Verification Instructions Request
self.create_verification_instructions_request(sales_invoice_name)
def on_cancel(self):
pass
def add_full_name(self):
middle_name = self.middle_name
if self.middle_name == None:
middle_name = ""
self._full_name = f"{self.first_name} {middle_name} {self.last_name}"
def add_company_information(self):
user = frappe.get_doc("User", frappe.session.user)
self.db_set("company_name",user.full_name)
if user.full_name == "Administrator":
self.db_set("company_email","administrator")
else :
self.db_set("company_email",user.email)
def create_user(self):
if frappe.db.exists("User", {"email":self.email}):
return True
else:
new_doc = frappe.new_doc("User")
new_doc.email = self.email
new_doc.first_name = self.first_name
new_doc.last_name = self.last_name
new_doc.middle_name = self.middle_name
new_doc.enabled = True
new_doc.language = self.language
new_doc.module_profile = ""
new_doc.role_profile_name = "Applicant"
new_doc.insert(ignore_permissions = True)
return new_doc
def create_customer(self, customer_name, customer_type, email, customer_group):
"""Creates a Customer if not exists and returns the Customer document.
Args:
customer_name (str): The name of the customer.
customer_type (str): Type of customer. Accepted values: "Individual", "Company".
email (str): The email of the customer.
customer_group (str): The customer group. E.g., "Applicants", "Companies".
Returns:
doc: A Frappe Customer document.
"""
if frappe.db.exists(
"Customer",
{
"customer_name": customer_name,
"email": email
}):
frappe.logger().debug(f"Customer '{customer_name}' already exists.")
customer_doc = frappe.get_doc("Customer", {"customer_name": customer_name})
else:
new_doc = frappe.new_doc("Customer")
new_doc.customer_name = customer_name
new_doc.customer_type = customer_type
new_doc.customer_group = customer_group
new_doc.email = email
new_doc.insert(ignore_permissions=True)
customer_doc = new_doc
frappe.logger().debug(f"Customer Created: {customer_doc.name}")
return customer_doc
def create_verification_instructions_request(self,sales_invoice_name):
new_doc = frappe.new_doc("Verification Instructions Request")
new_doc.payd_from = self.payd_from
new_doc.user_id = self.email
new_doc.company_submitting_application = self.company_email
new_doc.language = self.language
new_doc.sales_invoice = sales_invoice_name
# new_doc.sales_invoice = sales_invoice_name
new_doc.insert(ignore_permissions = True)
return new_doc
def create_sales_invoice(self,customer):
if not customer:
frappe.throw(_("Customer is not set. Cannot create Sales Invoice.") )
sales_invoice = frappe.get_doc(
{
"doctype": "Sales Invoice",
"customer": customer,
}
)
self.preparing_the_sales_invoice(self.other_services, sales_invoice)
sales_invoice.save(ignore_permissions = True)
return sales_invoice
def preparing_the_sales_invoice(self, list_items, sales_invoice):
for i in list_items:
is_stock_item = frappe.get_value("Item", i.service, "is_stock_item")
if is_stock_item:
sales_invoice.append(
"items",
{
"item_code": i.service,
"qty": 1,
"uom":"Nos",
},
)
elif bundle := frappe.db.exists("Product Bundle", {"new_item_code": i.service}):
self.preparing(bundle, sales_invoice)
if self.package:
self.preparing(self.package, sales_invoice)
def preparing(self, bundle, sales_invoice):
bundle = frappe.get_doc("Product Bundle", bundle)
for b_i in bundle.items:
sales_invoice.append(
"items",
{
"item_code": b_i.item_code,
"qty": 1,
"uom":"Nos",
},
)
def get_item_price(self,item):
try:
price_data = frappe.db.get_list(
"Item Price",
fields=['price_list_rate'],
filters={'item_code': item},
limit=1
)
# Check if we got any results
if price_data:
return price_data[0].price_list_rate # Extracting the price
else:
return 0 # Handle the case where no price was found
except Exception as e:
print("An error occurred while fetching item price:", str(e))
def sum_other_services_price (self):
sum_other_services_price = 0
if self.other_services:
for i in self.other_services:
sum_other_services_price += self.get_item_price(i.service)
return sum_other_services_price
def sum_total_price (self):
self.total_price = self.sum_other_services_price() + self.get_item_price(self.package)
@frappe.whitelist()
def get_filtered_item_codes(self):
try:
parent = self.package
item_codes = frappe.db.sql_list(
"""
SELECT item_code
FROM `tabProduct Bundle Item`
WHERE parent = %s
""", (parent) # Ensure the parameter is a tuple
)
return item_codes
except Exception as e:
frappe.log_error(frappe.get_traceback(), "Error in get_filtered_item_codes")
return [] # Return an empty list on error
Certainly! Let's perform a comprehensive review of your ApplicantInvitation class within the Frappe framework. I'll highlight potential issues, suggest improvements, and provide recommendations to enhance the code's robustness, readability, and efficiency.
1. Code Structure and Formatting
Indentation: Ensure consistent indentation throughout the code. Python relies on indentation for block definitions. In your snippet, the methods are aligned correctly, but always double-check to maintain consistency.
Docstrings and Comments: While there are some docstrings and comments, expanding them can enhance readability and maintainability.
Error Handling: Some methods lack error handling. Incorporating try-except blocks where necessary can prevent unexpected crashes.
2. Potential Issues and Recommendations
a. add_company_information Method
python
def add_company_information(self):
user = frappe.get_doc("User", frappe.session.user)
self.db_set("company_name", user.full_name)
if user.full_name == "Administrator":
self.db_set("company_email", "administrator")
else:
self.db_set("company_email", user.email)
Issue: Directly setting company_email to the string "administrator" may not be a valid email address.
Recommendation: Use a valid email format or handle the administrator case differently.
python
def add_company_information(self):
user = frappe.get_doc("User", frappe.session.user)
self.company_name = user.full_name
if user.full_name == "Administrator":
self.company_email = "admin@example.com" # Use a valid default email
else:
self.company_email = user.email
Issue 1: Fetching the customer document using only customer_name when both customer_name and email are used in exists can lead to incorrect retrieval if multiple customers share the same name.
Issue 2: Possible inefficiency in querying with a dictionary inside get_doc.
Recommendation:
Use the same filters consistently when retrieving the document:
python
def create_customer(self, customer_name, customer_type, email, customer_group):
"""Creates a Customer if not exists and returns the Customer document."""
filters = {"customer_name": customer_name, "email": email}
customer = frappe.get_all("Customer", filters=filters, limit=1)
if customer:
frappe.logger().debug(f"Customer '{customer_name}' with email '{email}' already exists.")
customer_doc = frappe.get_doc("Customer", customer[0].name)
else:
new_doc = frappe.new_doc("Customer")
new_doc.customer_name = customer_name
new_doc.customer_type = customer_type
new_doc.customer_group = customer_group
new_doc.email = email
new_doc.insert(ignore_permissions=True)
customer_doc = new_doc
frappe.logger().debug(f"Customer Created: {customer_doc.name}")
return customer_doc
Issue: Returning True when the user exists and returning the User document when creating a new user can lead to inconsistent return types, making it harder to handle the result.
Recommendation:
Return a consistent type, such as the User document in both cases.
python
def create_user(self):
user = frappe.get_doc("User", {"email": self.email}) if frappe.db.exists("User", {"email": self.email}) else None
if user:
frappe.logger().debug(f"User with email '{self.email}' already exists.")
return user
else:
new_doc = frappe.new_doc("User")
new_doc.email = self.email
new_doc.first_name = self.first_name
new_doc.last_name = self.last_name
new_doc.middle_name = self.middle_name or ""
new_doc.enabled = True
new_doc.language = self.language or "en" # Set a default language if not provided
new_doc.module_profile = ""
new_doc.role_profile_name = "Applicant"
new_doc.insert(ignore_permissions=True)
frappe.logger().debug(f"User Created: {new_doc.name}")
return new_doc
d. create_sales_invoice Method
python
def create_sales_invoice(self, customer):
if not customer:
frappe.throw(_("Customer is not set. Cannot create Sales Invoice."))
sales_invoice = frappe.get_doc(
{
"doctype": "Sales Invoice",
"customer": customer,
}
)
self.preparing_the_sales_invoice(self.other_services, sales_invoice)
sales_invoice.save(ignore_permissions=True)
return sales_invoice
Issue 1: The method assumes self.other_services is always defined. If it's None or empty, it may lead to issues.
Issue 2: Missing setting for essential fields in Sales Invoice like due_date, posting_date, etc., which might be required based on your ERPNext setup.
Recommendation:
Ensure that self.other_services is iterable and set necessary fields.
python
def create_sales_invoice(self, customer):
if not customer:
frappe.throw(_("Customer is not set. Cannot create Sales Invoice."))
sales_invoice = frappe.new_doc("Sales Invoice")
sales_invoice.customer = customer
sales_invoice.posting_date = frappe.utils.today()
sales_invoice.due_date = frappe.utils.add_days(sales_invoice.posting_date, 30) # Example due date
# Ensure other_services is a list
other_services = self.other_services if self.other_services else []
self.preparing_the_sales_invoice(other_services, sales_invoice)
sales_invoice.calculate_taxes_and_totals() # Automatically calculate taxes and totals
sales_invoice.insert(ignore_permissions=True)
frappe.logger().debug(f"Sales Invoice Created: {sales_invoice.name}")
return sales_invoice
e. preparing_the_sales_invoice and preparing Methods
python
def preparing_the_sales_invoice(self, list_items, sales_invoice):
for i in list_items:
is_stock_item = frappe.get_value("Item", i.service, "is_stock_item")
if is_stock_item:
sales_invoice.append(
"items",
{
"item_code": i.service,
"qty": 1,
"uom": "Nos",
},
)
elif bundle := frappe.db.exists("Product Bundle", {"new_item_code": i.service}):
self.preparing(bundle, sales_invoice)
if self.package:
self.preparing(self.package, sales_invoice)
def preparing(self, bundle, sales_invoice):
bundle = frappe.get_doc("Product Bundle", bundle)
for b_i in bundle.items:
sales_invoice.append(
"items",
{
"item_code": b_i.item_code,
"qty": 1,
"uom": "Nos",
},
)
Issue 1: The walrus operator (:=) is used, which requires Python 3.8+. Ensure your environment supports it.
Issue 2: The uom is hardcoded as "Nos". It would be better to fetch the default UOM from the Item or provide flexibility.
Issue 3: Potential infinite recursion or performance issues if Product Bundle references are circular or very deep.
Recommendation:
Enhance flexibility and add safeguards against problematic data.
python
def preparing_the_sales_invoice(self, list_items, sales_invoice):
for item in list_items:
item_code = item.service
is_stock_item = frappe.get_value("Item", item_code, "is_stock_item")
uom = frappe.get_value("Item", item_code, "stock_uom") or "Nos"
if is_stock_item:
sales_invoice.append(
"items",
{
"item_code": item_code,
"qty": 1,
"uom": uom,
},
)
else:
bundle = frappe.db.exists("Product Bundle", {"new_item_code": item_code})
if bundle:
self._add_bundle_items(bundle, sales_invoice)
else:
frappe.throw(_("Item {0} is neither a stock item nor a valid product bundle.".format(item_code)))
if self.package:
self._add_bundle_items(self.package, sales_invoice)
def _add_bundle_items(self, bundle_name, sales_invoice, depth=0):
MAX_DEPTH = 10
if depth > MAX_DEPTH:
frappe.throw(_("Maximum bundle depth exceeded. Possible circular reference detected."))
bundle = frappe.get_doc("Product Bundle", bundle_name)
for bundle_item in bundle.items:
item_code = bundle_item.item_code
is_stock_item = frappe.get_value("Item", item_code, "is_stock_item")
uom = frappe.get_value("Item", item_code, "stock_uom") or "Nos"
if is_stock_item:
sales_invoice.append(
"items",
{
"item_code": item_code,
"qty": 1,
"uom": uom,
},
)
else:
nested_bundle = frappe.db.exists("Product Bundle", {"new_item_code": item_code})
if nested_bundle:
self._add_bundle_items(nested_bundle, sales_invoice, depth + 1)
else:
frappe.throw(_("Item {0} in bundle {1} is neither a stock item nor a valid product bundle.".format(item_code, bundle_name)))
Issue 1: Using print for error messages is not ideal in production environments.
Issue 2: The method returns 0 if no price is found, which might not be appropriate.
Recommendation:
Use logging instead of print and decide how to handle items without prices (e.g., setting to 0, raising an error, or skipping).
python
def get_item_price(self, item):
try:
price_data = frappe.db.get_value(
"Item Price",
{"item_code": item},
"price_list_rate"
)
return price_data if price_data else 0
except Exception as e:
frappe.log_error(message=str(e), title="Error fetching item price for {}".format(item))
return 0 # Or consider raising an exception
g. sum_other_services_price and sum_total_price Methods
python
def sum_other_services_price(self):
sum_other_services_price = 0
if self.other_services:
for i in self.other_services:
sum_other_services_price += self.get_item_price(i.service)
return sum_other_services_price
def sum_total_price(self):
self.total_price = self.sum_other_services_price() + self.get_item_price(self.package)
Issue: These methods are named as if they perform an action (imperative) but are actually calculating and setting values.
Recommendation:
Rename methods to reflect their functionality and optimize the calculations.
python
def calculate_other_services_price(self):
return sum(self.get_item_price(service.service) for service in self.other_services or [])
def calculate_total_price(self):
package_price = self.get_item_price(self.package) if self.package else 0
self.total_price = self.calculate_other_services_price() + package_price
@frappe.whitelist()
def get_filtered_item_codes(self):
try:
parent = self.package
item_codes = frappe.db.sql_list(
"""
SELECT item_code
FROM `tabProduct Bundle Item`
WHERE parent = %s
""", (parent)
)
return item_codes
except Exception as e:
frappe.log_error(frappe.get_traceback(), "Error in get_filtered_item_codes")
return []
Issue: There's no need to define this as a method within the Document class unless it's intended to be a client-callable function. Also, using self.package assumes that self is an instance with the package attribute set.
Recommendation:
If it's meant to be called from the client side, consider using @staticmethod or moving it outside the class. Ensure the method receives necessary parameters.
python
@frappe.whitelist()
def get_filtered_item_codes(package):
try:
item_codes = frappe.db.sql_list(
"""
SELECT item_code
FROM `tabProduct Bundle Item`
WHERE parent = %s
""", (package,)
)
return item_codes
except Exception as e:
frappe.log_error(message=frappe.get_traceback(), title="Error in get_filtered_item_codes")
return []
3. Additional Recommendations
a. Use of Translations
Ensure that all user-facing strings are wrapped with _() for proper translation support. For example:
python
frappe.throw(_("Customer is not set. Cannot create Sales Invoice."))
b. Database Operations Optimization
Prefetching: When fetching multiple related records, consider using frappe.get_all with pluck or frappe.get_list to reduce the number of database queries.
Caching: If certain data (like item prices) are accessed frequently and don't change often, consider caching them to improve performance.
c. Permissions and Security
Ensure that methods altering data have proper permission checks, especially if they're exposed via @frappe.whitelist().
d. Logging
Utilize Frappe's logging mechanism instead of print statements to capture logs appropriately.
e. Exception Handling
Be cautious with broad except Exception clauses. Where possible, catch specific exceptions to avoid masking unexpected errors.
4. Revised ApplicantInvitation Class
Incorporating the above recommendations, here's a revised version of your ApplicantInvitation class:
python
5. Testing and Validation
After implementing the above changes, ensure to:
Write Unit Tests: Validate each method's functionality, especially create_sales_invoice, create_user, and bundle processing.
Data Validation: Ensure that all required fields are populated correctly and that relationships between documents are maintained.
Performance Testing: Especially for bundle processing, ensure that the system performs efficiently without excessive database calls or recursion depth issues.
6. Documentation
Maintain comprehensive documentation for your class and its methods. This will aid future developers (or yourself) in understanding the workflow and purpose of each method.
By addressing the highlighted issues and implementing the recommended improvements, your ApplicantInvitation class will be more robust, maintainable, and aligned with best practices within the Frappe framework. If you have specific areas you'd like to focus on or encounter particular issues during implementation, feel free to ask for more targeted assistance!