Skip to content

chore : check for optimzation#8

Open
DHINESH00 wants to merge 1 commit intodevelop_aerelefrom
ref_parent_manufacturing_order
Open

chore : check for optimzation#8
DHINESH00 wants to merge 1 commit intodevelop_aerelefrom
ref_parent_manufacturing_order

Conversation

@DHINESH00
Copy link

@DHINESH00 DHINESH00 commented Jan 27, 2026

PR Type

Enhancement


Description

  • Code formatting and style standardization across entire file

  • Added new import get_link_to_form from frappe.utils

  • Introduced pre-commit configuration for code quality checks

  • Improved code readability with consistent indentation (tabs to spaces)


Diagram Walkthrough

flowchart LR
  A["Parent Manufacturing Order<br/>Python File"] -->|"Formatting & Style<br/>Improvements"| B["Standardized Code<br/>Structure"]
  C["Pre-commit Config<br/>Added"] -->|"Code Quality<br/>Tools"| D["Ruff, ESLint,<br/>Prettier"]
  A -->|"New Import"| E["get_link_to_form<br/>Utility"]
Loading

File Walkthrough

Relevant files
Formatting
parent_manufacturing_order.py
Code formatting and style standardization                               

jewellery_erpnext/jewellery_erpnext/doctype/parent_manufacturing_order/parent_manufacturing_order.py

  • Converted all indentation from tabs to spaces (4-space standard)
  • Added import for get_link_to_form from frappe.utils
  • Reformatted long lines for improved readability
  • Fixed spacing around operators and function calls
  • Improved line breaks in multi-line statements and function definitions
+1413/-1243
Configuration changes
.pre-commit-config.yaml
Pre-commit hooks configuration for code quality                   

.pre-commit-config.yaml

  • New file added for pre-commit hooks configuration
  • Configured ruff for Python import sorting and linting
  • Added prettier for JavaScript/Vue/SCSS formatting
  • Added ESLint for JavaScript code quality
  • Configured trailing whitespace and YAML validation checks
  • Set up CI autoupdate schedule for weekly updates
+74/-0   


🛠️ Relevant configurations:


These are the relevant configurations for this tool:

[config]

is_auto_command: True
is_new_pr: True
model_reasoning: vertex_ai/gemini-2.5-pro
model: gpt-5.2-2025-12-11
model_turbo: anthropic/claude-haiku-4-5-20251001
fallback_models: ['anthropic/claude-sonnet-4-5-20250929', 'bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0']
second_model_for_exhaustive_mode: o4-mini
git_provider: github
publish_output: True
publish_output_no_suggestions: True
publish_output_progress: True
verbosity_level: 0
publish_logs: False
debug_mode: False
use_wiki_settings_file: True
use_repo_settings_file: True
use_global_settings_file: True
use_global_wiki_settings_file: False
disable_auto_feedback: False
ai_timeout: 150
response_language: en-US
clone_repo_instead_of_fetch: True
always_clone: False
add_repo_metadata: True
clone_repo_time_limit: 300
publish_inline_comments_fallback_batch_size: 5
publish_inline_comments_fallback_sleep_time: 2
max_model_tokens: 32000
custom_model_max_tokens: -1
patch_extension_skip_types: ['.md', '.txt']
extra_allowed_extensions: []
allow_dynamic_context: True
allow_forward_dynamic_context: True
max_extra_lines_before_dynamic_context: 12
patch_extra_lines_before: 5
patch_extra_lines_after: 1
ai_handler: litellm
cli_mode: False
TRIAL_GIT_ORG_MAX_INVOKES_PER_MONTH: 75
TRIAL_RATIO_CLOSE_TO_LIMIT: 0.8
invite_only_mode: False
enable_request_access_msg_on_new_pr: False
check_also_invites_field: False
calculate_context: True
disable_checkboxes: False
output_relevant_configurations: True
large_patch_policy: clip
seed: -1
temperature: 0.2
allow_dynamic_context_ab_testing: False
choose_dynamic_context_ab_testing_ratio: 0.5
ignore_pr_title: ['^\\[Auto\\]', '^Auto', '^\\[Bump\\]']
ignore_pr_target_branches: []
ignore_pr_source_branches: []
ignore_pr_labels: ['do-not-merge', 'skip-qodo']
ignore_ticket_labels: []
allow_only_specific_folders: []
ignore_pr_authors: []
ignore_repositories: []
ignore_language_framework: []
enable_ai_metadata: True
present_reasoning: True
max_tickets: 10
max_tickets_chars: 8000
prevent_any_approval: False
enable_comment_approval: False
enable_auto_approval: False
auto_approve_for_low_review_effort: -1
auto_approve_for_no_suggestions: False
ensure_ticket_compliance: False
new_diff_format: True
new_diff_format_add_external_references: True
enable_custom_labels: False

