diff --git a/spollex/spollex/report/stock_balance_custom/__init__.py b/spollex/spollex/report/stock_balance_custom/__init__.py new file mode 100644 index 0000000..40a96af --- /dev/null +++ b/spollex/spollex/report/stock_balance_custom/__init__.py @@ -0,0 +1 @@ +# -*- coding: utf-8 -*- diff --git a/spollex/spollex/report/stock_balance_custom/stock_balance_custom.js b/spollex/spollex/report/stock_balance_custom/stock_balance_custom.js new file mode 100644 index 0000000..3790425 --- /dev/null +++ b/spollex/spollex/report/stock_balance_custom/stock_balance_custom.js @@ -0,0 +1,182 @@ +// Copyright (c) 2026, 4C Solutions and contributors +// For license information, please see license.txt + +frappe.query_reports["Stock Balance Custom"] = { + filters: [ + { + fieldname: "company", + label: __("Company"), + fieldtype: "Link", + width: "80", + options: "Company", + default: frappe.defaults.get_default("company"), + }, + { + fieldname: "from_date", + label: __("From Date"), + fieldtype: "Date", + width: "80", + reqd: 1, + default: frappe.datetime.add_months(frappe.datetime.get_today(), -1), + }, + { + fieldname: "to_date", + label: __("To Date"), + fieldtype: "Date", + width: "80", + reqd: 1, + default: frappe.datetime.get_today(), + }, + { + fieldname: "item_group", + label: __("Item Group"), + fieldtype: "MultiSelectList", + width: "80", + options: "Item Group", + get_data: function (txt) { + return frappe.db.get_link_options("Item Group", txt); + }, + }, + { + fieldname: "item_code", + label: __("Items"), + fieldtype: "MultiSelectList", + width: "80", + options: "Item", + get_data: async function (txt) { + let item_group = frappe.query_report.get_filter_value("item_group"); + + let filters = { + is_stock_item: 1, + }; + + if (item_group) { + if (Array.isArray(item_group) && item_group.length) { + filters.item_group = ["in", item_group]; + } else if (typeof item_group === "string" && item_group.trim()) { + filters.item_group = item_group; + } + } + + let { message: data } = await frappe.call({ + method: "erpnext.controllers.queries.item_query", + args: { + doctype: "Item", + txt: txt, + searchfield: "name", + start: 0, + page_len: 10, + filters: filters, + as_dict: 1, + }, + }); + + data = data.map(({ name, ...rest }) => { + return { + value: name, + description: Object.values(rest), + }; + }); + + return data || []; + }, + }, + { + fieldname: "warehouse", + label: __("Warehouses"), + fieldtype: "MultiSelectList", + width: "80", + options: "Warehouse", + get_data: (txt) => { + let warehouse_type = frappe.query_report.get_filter_value("warehouse_type"); + let company = frappe.query_report.get_filter_value("company"); + + let filters = { + ...(warehouse_type && { warehouse_type }), + ...(company && { company }), + }; + + return frappe.db.get_link_options("Warehouse", txt, filters); + }, + }, + { + fieldname: "warehouse_type", + label: __("Warehouse Type"), + fieldtype: "Link", + width: "80", + options: "Warehouse Type", + }, + { + fieldname: "valuation_field_type", + label: __("Valuation Field Type"), + fieldtype: "Select", + width: "80", + options: "Currency\nFloat", + default: "Currency", + }, + { + fieldname: "include_uom", + label: __("Include UOM"), + fieldtype: "Link", + options: "UOM", + }, + { + fieldname: "show_variant_attributes", + label: __("Show Variant Attributes"), + fieldtype: "Check", + }, + { + fieldname: "show_stock_ageing_data", + label: __("Show Stock Ageing Data"), + fieldtype: "Check", + }, + { + fieldname: "ignore_closing_balance", + label: __("Ignore Closing Balance"), + fieldtype: "Check", + default: 0, + }, + { + fieldname: "include_zero_stock_items", + label: __("Include Zero Stock Items"), + fieldtype: "Check", + default: 1, + }, + { + fieldname: "show_dimension_wise_stock", + label: __("Show Dimension Wise Stock"), + fieldtype: "Check", + default: 0, + }, + ], + + formatter: function (value, row, column, data, default_formatter) { + value = default_formatter(value, row, column, data); + + if (column.fieldname == "out_qty" && data && data.out_qty > 0) { + value = "" + value + ""; + } else if (column.fieldname == "in_qty" && data && data.in_qty > 0) { + value = "" + value + ""; + } + + return value; + }, + + onload: function (report) { + report.page.add_inner_button(__("View Stock Ledger"), function () { + var filters = report.get_values(); + if (filters.item_group) { + if (Array.isArray(filters.item_group)) { + if (filters.item_group.length === 1) { + filters.item_group = filters.item_group[0]; + } else { + delete filters.item_group; + } + } + } + frappe.set_route("query-report", "Stock Ledger", filters); + }); + }, +}; + +erpnext.utils.add_inventory_dimensions("Stock Balance Custom", 8); diff --git a/spollex/spollex/report/stock_balance_custom/stock_balance_custom.json b/spollex/spollex/report/stock_balance_custom/stock_balance_custom.json new file mode 100644 index 0000000..01c1f29 --- /dev/null +++ b/spollex/spollex/report/stock_balance_custom/stock_balance_custom.json @@ -0,0 +1,35 @@ +{ + "add_total_row": 1, + "add_translate_data": 0, + "columns": [], + "creation": "2026-09-12 01:54:21.375969", + "disable_prepared_report_automation": 0, + "disabled": 0, + "docstatus": 0, + "doctype": "Report", + "doctype_to_sync": [], + "filters": [], + "idx": 0, + "is_standard": "Yes", + "letter_head": null, + "modified": "2026-09-12 01:59:39.253934", + "modified_by": "Administrator", + "module": "spollex", + "name": "Stock Balance Custom", + "owner": "Administrator", + "prepared_report": 0, + "ref_doctype": "Stock Ledger Entry", + "reference_report": "Stock Balance", + "report_name": "Stock Balance Custom", + "report_type": "Script Report", + "roles": [ + { + "role": "Stock User" + }, + { + "role": "Accounts Manager" + } + ], + "snapshot_report": 0, + "timeout": 0 +} \ No newline at end of file diff --git a/spollex/spollex/report/stock_balance_custom/stock_balance_custom.py b/spollex/spollex/report/stock_balance_custom/stock_balance_custom.py new file mode 100644 index 0000000..9a68178 --- /dev/null +++ b/spollex/spollex/report/stock_balance_custom/stock_balance_custom.py @@ -0,0 +1,169 @@ +# Copyright (c) 2026, 4C Solutions and Contributors +# License: GNU General Public License v3. See license.txt + +import json +from typing import Any + +import frappe +from frappe.query_builder import Order +from frappe.query_builder.functions import Count +from frappe.utils.nestedset import get_descendants_of + +from erpnext.stock.report.stock_balance.stock_balance import ( + StockBalanceFilter, + StockBalanceReport, +) + + +def execute(filters: StockBalanceFilter | dict[str, Any] | None = None): + return StockBalanceCustomReport(filters).run() + + +def parse_filter_list(val: Any) -> list[str]: + """Parse a filter value into a list of non-empty strings. + + Handles JSON lists (from frontend MultiSelectList), lists/tuples/sets, and single strings. + """ + if not val: + return [] + if isinstance(val, str): + try: + parsed = json.loads(val) + if isinstance(parsed, list): + return [str(x) for x in parsed if x] + except Exception: + pass + return [val] + if isinstance(val, (list, tuple, set)): + return [str(x) for x in val if x] + return [str(val)] + + +def get_item_groups_with_descendants(item_groups: Any) -> list[str]: + """Return the given item groups and all their descendants in the tree hierarchy.""" + groups = parse_filter_list(item_groups) + if not groups: + return [] + all_groups = set() + for ig in groups: + if not ig: + continue + all_groups.add(ig) + if descendants := get_descendants_of("Item Group", ig, ignore_permissions=True): + all_groups.update(descendants) + return list(all_groups) + + +class StockBalanceCustomReport(StockBalanceReport): + """Custom Stock Balance Report subclassing ERPNext's standard StockBalanceReport + + Enhances standard functionality by supporting multiselect Item Group filters with descendant traversal. + """ + + def __init__(self, filters: StockBalanceFilter | dict[str, Any] | None = None) -> None: + # Ensure self.filters is a frappe._dict for consistent attribute & dict-style access + super().__init__(frappe._dict(filters or {})) + + def prepare_stock_reco_voucher_wise_count(self) -> None: + self.stock_reco_voucher_wise_count = frappe._dict() + + doctype = frappe.qb.DocType("Stock Ledger Entry") + item = frappe.qb.DocType("Item") + + query = ( + frappe.qb.from_(doctype) + .inner_join(item) + .on(doctype.item_code == item.name) + .select(doctype.voucher_detail_no, Count(doctype.name).as_("count")) + .where( + (doctype.voucher_type == "Stock Reconciliation") + & (doctype.docstatus < 2) + & (doctype.is_cancelled == 0) + & (item.has_serial_no == 1) + ) + .groupby(doctype.voucher_detail_no) + ) + + if items := self.filters.get("item_code"): + items = parse_filter_list(items) + if items: + query = query.where(item.name.isin(items)) + + if self.filters.get("item_group"): + children = get_item_groups_with_descendants(self.filters.get("item_group")) + if children: + query = query.where(item.item_group.isin(children)) + + if warehouses := self.filters.get("warehouse"): + warehouses = parse_filter_list(warehouses) + children = [] + for warehouse in warehouses: + children.append(warehouse) + if warehouse_children := get_descendants_of("Warehouse", warehouse, ignore_permissions=True): + children.extend(warehouse_children) + + if children: + query = query.where(doctype.warehouse.isin(children)) + + data = query.run(as_dict=True) + if not data: + return + + for row in data: + if row.count != 1: + continue + + sr_item = frappe.db.get_value( + "Stock Reconciliation Item", row.voucher_detail_no, ["current_qty", "qty"], as_dict=True + ) + + if sr_item and sr_item.qty and sr_item.current_qty: + self.stock_reco_voucher_wise_count[row.voucher_detail_no] = sr_item.current_qty + + def get_closing_balance(self) -> list[dict[str, Any]]: + if self.filters.get("ignore_closing_balance"): + return [] + + table = frappe.qb.DocType("Closing Stock Balance") + + query = ( + frappe.qb.from_(table) + .select(table.name, table.to_date) + .where( + (table.docstatus == 1) + & (table.company == self.filters.get("company")) + & (table.to_date <= self.from_date) + & (table.status == "Completed") + ) + .orderby(table.to_date, order=Order.desc) + .limit(1) + ) + + for fieldname in ["warehouse", "item_code", "item_group", "warehouse_type"]: + if value := self.filters.get(fieldname): + if fieldname == "item_group": + groups = parse_filter_list(value) + if groups: + query = query.where(table[fieldname].isin(groups)) + elif isinstance(value, (list, tuple, set)): + query = query.where(table[fieldname].isin(list(value))) + else: + query = query.where(table[fieldname] == value) + + return query.run(as_dict=True) + + def apply_items_filters(self, query, item_table): + if item_group := self.filters.get("item_group"): + children = get_item_groups_with_descendants(item_group) + if children: + query = query.where(item_table.item_group.isin(children)) + + if item_codes := self.filters.get("item_code"): + item_codes = parse_filter_list(item_codes) + if item_codes: + query = query.where(item_table.name.isin(item_codes)) + + if brand := self.filters.get("brand"): + query = query.where(item_table.brand == brand) + + return query