[pr_description]

final_update_message: False
publish_labels: False
add_original_user_description: True
generate_ai_title: False
extra_instructions: Highlight any database schema changes (Doctype/child table modifications), new background jobs (frappe.enqueue / scheduler events),
and any changes that could increase DB queries or write amplification.

enable_pr_type: True
enable_help_text: False
enable_help_comment: False
bring_latest_tag: False
enable_pr_diagram: True
publish_description_as_comment: False
publish_description_as_comment_persistent: True
enable_semantic_files_types: True
collapsible_file_list: adaptive
collapsible_file_list_threshold: 8
inline_file_summary: False
use_description_markers: False
include_generated_by_header: True
enable_large_pr_handling: True
max_ai_calls: 4
auto_create_ticket: False

@qodo-free-for-open-source-projects

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🏅 Score: 75
🧪 No relevant tests
✅ No TODO sections
🔒 No security concerns identified
🔀 No multiple PR themes
⚡ Recommended focus areas for review

Configuration Issue

The pre-commit config references 'jewellery_erpnext' paths extensively but the PR title/branch suggests this is for a generic manufacturing module. Verify that path patterns match the actual repository structure and that hooks will run on the intended files. The 'no-commit-to-branch' hook targets 'develop' branch which may not align with the current branch strategy.

  files: "jewellery_erpnext.*"
  exclude: ".*json$|.*txt$|.*csv|.*md"
- id: check-yaml
- id: no-commit-to-branch
  args: ['--branch', 'develop']
Outdated Versions

Pre-commit hook versions are outdated (v4.3.0 from 2022, prettier v2.7.1, eslint v8.44.0, ruff v0.2.0). Consider updating to latest stable versions to benefit from bug fixes, performance improvements, and new features. Current ruff version is significantly behind (latest is v0.8+).

  rev: v4.3.0
  hooks:
    - id: trailing-whitespace
      files: "jewellery_erpnext.*"
      exclude: ".*json$|.*txt$|.*csv|.*md"
    - id: check-yaml
    - id: no-commit-to-branch
      args: ['--branch', 'develop']
    - id: check-merge-conflict
    - id: check-ast
    - id: check-json
    - id: check-toml
    - id: check-yaml
    - id: debug-statements

- repo: https://github.com/pre-commit/mirrors-prettier
  rev: v2.7.1
  hooks:
    - id: prettier
      types_or: [javascript, vue, scss]
      # Ignore any files that might contain jinja / bundles
      exclude: |
          (?x)^(
              jewellery_erpnext/public/dist/.*|
              cypress/.*|
              .*node_modules.*|
              .*boilerplate.*|
              jewellery_erpnext/public/js/controllers/.*|
              jewellery_erpnext/templates/pages/order.js|
              jewellery_erpnext/templates/includes/.*
          )$

- repo: https://github.com/pre-commit/mirrors-eslint
  rev: v8.44.0
  hooks:
    - id: eslint
      types_or: [javascript]
      args: ['--quiet']
      # Ignore any files that might contain jinja / bundles
      exclude: |
          (?x)^(
              jewellery_erpnext/public/dist/.*|
              cypress/.*|
              .*node_modules.*|
              .*boilerplate.*|
              jewellery_erpnext/public/js/controllers/.*|
              jewellery_erpnext/templates/pages/order.js|
              jewellery_erpnext/templates/includes/.*
          )$

- repo: https://github.com/astral-sh/ruff-pre-commit
  rev: v0.2.0

🛠️ Relevant configurations:


These are the relevant configurations for this tool:

[config]

is_auto_command: True
is_new_pr: True
model_reasoning: vertex_ai/gemini-2.5-pro
model: gpt-5.2-2025-12-11
model_turbo: anthropic/claude-haiku-4-5-20251001
fallback_models: ['anthropic/claude-sonnet-4-5-20250929', 'bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0']
second_model_for_exhaustive_mode: o4-mini
git_provider: github
publish_output: True
publish_output_no_suggestions: True
publish_output_progress: True
verbosity_level: 0
publish_logs: False
debug_mode: False
use_wiki_settings_file: True
use_repo_settings_file: True
use_global_settings_file: True
use_global_wiki_settings_file: False
disable_auto_feedback: False
ai_timeout: 150
response_language: en-US
clone_repo_instead_of_fetch: True
always_clone: False
add_repo_metadata: True
clone_repo_time_limit: 300
publish_inline_comments_fallback_batch_size: 5
publish_inline_comments_fallback_sleep_time: 2
max_model_tokens: 32000
custom_model_max_tokens: -1
patch_extension_skip_types: ['.md', '.txt']
extra_allowed_extensions: []
allow_dynamic_context: True
allow_forward_dynamic_context: True
max_extra_lines_before_dynamic_context: 12
patch_extra_lines_before: 5
patch_extra_lines_after: 1
ai_handler: litellm
cli_mode: False
TRIAL_GIT_ORG_MAX_INVOKES_PER_MONTH: 75
TRIAL_RATIO_CLOSE_TO_LIMIT: 0.8
invite_only_mode: False
enable_request_access_msg_on_new_pr: False
check_also_invites_field: False
calculate_context: True
disable_checkboxes: False
output_relevant_configurations: True
large_patch_policy: clip
seed: -1
temperature: 0.2
allow_dynamic_context_ab_testing: False
choose_dynamic_context_ab_testing_ratio: 0.5
ignore_pr_title: ['^\\[Auto\\]', '^Auto', '^\\[Bump\\]']
ignore_pr_target_branches: []
ignore_pr_source_branches: []
ignore_pr_labels: ['do-not-merge', 'skip-qodo']
ignore_ticket_labels: []
allow_only_specific_folders: []
ignore_pr_authors: []
ignore_repositories: []
ignore_language_framework: []
enable_ai_metadata: True
present_reasoning: True
max_tickets: 10
max_tickets_chars: 8000
prevent_any_approval: False
enable_comment_approval: False
enable_auto_approval: False
auto_approve_for_low_review_effort: -1
auto_approve_for_no_suggestions: False
ensure_ticket_compliance: False
new_diff_format: True
new_diff_format_add_external_references: True
enable_custom_labels: False

[pr_reviewer]

require_score_review: True
require_tests_review: True
require_estimate_effort_to_review: True
require_can_be_split_review: True
require_security_review: True
require_todo_scan: True
require_ticket_analysis_review: True
require_ticket_labels: False
require_no_ticket_labels: False
check_pr_additional_content: False
persistent_comment: True
extra_instructions: You are a Senior Technical Architect specializing in the Frappe Framework, Python, and MariaDB optimization.
Be concise but strict about performance and security. Provide code snippets (or pseudocode) for fixes.

========================
1) 🚨 FRAPPE PERFORMANCE KILLERS (High Priority)
========================
A) N+1 Query Detection (must flag):
- Flag ANY loop that contains `frappe.get_doc`, `frappe.db.get_value`, `frappe.db.get_all/get_list`, or `frappe.db.sql`.
- Explain the query multiplier (e.g., “1 + N queries”) and propose a bulk-fetch refactor:
  - pre-fetch with `frappe.get_all/get_list` (with fields + filters) or one SQL query with IN,
  - build a dict/map keyed by name, then iterate without DB calls.

B) Heavy Writes / Controller chain (must flag):
- If `doc.save()` is used to update just 1–2 fields, aggressively suggest replacing with:
  - `frappe.db.set_value(doctype, name, field, value)`
  - or `frappe.db.set_value(doctype, name, {field1: v1, field2: v2})`
- Explain it avoids triggering heavy validations / hooks / controller logic unnecessarily.
- Exception: if controller validations are required for correctness, require justification.

C) ORM abuse / wrong API choice:
- Warn against `frappe.db.sql()` if the same can be achieved by permission-safe ORM (`frappe.get_list/get_all`)
  unless it is a complex join/aggregation needing SQL.
- Also warn when `frappe.db.*` is used in user-facing endpoints where permission checks matter.

D) Redundant commits (must flag):
- `frappe.db.commit()` inside loops is forbidden unless there is a carefully justified transactional reason.
- Suggest moving commit outside loop, batching, or using background jobs.

E) Unbounded reads:
- Flag `get_all/get_list` without strong filters or without pagination on potentially large tables.
- Recommend adding filters, indexed ordering, `limit/page_length`, or background processing.

F) Hot hooks:
- Flag heavy work (bulk queries, file IO, network calls) inside validate/on_update/after_insert hooks.
- Recommend `frappe.enqueue` and async jobs.

========================
2) 🛡️ SECURITY & SQL SAFETY (must be strict)
========================
A) SQL injection:
- Strictly forbid f-strings / concatenation inside `frappe.db.sql()`.
- REQUIRE parameter passing: `frappe.db.sql("... %s", (val,))`.

B) Whitelisting:
- If functions are intended to be called from client (JS / REST), ensure `@frappe.whitelist()` exists.
- Confirm sensitive functions are NOT accidentally exposed.

C) Permission checks:
- For new `get_list/get_all`/SQL calls, ensure strict permissions are not bypassed.
- If `ignore_permissions=True` or `frappe.db.*` is used, REQUIRE explicit justification + risk assessment.

D) Unsafe patterns:
- Flag `eval/exec`, insecure deserialization, and unsafe file path usage.

========================
3) 🐍 PYTHONIC & LOGIC OPTIMIZATIONS
========================
A) Mutable defaults (must flag):
- `def f(x=[])` / `def f(x={})` etc. Require `None` + initialization.

B) Data structure choices:
- If code does `if item in big_list`, suggest `set(big_list)` for O(1) lookups.

C) Inefficient loops:
- Reduce nested loops; pull invariants out; memoize expensive computations.

D) List building:
- Suggest list comprehensions ONLY when readability remains good.
- Avoid creating large intermediate lists when generators/chunking is better.

E) String + datetime churn:
- Flag repeated parsing/formatting/conversions inside loops.

========================
4) 📉 MARIADB / DATABASE OPTIMIZATION CHECKS
========================
A) Wildcards / over-fetching:
- Warn against `SELECT *`. Require selecting specific columns.

B) Indexing:
- If a field is used in WHERE / JOIN / ORDER BY patterns frequently, ask if it needs an index.
- If appropriate, suggest composite index order aligned with query filters (e.g., company + docstatus + posting_date).

C) Sorting + limiting:
- Flag ORDER BY on large sets without indexed order; recommend index or reduce rows first.

D) Aggregations:
- If Python loops compute SUM/COUNT over many rows, suggest SQL aggregation where safe.

========================
5) OUTPUT REQUIREMENTS
========================
- Provide concrete refactor steps and code snippets.
- Quantify impact when possible: “reduces from N queries to 1”.
- If table sizes/indexes are unknown, recommend checking EXPLAIN and adding indexes if confirmed.

final_update_message: False
enable_review_labels_security: True
enable_review_labels_effort: True
enable_help_text: False
num_max_findings: 8

@qodo-free-for-open-source-projects
Copy link

qodo-free-for-open-source-projects bot commented Jan 27, 2026

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Bulk update records to reduce queries

Refactor the hold_mop function to perform a bulk update. Fetch all operations
needing an update in one query, then update their status with a single
frappe.db.set_value call.

jewellery_erpnext/jewellery_erpnext/doctype/parent_manufacturing_order/parent_manufacturing_order.py [1471-1482]

-for i in frappe.db.get_list(
+operations_to_update = frappe.get_all(
     "Manufacturing Operation",
-    filters={"manufacturing_order": self.name},
-    fields="name",
-):
-    if (
-        frappe.db.get_value("Manufacturing Operation", i["name"], "status")
-        != "Finished"
-    ):
-        frappe.db.set_value(
-            "Manufacturing Operation", i["name"], "status", "Finished"
-        )
+    filters={
+        "manufacturing_order": self.name,
+        "status": ("!=", "Finished")
+    },
+    pluck="name"
+)
+if operations_to_update:
+    frappe.db.set_value(
+        "Manufacturing Operation", operations_to_update, "status", "Finished"
+    )
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies inefficient database access in a loop and proposes a much more performant bulk update approach, significantly reducing database I/O.

Medium
Cache database results within a loop

In create_material_requests, cache the result of
frappe.db.get_value("Warehouse", ...) within the loop to avoid redundant
database queries for the same department.

jewellery_erpnext/jewellery_erpnext/doctype/parent_manufacturing_order/parent_manufacturing_order.py [259-390]

+from_warehouse_cache = {}
 for row in data:
     item_type = get_item_type(row.item_variant)
     if item_type == "metal_item":
         if not warehouse_dict.get("M"):
             frappe.throw(
                 _("Please mention warehouse details in Manufacturer")
             )
         department = warehouse_dict["M"]["department"]
         to_warehouse = warehouse_dict["M"]["target_warehouse"]
+        if department not in from_warehouse_cache:
+            from_warehouse_cache[department] = frappe.db.get_value(
+                "Warehouse",
+                {
+                    "disabled": 0,
+                    "department": department,
+                    "warehouse_type": "Raw Material",
+                },
+                "name",
+            )
         metal_items.append(
             {
                 "item_code": row.item_variant,
                 "qty": row.quantity,
-                "from_warehouse": frappe.db.get_value(
-                    "Warehouse",
-                    {
-                        "disabled": 0,
-                        "department": department,
-                        "warehouse_type": "Raw Material",
-                    },
-                    "name",
-                ),
+                "from_warehouse": from_warehouse_cache[department],
                 "warehouse": to_warehouse,
                 "is_customer_item": row.is_customer_item,
                 "sub_setting_type": None,
                 "pcs": None,
             }
         )
     elif item_type == "finding_item":
         ...

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies repeated database calls inside a loop and proposes a caching mechanism, which is a valid and effective performance optimization.

Medium
Optimize database calls in loop

Optimize the database query within the loop by fetching all Attribute Value
records at once using an IN clause to avoid multiple database calls.

jewellery_erpnext/jewellery_erpnext/doctype/parent_manufacturing_order/parent_manufacturing_order.py [40-44]

-for row in diamond_grade_data:
-    if frappe.db.get_value(
-        "Attribute Value", row, "is_customer_diamond_quality"
-    ):
-        self.diamond_grade = row
+customer_diamond_grades = frappe.db.get_all(
+    "Attribute Value",
+    filters={"name": ("in", diamond_grade_data), "is_customer_diamond_quality": 1},
+    pluck="name",
+    limit=1
+)
+if customer_diamond_grades:
+    self.diamond_grade = customer_diamond_grades[0]
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies an N+1 query problem and provides an efficient solution using a single bulk query, which can significantly improve performance.

Low
Avoid redundant database query

Refactor the code to use a single database query instead of two identical ones.
Store the result in a variable and then perform the check.

jewellery_erpnext/jewellery_erpnext/doctype/parent_manufacturing_order/parent_manufacturing_order.py [1487-1496]

-if frappe.db.get_value("Manufacturing Work Order", {"manufacturing_order": pmo, "for_cad_cam": 1}):
-    cad_mwo = frappe.db.get_value("Manufacturing Work Order", {"manufacturing_order": pmo, "for_cad_cam": 1})
+cad_mwo = frappe.db.get_value("Manufacturing Work Order", {"manufacturing_order": pmo, "for_cad_cam": 1})
+if cad_mwo:
     return frappe.msgprint(
         f"Manufacturing Work Order for CAD/CAM Department is <b>already</b> created. <b>{get_link_to_form('Manufacturing Work Order', cad_mwo)}</b>"
     )

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies a redundant database call and proposes a valid optimization, which improves performance by reducing database load.

Low
Security
Add permission check to whitelisted method

Add a permission check using frappe.has_permission to the whitelisted
send_to_customer_for_approval method to enhance security.

jewellery_erpnext/jewellery_erpnext/doctype/parent_manufacturing_order/parent_manufacturing_order.py [455-461]

 @frappe.whitelist()
 def send_to_customer_for_approval(self):
+    if not frappe.has_permission(self.doctype, "write", self.name):
+        frappe.throw(_("Insufficient permissions to send for approval"))
+    
     mwo_list = frappe.db.get_all(
         "Manufacturing Work Order",
         {"manufacturing_order": self.name, "docstatus": 1},
         ["name", "department", "manufacturing_operation"],
     )
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a security vulnerability where a whitelisted method lacks permission checks, preventing unauthorized actions.

High
Validate permissions in whitelisted function

Add a permission check using frappe.has_permission to the whitelisted create_mwo
function to ensure only authorized users can create Manufacturing Work Orders.

jewellery_erpnext/jewellery_erpnext/doctype/parent_manufacturing_order/parent_manufacturing_order.py [1485-1492]

 @frappe.whitelist()
 def create_mwo(pmo, doc, reason=None):
+    if not frappe.has_permission("Parent Manufacturing Order", "write", pmo):
+        frappe.throw(_("Insufficient permissions to create Manufacturing Work Order"))
+    
     if frappe.db.get_value(
         "Manufacturing Work Order", {"manufacturing_order": pmo, "for_cad_cam": 1}
     ):
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a security vulnerability where a whitelisted function lacks permission checks, preventing unauthorized document creation.

High
General
Validate quantities before document creation

Validate all item quantities before creating a Material Request document to
ensure the operation is atomic and prevent partial document creation.

jewellery_erpnext/jewellery_erpnext/doctype/parent_manufacturing_order/parent_manufacturing_order.py [403-448]

 for item_type, val in trimmed_items.items():
     if val:
+        for i in val:
+            if i["qty"] <= 0:
+                frappe.throw(
+                    f"Please Check BOM Table:<b>{item_type.upper()}</b>, <b>{i['item_code']}</b> is {i['qty']} Not Allowed."
+                )
+        
         mr_doc = frappe.new_doc("Material Request")
         ...
         mr_doc.custom_department = frappe.db.get_value(
             "Warehouse", val[0]["from_warehouse"], "department"
         )
         for i in val:
-            if i["qty"] > 0:
-                mr_doc.append(
-                    "items",
-                    {
-                        "item_code": i["item_code"],
-                        "qty": i["qty"] * self.qty,
-                        ...
-                    },
-                )
-            else:
-                frappe.throw(
-                    f"Please Check BOM Table:<b>{item_type.upper()}</b>, <b>{i['item_code']}</b> is {i['qty']} Not Allowed."
-                )
+            mr_doc.append(
+                "items",
+                {
+                    "item_code": i["item_code"],
+                    "qty": i["qty"] * self.qty,
+                    ...
+                },
+            )
         counter += 1
         mr_doc.save()

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out a potential issue where a document is created before all its items are validated, improving the atomicity of the operation.

Medium
Fetch operations with single IN query

Replace the loop that fetches manufacturing operations one by one with a single,
more efficient query using an IN clause to avoid an N+1 problem.

jewellery_erpnext/jewellery_erpnext/doctype/parent_manufacturing_order/parent_manufacturing_order.py [1366-1378]

 mwo = frappe.get_all(
     "Manufacturing Work Order", {"manufacturing_order": pmo_name}, pluck="name"
 )
-mwo_last_operation = []
-for mwo_id in mwo:
-    operation = frappe.db.get_value(
+if mwo:
+    mwo_operations = frappe.get_all(
         "Manufacturing Work Order",
-        filters={"name": mwo_id},
-        fieldname="manufacturing_operation",
-        order_by="modified desc",
+        filters={"name": ("in", mwo)},
+        fields=["manufacturing_operation"],
+        order_by="modified desc"
     )
-    if operation is not None:
-        mwo_last_operation.append(operation)
+    mwo_last_operation = [op.manufacturing_operation for op in mwo_operations if op.manufacturing_operation]
+else:
+    mwo_last_operation = []
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies an N+1 query problem and proposes a more efficient solution using a single query, significantly improving performance.

Medium
Fetch warehouse data once before loop

Move the variant_warehouse database query out of the for loop to avoid making
redundant calls for each BOM table.

jewellery_erpnext/jewellery_erpnext/doctype/parent_manufacturing_order/parent_manufacturing_order.py [215-253]

+variant_warehouse = frappe.db.get_all(
+    "Variant based Warehouse",
+    {"parent": self.manufacturer},
+    ["variant", "department", "target_warehouse"],
+)
+warehouse_dict = {}
+for row in variant_warehouse:
+    warehouse_dict.update({row.variant: row})
+
 for bom_table in bom_tables:
     # Get bom table's
     if bom_table == "BOM Metal Detail":
         data = frappe.get_all(
             bom_table,
             {"parent": bom},
             ["item_variant", "quantity", "is_customer_item"],
         )
     if bom_table == "BOM Finding Detail":
         data = frappe.get_all(
             bom_table,
             {"parent": bom},
             ["item_variant", "quantity", "qty", "is_customer_item"],
         )
     if bom_table == "BOM Diamond Detail" or bom_table == "BOM Gemstone Detail":
         data = frappe.get_all(
             bom_table,
             {"parent": bom},
             [
                 "item_variant",
                 "quantity",
                 "is_customer_item",
                 "sub_setting_type",
                 "pcs",
             ],
         )
     if bom_table == "BOM Other Detail":
         data = frappe.get_all(
             bom_table,
             {"parent": bom},
             ["item_code", "quantity", "qty"],
         )
     if data:
         # Loop through the rows of the bom table
-        variant_warehouse = frappe.db.get_all(
-            "Variant based Warehouse",
-            {"parent": self.manufacturer},
-            ["variant", "department", "target_warehouse"],
-        )
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies a redundant database query inside a loop and proposes moving it out, which improves performance by reducing I/O operations.

Low
Batch department field updates together

Consolidate multiple self.db_set calls into a single frappe.db.set_value call to
update department fields more efficiently.

jewellery_erpnext/jewellery_erpnext/doctype/parent_manufacturing_order/parent_manufacturing_order.py [80-112]

 if self.manufacturer:
     warehouse_details = frappe.db.get_value(
         "Manufacturing Setting",
         {"manufacturer": self.manufacturer},
         [
             "default_department",
             "default_diamond_department",
             "default_gemstone_department",
             "default_finding_department",
             "default_other_material_department",
         ],
         as_dict=1,
     )
 
-    metal_department = warehouse_details.get("default_department") or None
-    diamond_department = (
-        warehouse_details.get("default_diamond_department") or None
-    )
-    gemstone_department = (
-        warehouse_details.get("default_gemstone_department") or None
-    )
-    finding_department = (
-        warehouse_details.get("default_finding_department") or None
-    )
-    other_material_department = (
-        warehouse_details.get("default_other_material_department") or None
+    frappe.db.set_value(
+        self.doctype,
+        self.name,
+        {
+            "metal_department": warehouse_details.get("default_department"),
+            "diamond_department": warehouse_details.get("default_diamond_department"),
+            "gemstone_department": warehouse_details.get("default_gemstone_department"),
+            "finding_department": warehouse_details.get("default_finding_department"),
+            "other_material_department": warehouse_details.get("default_other_material_department"),
+        },
     )
 
-    self.db_set("metal_department", metal_department)
-    self.db_set("diamond_department", diamond_department)
-    self.db_set("gemstone_department", gemstone_department)
-    self.db_set("finding_department", finding_department)
-    self.db_set("other_material_department", other_material_department)
-
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly proposes consolidating five separate db_set calls into a single db.set_value call, improving performance by reducing database writes.

Low
  • More
  • Author self-review: I have reviewed the PR code suggestions, and addressed the relevant ones.

🛠️ Relevant configurations:


These are the relevant configurations for this tool:

[config]

is_auto_command: True
is_new_pr: True
model_reasoning: vertex_ai/gemini-2.5-pro
model: gpt-5.2-2025-12-11
model_turbo: anthropic/claude-haiku-4-5-20251001
fallback_models: ['anthropic/claude-sonnet-4-5-20250929', 'bedrock/us.anthropic.claude-sonnet-4-5-20250929-v1:0']
second_model_for_exhaustive_mode: o4-mini
git_provider: github
publish_output: True
publish_output_no_suggestions: True
publish_output_progress: True
verbosity_level: 0
publish_logs: False
debug_mode: False
use_wiki_settings_file: True
use_repo_settings_file: True
use_global_settings_file: True
use_global_wiki_settings_file: False
disable_auto_feedback: False
ai_timeout: 150
response_language: en-US
clone_repo_instead_of_fetch: True
always_clone: False
add_repo_metadata: True
clone_repo_time_limit: 300
publish_inline_comments_fallback_batch_size: 5
publish_inline_comments_fallback_sleep_time: 2
max_model_tokens: 32000
custom_model_max_tokens: -1
patch_extension_skip_types: ['.md', '.txt']
extra_allowed_extensions: []
allow_dynamic_context: True
allow_forward_dynamic_context: True
max_extra_lines_before_dynamic_context: 12
patch_extra_lines_before: 5
patch_extra_lines_after: 1
ai_handler: litellm
cli_mode: False
TRIAL_GIT_ORG_MAX_INVOKES_PER_MONTH: 75
TRIAL_RATIO_CLOSE_TO_LIMIT: 0.8
invite_only_mode: False
enable_request_access_msg_on_new_pr: False
check_also_invites_field: False
calculate_context: True
disable_checkboxes: False
output_relevant_configurations: True
large_patch_policy: clip
seed: -1
temperature: 0.2
allow_dynamic_context_ab_testing: False
choose_dynamic_context_ab_testing_ratio: 0.5
ignore_pr_title: ['^\\[Auto\\]', '^Auto', '^\\[Bump\\]']
ignore_pr_target_branches: []
ignore_pr_source_branches: []
ignore_pr_labels: ['do-not-merge', 'skip-qodo']
ignore_ticket_labels: []
allow_only_specific_folders: []
ignore_pr_authors: []
ignore_repositories: []
ignore_language_framework: []
enable_ai_metadata: True
present_reasoning: True
max_tickets: 10
max_tickets_chars: 8000
prevent_any_approval: False
enable_comment_approval: False
enable_auto_approval: False
auto_approve_for_low_review_effort: -1
auto_approve_for_no_suggestions: False
ensure_ticket_compliance: False
new_diff_format: True
new_diff_format_add_external_references: True
enable_custom_labels: False
extra_statistics: {'suggestion_statistics': [{'score': 5, 'label': 'general'}, {'score': 6, 'label': 'general'}, {'score': 7, 'label': 'general'}, {'score': 7, 'label': 'general'}]}

[pr_code_suggestions]

suggestions_depth: exhaustive
commitable_code_suggestions: False
decouple_hunks: False
dual_publishing_score_threshold: -1
focus_only_on_problems: True
allow_thumbs_up_down: False
enable_suggestion_type_reuse: False
enable_more_suggestions_checkbox: True
high_level_suggestions_enabled: True
extra_instructions: Focus suggestions on PERFORMANCE + SECURITY:
- Reduce DB roundtrips (bulk fetch, IN queries, joins/aggregates).
- Prefer set_value over save for small field updates unless validations are required.
- Ensure parameterized SQL only.
- Ensure endpoints are whitelisted intentionally and respect permissions.
- Prefer chunking/generators for big datasets.
Return copy-paste ready snippets when feasible.

enable_help_text: False
show_extra_context: False
persistent_comment: True
max_history_len: 5
apply_suggestions_checkbox: True
enable_chat_in_code_suggestions: True
apply_limit_scope: True
suggestions_score_threshold: 0
new_score_mechanism: True
new_score_mechanism_th_high: 9
new_score_mechanism_th_medium: 7
discard_unappliable_suggestions: False
num_code_suggestions_per_chunk: 6
num_best_practice_suggestions: 2
max_number_of_calls: 3
final_clip_factor: 0.8
demand_code_suggestions_self_review: True
code_suggestions_self_review_text: **Author self-review**: I have reviewed the PR code suggestions, and addressed the relevant ones.
approve_pr_on_self_review: False
fold_suggestions_on_self_review: True
publish_post_process_suggestion_impact: True
wiki_page_accepted_suggestions: True
enable_local_self_reflect_in_large_prs: False
simplify_response: True

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant