From 08a06ce5c68023c41f53b584082b5e1c4ddb1f59 Mon Sep 17 00:00:00 2001 From: Deepesh Garg Date: Thu, 17 Mar 2022 12:56:43 +0530 Subject: [PATCH 01/63] fix: Clean and fixes in Dimension-wise Accounts Balance Report --- .../dimension_wise_accounts_balance_report.js | 5 +- .../dimension_wise_accounts_balance_report.py | 154 ++++++++---------- 2 files changed, 76 insertions(+), 83 deletions(-) diff --git a/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.js b/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.js index 6a0394861b8..ea05a35b259 100644 --- a/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.js +++ b/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.js @@ -39,12 +39,14 @@ frappe.require("assets/erpnext/js/financial_statements.js", function() { "label": __("From Date"), "fieldtype": "Date", "default": frappe.defaults.get_user_default("year_start_date"), + "reqd": 1 }, { "fieldname": "to_date", "label": __("To Date"), "fieldtype": "Date", "default": frappe.defaults.get_user_default("year_end_date"), + "reqd": 1 }, { "fieldname": "finance_book", @@ -56,6 +58,7 @@ frappe.require("assets/erpnext/js/financial_statements.js", function() { "fieldname": "dimension", "label": __("Select Dimension"), "fieldtype": "Select", + "default": "Cost Center", "options": get_accounting_dimension_options(), "reqd": 1, }, @@ -70,7 +73,7 @@ frappe.require("assets/erpnext/js/financial_statements.js", function() { }); function get_accounting_dimension_options() { - let options =["", "Cost Center", "Project"]; + let options =["Cost Center", "Project"]; frappe.db.get_list('Accounting Dimension', {fields:['document_type']}).then((res) => { res.forEach((dimension) => { diff --git a/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py b/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py index c69bb3f70c5..c14f9524323 100644 --- a/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py +++ b/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py @@ -16,20 +16,22 @@ from erpnext.accounts.report.trial_balance.trial_balance import validate_filters def execute(filters=None): - validate_filters(filters) - dimension_items_list = get_dimension_items_list(filters.dimension, filters.company) - if not dimension_items_list: + validate_filters(filters) + dimension_list = get_dimensions(filters) + + if not dimension_list: return [], [] - dimension_items_list = [''.join(d) for d in dimension_items_list] - columns = get_columns(dimension_items_list) - data = get_data(filters, dimension_items_list) + # dimension_items_list = [''.join(d) for d in dimension_items_list] + columns = get_columns(dimension_list) + data = get_data(filters, dimension_list) return columns, data -def get_data(filters, dimension_items_list): +def get_data(filters, dimension_list): company_currency = erpnext.get_company_currency(filters.company) + acc = frappe.db.sql(""" select name, account_number, parent_account, lft, rgt, root_type, @@ -52,60 +54,54 @@ def get_data(filters, dimension_items_list): where lft >= %s and rgt <= %s and company = %s""", (min_lft, max_rgt, filters.company)) gl_entries_by_account = {} - set_gl_entries_by_account(dimension_items_list, filters, account, gl_entries_by_account) - format_gl_entries(gl_entries_by_account, accounts_by_name, dimension_items_list) - accumulate_values_into_parents(accounts, accounts_by_name, dimension_items_list) - out = prepare_data(accounts, filters, parent_children_map, company_currency, dimension_items_list) + set_gl_entries_by_account(dimension_list, filters, account, gl_entries_by_account) + format_gl_entries(gl_entries_by_account, accounts_by_name, dimension_list, + frappe.scrub(filters.get('dimension'))) + accumulate_values_into_parents(accounts, accounts_by_name, dimension_list) + out = prepare_data(accounts, filters, company_currency, dimension_list) out = filter_out_zero_value_rows(out, parent_children_map) return out -def set_gl_entries_by_account(dimension_items_list, filters, account, gl_entries_by_account): - for item in dimension_items_list: - condition = get_condition(filters.from_date, item, filters.dimension) - if account: - condition += " and account in ({})"\ - .format(", ".join([frappe.db.escape(d) for d in account])) +def set_gl_entries_by_account(dimension_list, filters, account, gl_entries_by_account): + condition = get_condition(filters.get('dimension')) - gl_filters = { - "company": filters.get("company"), - "from_date": filters.get("from_date"), - "to_date": filters.get("to_date"), - "finance_book": cstr(filters.get("finance_book")) - } + if account: + condition += " and account in ({})"\ + .format(", ".join([frappe.db.escape(d) for d in account])) - gl_filters['item'] = ''.join(item) + gl_filters = { + "company": filters.get("company"), + "from_date": filters.get("from_date"), + "to_date": filters.get("to_date"), + "finance_book": cstr(filters.get("finance_book")) + } - if filters.get("include_default_book_entries"): - gl_filters["company_fb"] = frappe.db.get_value("Company", - filters.company, 'default_finance_book') + gl_filters['dimensions'] = set(dimension_list) - for key, value in filters.items(): - if value: - gl_filters.update({ - key: value - }) + if filters.get("include_default_book_entries"): + gl_filters["company_fb"] = frappe.db.get_value("Company", + filters.company, 'default_finance_book') - gl_entries = frappe.db.sql(""" + gl_entries = frappe.db.sql(""" select - posting_date, account, debit, credit, is_opening, fiscal_year, + posting_date, account, {dimension}, debit, credit, is_opening, fiscal_year, debit_in_account_currency, credit_in_account_currency, account_currency from `tabGL Entry` where company=%(company)s {condition} + and posting_date >= %(from_date)s and posting_date <= %(to_date)s and is_cancelled = 0 order by account, posting_date""".format( - condition=condition), - gl_filters, as_dict=True) #nosec + dimension = frappe.scrub(filters.get('dimension')), condition=condition), gl_filters, as_dict=True) #nosec - for entry in gl_entries: - entry['dimension_item'] = ''.join(item) - gl_entries_by_account.setdefault(entry.account, []).append(entry) + for entry in gl_entries: + gl_entries_by_account.setdefault(entry.account, []).append(entry) -def format_gl_entries(gl_entries_by_account, accounts_by_name, dimension_items_list): +def format_gl_entries(gl_entries_by_account, accounts_by_name, dimension_list, dimension_type): for entries in itervalues(gl_entries_by_account): for entry in entries: @@ -115,11 +111,12 @@ def format_gl_entries(gl_entries_by_account, accounts_by_name, dimension_items_l _("Could not retrieve information for {0}.").format(entry.account), title="Error", raise_exception=1 ) - for item in dimension_items_list: - if item == entry.dimension_item: - d[frappe.scrub(item)] = d.get(frappe.scrub(item), 0.0) + flt(entry.debit) - flt(entry.credit) -def prepare_data(accounts, filters, parent_children_map, company_currency, dimension_items_list): + for dimension in dimension_list: + if dimension == entry.get(dimension_type): + d[frappe.scrub(dimension)] = d.get(frappe.scrub(dimension), 0.0) + flt(entry.debit) - flt(entry.credit) + +def prepare_data(accounts, filters, company_currency, dimension_list): data = [] for d in accounts: @@ -136,13 +133,13 @@ def prepare_data(accounts, filters, parent_children_map, company_currency, dimen if d.account_number else d.account_name) } - for item in dimension_items_list: - row[frappe.scrub(item)] = flt(d.get(frappe.scrub(item), 0.0), 3) + for dimension in dimension_list: + row[frappe.scrub(dimension)] = flt(d.get(frappe.scrub(dimension), 0.0), 3) - if abs(row[frappe.scrub(item)]) >= 0.005: + if abs(row[frappe.scrub(dimension)]) >= 0.005: # ignore zero values has_value = True - total += flt(d.get(frappe.scrub(item), 0.0), 3) + total += flt(d.get(frappe.scrub(dimension), 0.0), 3) row["has_value"] = has_value row["total"] = total @@ -150,62 +147,55 @@ def prepare_data(accounts, filters, parent_children_map, company_currency, dimen return data -def accumulate_values_into_parents(accounts, accounts_by_name, dimension_items_list): +def accumulate_values_into_parents(accounts, accounts_by_name, dimension_list): """accumulate children's values in parent accounts""" for d in reversed(accounts): if d.parent_account: - for item in dimension_items_list: - accounts_by_name[d.parent_account][frappe.scrub(item)] = \ - accounts_by_name[d.parent_account].get(frappe.scrub(item), 0.0) + d.get(frappe.scrub(item), 0.0) + for dimension in dimension_list: + accounts_by_name[d.parent_account][frappe.scrub(dimension)] = \ + accounts_by_name[d.parent_account].get(frappe.scrub(dimension), 0.0) + d.get(frappe.scrub(dimension), 0.0) -def get_condition(from_date, item, dimension): +def get_condition(dimension): conditions = [] - if from_date: - conditions.append("posting_date >= %(from_date)s") - if dimension: - if dimension not in ['Cost Center', 'Project']: - if dimension in ['Customer', 'Supplier']: - dimension = 'Party' - else: - dimension = 'Voucher No' - txt = "{0} = %(item)s".format(frappe.scrub(dimension)) - conditions.append(txt) + conditions.append("{0} in %(dimensions)s".format(frappe.scrub(dimension))) return " and {}".format(" and ".join(conditions)) if conditions else "" -def get_dimension_items_list(dimension, company): - meta = frappe.get_meta(dimension, cached=False) - fieldnames = [d.fieldname for d in meta.get("fields")] - filters = {} - if 'company' in fieldnames: - filters['company'] = company - return frappe.get_all(dimension, filters, as_list=True) +def get_dimensions(filters): + meta = frappe.get_meta(filters.get('dimension'), cached=False) + query_filters = {} -def get_columns(dimension_items_list, accumulated_values=1, company=None): + if meta.has_field('company'): + query_filters = {'company': filters.get('company')} + + return frappe.get_all(filters.get('dimension'), filters=query_filters, pluck='name') + +def get_columns(dimension_list): columns = [{ "fieldname": "account", "label": _("Account"), "fieldtype": "Link", "options": "Account", "width": 300 + }, + { + "fieldname": "currency", + "label": _("Currency"), + "fieldtype": "Link", + "options": "Currency", + "hidden": 1 }] - if company: + + for dimension in dimension_list: columns.append({ - "fieldname": "currency", - "label": _("Currency"), - "fieldtype": "Link", - "options": "Currency", - "hidden": 1 - }) - for item in dimension_items_list: - columns.append({ - "fieldname": frappe.scrub(item), - "label": item, + "fieldname": frappe.scrub(dimension), + "label": dimension, "fieldtype": "Currency", "options": "currency", "width": 150 }) + columns.append({ "fieldname": "total", "label": "Total", From cab69fe1f298b44613be21c06591e868c24ee249 Mon Sep 17 00:00:00 2001 From: Deepesh Garg Date: Thu, 17 Mar 2022 12:57:12 +0530 Subject: [PATCH 02/63] fix: Remove comments --- .../dimension_wise_accounts_balance_report.py | 1 - 1 file changed, 1 deletion(-) diff --git a/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py b/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py index c14f9524323..90992ac744c 100644 --- a/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py +++ b/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py @@ -23,7 +23,6 @@ def execute(filters=None): if not dimension_list: return [], [] - # dimension_items_list = [''.join(d) for d in dimension_items_list] columns = get_columns(dimension_list) data = get_data(filters, dimension_list) From aa1732a21287bf51f76523c39be00c643dfe36a2 Mon Sep 17 00:00:00 2001 From: Deepesh Garg Date: Tue, 15 Mar 2022 18:20:11 +0530 Subject: [PATCH 03/63] fix: Error in bank reco statement (cherry picked from commit fbcb413d9689222442f56197ab14bc17bd9b72bb) --- .../bank_reconciliation_statement.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py b/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py index b72d2669775..fe644ed3569 100644 --- a/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py +++ b/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py @@ -267,7 +267,7 @@ def get_loan_amount(filters): total_amount += flt(amount) - return amount + return total_amount def get_balance_row(label, amount, account_currency): if amount > 0: From face53ae8e43658cf45f0b5351b16ed4e12e8df4 Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Thu, 17 Mar 2022 18:17:16 +0530 Subject: [PATCH 04/63] feat: Create single PL/DN from several SO. (backport #30238) (#30289) * feat: Create single PL/DN from several SO. New PR from latest develop to avoid rebase (cherry picked from commit 61eb9b6c6848253da4108fbe1483c94ea4ec8a26) * to enable selection of SO irrespective of customer,removed validation for customer (cherry picked from commit 466df6bdb76cbd7da88f4d092e608b4c39889929) * fixed spacings (cherry picked from commit f33a725a9e137d5b9d7290baa072152e26740328) * added new field - Picked Qty, in Sales Order Item (cherry picked from commit a68213d82e7a98e289f04cfc5ee58c2f6d5730d9) * Added new field in SO - % Picked (cherry picked from commit 9f7fee7a4f601a455003a2e7b2deddeb7acfbcab) * removed semicolon for break statement (cherry picked from commit e970616b511e8aaa1a07fd96030029992ed2e6f6) * as per review comments - changed for loop (cherry picked from commit 0211f27e83255bc3c40b8866a3a4fc49909b8279) * corrected spacing (cherry picked from commit a12895ec035af45cacb04fd9459df6eb153024a4) Co-authored-by: Krithi Ramani --- .../doctype/sales_order/sales_order.json | 10 +- .../sales_order_item/sales_order_item.json | 8 +- erpnext/stock/doctype/pick_list/pick_list.js | 4 - erpnext/stock/doctype/pick_list/pick_list.py | 170 +++++++++++++----- .../stock/doctype/pick_list/test_pick_list.py | 98 +++++++++- 5 files changed, 232 insertions(+), 58 deletions(-) diff --git a/erpnext/selling/doctype/sales_order/sales_order.json b/erpnext/selling/doctype/sales_order/sales_order.json index 7e99a062439..fe2f14e19a6 100644 --- a/erpnext/selling/doctype/sales_order/sales_order.json +++ b/erpnext/selling/doctype/sales_order/sales_order.json @@ -130,6 +130,7 @@ "per_delivered", "column_break_81", "per_billed", + "per_picked", "billing_status", "sales_team_section_break", "sales_partner", @@ -1514,13 +1515,19 @@ "fieldtype": "Currency", "label": "Amount Eligible for Commission", "read_only": 1 + }, + { + "fieldname": "per_picked", + "fieldtype": "Percent", + "label": "% Picked", + "read_only": 1 } ], "icon": "fa fa-file-text", "idx": 105, "is_submittable": 1, "links": [], - "modified": "2021-10-05 12:16:40.775704", + "modified": "2022-03-15 21:38:31.437586", "modified_by": "Administrator", "module": "Selling", "name": "Sales Order", @@ -1594,6 +1601,7 @@ "show_name_in_global_search": 1, "sort_field": "modified", "sort_order": "DESC", + "states": [], "timeline_field": "customer", "title_field": "customer_name", "track_changes": 1, diff --git a/erpnext/selling/doctype/sales_order_item/sales_order_item.json b/erpnext/selling/doctype/sales_order_item/sales_order_item.json index 7e55499533b..195e96486b3 100644 --- a/erpnext/selling/doctype/sales_order_item/sales_order_item.json +++ b/erpnext/selling/doctype/sales_order_item/sales_order_item.json @@ -23,6 +23,7 @@ "quantity_and_rate", "qty", "stock_uom", + "picked_qty", "col_break2", "uom", "conversion_factor", @@ -798,12 +799,17 @@ "fieldtype": "Check", "label": "Grant Commission", "read_only": 1 + }, + { + "fieldname": "picked_qty", + "fieldtype": "Float", + "label": "Picked Qty" } ], "idx": 1, "istable": 1, "links": [], - "modified": "2022-02-24 14:41:57.325799", + "modified": "2022-03-15 20:17:33.984799", "modified_by": "Administrator", "module": "Selling", "name": "Sales Order Item", diff --git a/erpnext/stock/doctype/pick_list/pick_list.js b/erpnext/stock/doctype/pick_list/pick_list.js index 730fd7a829c..13b74b5eb16 100644 --- a/erpnext/stock/doctype/pick_list/pick_list.js +++ b/erpnext/stock/doctype/pick_list/pick_list.js @@ -146,10 +146,6 @@ frappe.ui.form.on('Pick List', { customer: frm.doc.customer }; frm.get_items_btn = frm.add_custom_button(__('Get Items'), () => { - if (!frm.doc.customer) { - frappe.msgprint(__('Please select Customer first')); - return; - } erpnext.utils.map_current_doc({ method: 'erpnext.selling.doctype.sales_order.sales_order.create_pick_list', source_doctype: 'Sales Order', diff --git a/erpnext/stock/doctype/pick_list/pick_list.py b/erpnext/stock/doctype/pick_list/pick_list.py index b2eaecb5868..3a496866cf1 100644 --- a/erpnext/stock/doctype/pick_list/pick_list.py +++ b/erpnext/stock/doctype/pick_list/pick_list.py @@ -3,6 +3,8 @@ import json from collections import OrderedDict, defaultdict +from itertools import groupby +from operator import itemgetter import frappe from frappe import _ @@ -24,8 +26,21 @@ class PickList(Document): def before_save(self): self.set_item_locations() + # set percentage picked in SO + for location in self.get('locations'): + if location.sales_order and frappe.db.get_value("Sales Order",location.sales_order,"per_picked") == 100: + frappe.throw("Row " + str(location.idx) + " has been picked already!") + def before_submit(self): for item in self.locations: + # if the user has not entered any picked qty, set it to stock_qty, before submit + if item.picked_qty == 0: + item.picked_qty = item.stock_qty + + if item.sales_order_item: + # update the picked_qty in SO Item + self.update_so(item.sales_order_item,item.picked_qty,item.item_code) + if not frappe.get_cached_value('Item', item.item_code, 'has_serial_no'): continue if not item.serial_no: @@ -37,6 +52,32 @@ class PickList(Document): frappe.throw(_('For item {0} at row {1}, count of serial numbers does not match with the picked quantity') .format(frappe.bold(item.item_code), frappe.bold(item.idx)), title=_("Quantity Mismatch")) + def before_cancel(self): + #update picked_qty in SO Item on cancel of PL + for location in self.get('locations'): + if location.sales_order_item: + self.update_so(location.sales_order_item,0,location.item_code) + + def update_so(self,so_item,picked_qty,item_code): + so_doc = frappe.get_doc("Sales Order",frappe.db.get_value("Sales Order Item",so_item,"parent")) + already_picked,actual_qty = frappe.db.get_value("Sales Order Item",so_item,["picked_qty","qty"]) + + if self.docstatus == 1: + if (((already_picked + picked_qty)/ actual_qty)*100) > (100 + flt(frappe.db.get_single_value('Stock Settings', 'over_delivery_receipt_allowance'))): + frappe.throw('You are picking more than required quantity for ' + item_code + '. Check if there is any other pick list created for '+so_doc.name) + + frappe.db.set_value("Sales Order Item",so_item,"picked_qty",already_picked+picked_qty) + + total_picked_qty = 0 + total_so_qty = 0 + for item in so_doc.get('items'): + total_picked_qty += flt(item.picked_qty) + total_so_qty += flt(item.stock_qty) + total_picked_qty=total_picked_qty + picked_qty + per_picked = total_picked_qty/total_so_qty * 100 + + so_doc.db_set("per_picked", flt(per_picked) ,update_modified=False) + @frappe.whitelist() def set_item_locations(self, save=False): self.validate_for_qty() @@ -64,10 +105,6 @@ class PickList(Document): item_doc.name = None for row in locations: - row.update({ - 'picked_qty': row.stock_qty - }) - location = item_doc.as_dict() location.update(row) self.append('locations', location) @@ -340,63 +377,102 @@ def get_available_item_locations_for_other_item(item_code, from_warehouses, requ def create_delivery_note(source_name, target_doc=None): pick_list = frappe.get_doc('Pick List', source_name) validate_item_locations(pick_list) - - sales_orders = [d.sales_order for d in pick_list.locations if d.sales_order] - sales_orders = set(sales_orders) - + sales_dict = dict() + sales_orders = [] delivery_note = None - for sales_order in sales_orders: - delivery_note = create_delivery_note_from_sales_order(sales_order, - delivery_note, skip_item_mapping=True) + for location in pick_list.locations: + if location.sales_order: + sales_orders.append([frappe.db.get_value("Sales Order",location.sales_order,'customer'),location.sales_order]) + # Group sales orders by customer + for key,keydata in groupby(sales_orders,key=itemgetter(0)): + sales_dict[key] = set([d[1] for d in keydata]) - # map rows without sales orders as well - if not delivery_note: + if sales_dict: + delivery_note = create_dn_with_so(sales_dict,pick_list) + + is_item_wo_so = 0 + for location in pick_list.locations : + if not location.sales_order: + is_item_wo_so = 1 + break + if is_item_wo_so == 1: + # Create a DN for items without sales orders as well + delivery_note = create_dn_wo_so(pick_list) + + frappe.msgprint(_('Delivery Note(s) created for the Pick List')) + return delivery_note + +def create_dn_wo_so(pick_list): delivery_note = frappe.new_doc("Delivery Note") - item_table_mapper = { - 'doctype': 'Delivery Note Item', - 'field_map': { - 'rate': 'rate', - 'name': 'so_detail', - 'parent': 'against_sales_order', - }, - 'condition': lambda doc: abs(doc.delivered_qty) < abs(doc.qty) and doc.delivered_by_supplier!=1 - } - - item_table_mapper_without_so = { - 'doctype': 'Delivery Note Item', - 'field_map': { - 'rate': 'rate', - 'name': 'name', - 'parent': '', + item_table_mapper_without_so = { + 'doctype': 'Delivery Note Item', + 'field_map': { + 'rate': 'rate', + 'name': 'name', + 'parent': '', + } } - } + map_pl_locations(pick_list,item_table_mapper_without_so,delivery_note) + delivery_note.insert(ignore_mandatory = True) + + return delivery_note + + +def create_dn_with_so(sales_dict,pick_list): + delivery_note = None + + for customer in sales_dict: + for so in sales_dict[customer]: + delivery_note = None + delivery_note = create_delivery_note_from_sales_order(so, + delivery_note, skip_item_mapping=True) + + item_table_mapper = { + 'doctype': 'Delivery Note Item', + 'field_map': { + 'rate': 'rate', + 'name': 'so_detail', + 'parent': 'against_sales_order', + }, + 'condition': lambda doc: abs(doc.delivered_qty) < abs(doc.qty) and doc.delivered_by_supplier!=1 + } + break + if delivery_note: + # map all items of all sales orders of that customer + for so in sales_dict[customer]: + map_pl_locations(pick_list,item_table_mapper,delivery_note,so) + delivery_note.insert(ignore_mandatory = True) + + return delivery_note + +def map_pl_locations(pick_list,item_mapper,delivery_note,sales_order = None): for location in pick_list.locations: - if location.sales_order_item: - sales_order_item = frappe.get_cached_doc('Sales Order Item', {'name':location.sales_order_item}) - else: - sales_order_item = None + if location.sales_order == sales_order: + if location.sales_order_item: + sales_order_item = frappe.get_cached_doc('Sales Order Item', {'name':location.sales_order_item}) + else: + sales_order_item = None - source_doc, table_mapper = [sales_order_item, item_table_mapper] if sales_order_item \ - else [location, item_table_mapper_without_so] + source_doc, table_mapper = [sales_order_item, item_mapper] if sales_order_item \ + else [location, item_mapper] - dn_item = map_child_doc(source_doc, delivery_note, table_mapper) + dn_item = map_child_doc(source_doc, delivery_note, table_mapper) - if dn_item: - dn_item.warehouse = location.warehouse - dn_item.qty = flt(location.picked_qty) / (flt(location.conversion_factor) or 1) - dn_item.batch_no = location.batch_no - dn_item.serial_no = location.serial_no - - update_delivery_note_item(source_doc, dn_item, delivery_note) + if dn_item: + dn_item.warehouse = location.warehouse + dn_item.qty = flt(location.picked_qty) / (flt(location.conversion_factor) or 1) + dn_item.batch_no = location.batch_no + dn_item.serial_no = location.serial_no + update_delivery_note_item(source_doc, dn_item, delivery_note) set_delivery_note_missing_values(delivery_note) delivery_note.pick_list = pick_list.name - delivery_note.customer = pick_list.customer if pick_list.customer else None + delivery_note.company = pick_list.company + delivery_note.customer = frappe.get_value("Sales Order",sales_order,"customer") - return delivery_note @frappe.whitelist() def create_stock_entry(pick_list): @@ -561,4 +637,4 @@ def update_common_item_properties(item, location): item.material_request = location.material_request item.serial_no = location.serial_no item.batch_no = location.batch_no - item.material_request_item = location.material_request_item + item.material_request_item = location.material_request_item \ No newline at end of file diff --git a/erpnext/stock/doctype/pick_list/test_pick_list.py b/erpnext/stock/doctype/pick_list/test_pick_list.py index f3b6b89784a..f60104c09ac 100644 --- a/erpnext/stock/doctype/pick_list/test_pick_list.py +++ b/erpnext/stock/doctype/pick_list/test_pick_list.py @@ -17,7 +17,6 @@ from erpnext.stock.doctype.stock_reconciliation.stock_reconciliation import ( class TestPickList(FrappeTestCase): - def test_pick_list_picks_warehouse_for_each_item(self): try: frappe.get_doc({ @@ -188,7 +187,6 @@ class TestPickList(FrappeTestCase): }] }) pick_list.set_item_locations() - self.assertEqual(pick_list.locations[0].batch_no, oldest_batch_no) pr1.cancel() @@ -311,6 +309,7 @@ class TestPickList(FrappeTestCase): 'item_code': '_Test Item', 'qty': 1, 'conversion_factor': 5, + 'stock_qty':5, 'delivery_date': frappe.utils.today() }, { 'item_code': '_Test Item', @@ -329,9 +328,9 @@ class TestPickList(FrappeTestCase): 'purpose': 'Delivery', 'locations': [{ 'item_code': '_Test Item', - 'qty': 1, - 'stock_qty': 5, - 'conversion_factor': 5, + 'qty': 2, + 'stock_qty': 1, + 'conversion_factor': 0.5, 'sales_order': sales_order.name, 'sales_order_item': sales_order.items[0].name , }, { @@ -389,6 +388,95 @@ class TestPickList(FrappeTestCase): for expected_item, created_item in zip(expected_items, pl.locations): _compare_dicts(expected_item, created_item) + def test_multiple_dn_creation(self): + sales_order_1 = frappe.get_doc({ + 'doctype': 'Sales Order', + 'customer': '_Test Customer', + 'company': '_Test Company', + 'items': [{ + 'item_code': '_Test Item', + 'qty': 1, + 'conversion_factor': 1, + 'delivery_date': frappe.utils.today() + }], + }).insert() + sales_order_1.submit() + sales_order_2 = frappe.get_doc({ + 'doctype': 'Sales Order', + 'customer': '_Test Customer 1', + 'company': '_Test Company', + 'items': [{ + 'item_code': '_Test Item 2', + 'qty': 1, + 'conversion_factor': 1, + 'delivery_date': frappe.utils.today() + }, + ], + }).insert() + sales_order_2.submit() + pick_list = frappe.get_doc({ + 'doctype': 'Pick List', + 'company': '_Test Company', + 'items_based_on': 'Sales Order', + 'purpose': 'Delivery', + 'picker':'P001', + 'locations': [{ + 'item_code': '_Test Item ', + 'qty': 1, + 'stock_qty': 1, + 'conversion_factor': 1, + 'sales_order': sales_order_1.name, + 'sales_order_item': sales_order_1.items[0].name , + }, { + 'item_code': '_Test Item 2', + 'qty': 1, + 'stock_qty': 1, + 'conversion_factor': 1, + 'sales_order': sales_order_2.name, + 'sales_order_item': sales_order_2.items[0].name , + } + ] + }) + pick_list.set_item_locations() + pick_list.submit() + create_delivery_note(pick_list.name) + for dn in frappe.get_all("Delivery Note",filters={"pick_list":pick_list.name,"customer":"_Test Customer"},fields={"name"}): + for dn_item in frappe.get_doc("Delivery Note",dn.name).get("items"): + self.assertEqual(dn_item.item_code, '_Test Item') + self.assertEqual(dn_item.against_sales_order,sales_order_1.name) + for dn in frappe.get_all("Delivery Note",filters={"pick_list":pick_list.name,"customer":"_Test Customer 1"},fields={"name"}): + for dn_item in frappe.get_doc("Delivery Note",dn.name).get("items"): + self.assertEqual(dn_item.item_code, '_Test Item 2') + self.assertEqual(dn_item.against_sales_order,sales_order_2.name) + #test DN creation without so + pick_list_1 = frappe.get_doc({ + 'doctype': 'Pick List', + 'company': '_Test Company', + 'purpose': 'Delivery', + 'picker':'P001', + 'locations': [{ + 'item_code': '_Test Item ', + 'qty': 1, + 'stock_qty': 1, + 'conversion_factor': 1, + }, { + 'item_code': '_Test Item 2', + 'qty': 2, + 'stock_qty': 2, + 'conversion_factor': 1, + } + ] + }) + pick_list_1.set_item_locations() + pick_list_1.submit() + create_delivery_note(pick_list_1.name) + for dn in frappe.get_all("Delivery Note",filters={"pick_list":pick_list_1.name},fields={"name"}): + for dn_item in frappe.get_doc("Delivery Note",dn.name).get("items"): + if dn_item.item_code == '_Test Item': + self.assertEqual(dn_item.qty,1) + if dn_item.item_code == '_Test Item 2': + self.assertEqual(dn_item.qty,2) + # def test_pick_list_skips_items_in_expired_batch(self): # pass From 935d2e3d64167f4f1a1c73496758e9c77c49bfbb Mon Sep 17 00:00:00 2001 From: Deepesh Garg Date: Wed, 16 Mar 2022 09:02:04 +0530 Subject: [PATCH 05/63] fix: Validate income/expense account in sales and purchase invoice (cherry picked from commit 06936cf1c024ffa4ed471790b8859aeadc5c5575) --- .../accounts/doctype/purchase_invoice/purchase_invoice.py | 6 ++++++ erpnext/accounts/doctype/sales_invoice/sales_invoice.py | 7 +++++++ erpnext/controllers/accounts_controller.py | 6 +++--- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py index f3452e1cf81..1c1d913886f 100644 --- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py +++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py @@ -33,6 +33,7 @@ from erpnext.accounts.utils import get_account_currency, get_fiscal_year from erpnext.assets.doctype.asset.asset import get_asset_account, is_cwip_accounting_enabled from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account from erpnext.buying.utils import check_on_hold_or_closed_status +from erpnext.controllers.accounts_controller import validate_account_head from erpnext.controllers.buying_controller import BuyingController from erpnext.stock import get_warehouse_account_map from erpnext.stock.doctype.purchase_receipt.purchase_receipt import ( @@ -105,6 +106,7 @@ class PurchaseInvoice(BuyingController): self.validate_uom_is_integer("uom", "qty") self.validate_uom_is_integer("stock_uom", "stock_qty") self.set_expense_account(for_validate=True) + self.validate_expense_account() self.set_against_expense_account() self.validate_write_off_account() self.validate_multiple_billing("Purchase Receipt", "pr_detail", "amount", "items") @@ -309,6 +311,10 @@ class PurchaseInvoice(BuyingController): elif not item.expense_account and for_validate: throw(_("Expense account is mandatory for item {0}").format(item.item_code or item.item_name)) + def validate_expense_account(self): + for item in self.get('items'): + validate_account_head(item.idx, item.expense_account, self.company, 'Expense') + def set_against_expense_account(self): against_accounts = [] for item in self.get("items"): diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py index f1e64c7d020..0186b3b9366 100644 --- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py +++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py @@ -38,6 +38,7 @@ from erpnext.assets.doctype.asset.depreciation import ( get_gl_entries_on_asset_regain, make_depreciation_entry, ) +from erpnext.controllers.accounts_controller import validate_account_head from erpnext.controllers.selling_controller import SellingController from erpnext.healthcare.utils import manage_invoice_submit_cancel from erpnext.projects.doctype.timesheet.timesheet import get_projectwise_timesheet_data @@ -113,6 +114,8 @@ class SalesInvoice(SellingController): self.validate_fixed_asset() self.set_income_account_for_fixed_assets() self.validate_item_cost_centers() + self.validate_income_account() + validate_inter_company_party(self.doctype, self.customer, self.company, self.inter_company_invoice_reference) if cint(self.is_pos): @@ -180,6 +183,10 @@ class SalesInvoice(SellingController): if cost_center_company != self.company: frappe.throw(_("Row #{0}: Cost Center {1} does not belong to company {2}").format(frappe.bold(item.idx), frappe.bold(item.cost_center), frappe.bold(self.company))) + def validate_income_account(self): + for item in self.get('items'): + validate_account_head(item.idx, item.income_account, self.company, 'Income') + def set_tax_withholding(self): tax_withholding_details = get_party_tax_withholding_details(self) diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py index f146071c0bd..23449082b89 100644 --- a/erpnext/controllers/accounts_controller.py +++ b/erpnext/controllers/accounts_controller.py @@ -1567,12 +1567,12 @@ def validate_taxes_and_charges(tax): tax.rate = None -def validate_account_head(idx, account, company): +def validate_account_head(idx, account, company, context=''): account_company = frappe.get_cached_value('Account', account, 'company') if account_company != company: - frappe.throw(_('Row {0}: Account {1} does not belong to Company {2}') - .format(idx, frappe.bold(account), frappe.bold(company)), title=_('Invalid Account')) + frappe.throw(_('Row {0}: {3} Account {1} does not belong to Company {2}') + .format(idx, frappe.bold(account), frappe.bold(company), context), title=_('Invalid Account')) def validate_cost_center(tax, doc): From 2cf19aa19d894b4759bb3c688e34d62b058525c2 Mon Sep 17 00:00:00 2001 From: Deepesh Garg Date: Thu, 17 Mar 2022 18:00:39 +0530 Subject: [PATCH 06/63] fix: Test case (cherry picked from commit 4237e5d9283023bc41e6efb147140750d1075b17) --- .../test_deferred_revenue_and_expense.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/erpnext/accounts/report/deferred_revenue_and_expense/test_deferred_revenue_and_expense.py b/erpnext/accounts/report/deferred_revenue_and_expense/test_deferred_revenue_and_expense.py index 86eb2134fe8..17475a77dbf 100644 --- a/erpnext/accounts/report/deferred_revenue_and_expense/test_deferred_revenue_and_expense.py +++ b/erpnext/accounts/report/deferred_revenue_and_expense/test_deferred_revenue_and_expense.py @@ -88,10 +88,12 @@ class TestDeferredRevenueAndExpense(unittest.TestCase): posting_date="2021-05-01", parent_cost_center="Main - _CD", cost_center="Main - _CD", - do_not_submit=True, + do_not_save=True, rate=300, price_list_rate=300, ) + + si.items[0].income_account = "Sales - _CD" si.items[0].enable_deferred_revenue = 1 si.items[0].service_start_date = "2021-05-01" si.items[0].service_end_date = "2021-08-01" @@ -269,11 +271,13 @@ class TestDeferredRevenueAndExpense(unittest.TestCase): posting_date="2021-05-01", parent_cost_center="Main - _CD", cost_center="Main - _CD", - do_not_submit=True, + do_not_save=True, rate=300, price_list_rate=300, ) + si.items[0].enable_deferred_revenue = 1 + si.items[0].income_account = "Sales - _CD" si.items[0].deferred_revenue_account = deferred_revenue_account si.items[0].income_account = "Sales - _CD" si.save() From 3d35c69a2d906ab07ee643ad0daa26de8c54d09b Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Fri, 18 Mar 2022 17:32:01 +0530 Subject: [PATCH 07/63] fix: respect db multi_tenancy while fetching precision (#30301) (#30302) [skip ci] (cherry picked from commit 5a9bf9ffd64ffba14cb4bff63431fff319a82ed7) Co-authored-by: Ankush Menat --- erpnext/stock/report/stock_ageing/stock_ageing.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/erpnext/stock/report/stock_ageing/stock_ageing.py b/erpnext/stock/report/stock_ageing/stock_ageing.py index 97a740e1844..7ca40033edb 100644 --- a/erpnext/stock/report/stock_ageing/stock_ageing.py +++ b/erpnext/stock/report/stock_ageing/stock_ageing.py @@ -12,7 +12,7 @@ from frappe.utils import cint, date_diff, flt from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos Filters = frappe._dict -precision = cint(frappe.db.get_single_value("System Settings", "float_precision")) + def execute(filters: Filters = None) -> Tuple: to_date = filters["to_date"] @@ -30,6 +30,8 @@ def format_report_data(filters: Filters, item_details: Dict, to_date: str) -> Li _func = itemgetter(1) data = [] + precision = cint(frappe.db.get_single_value("System Settings", "float_precision", cache=True)) + for item, item_dict in item_details.items(): earliest_age, latest_age = 0, 0 details = item_dict["details"] @@ -76,6 +78,9 @@ def get_average_age(fifo_queue: List, to_date: str) -> float: return flt(age_qty / total_qty, 2) if total_qty else 0.0 def get_range_age(filters: Filters, fifo_queue: List, to_date: str, item_dict: Dict) -> Tuple: + + precision = cint(frappe.db.get_single_value("System Settings", "float_precision", cache=True)) + range1 = range2 = range3 = above_range3 = 0.0 for item in fifo_queue: From cca9668309711bf3ca517726a94df547c5a16bbb Mon Sep 17 00:00:00 2001 From: Devarsh Bhatt <58166671+bhattdevarsh@users.noreply.github.com> Date: Sat, 19 Mar 2022 13:02:21 +0530 Subject: [PATCH 08/63] fix: Allow on Submit for Material Request Item Required Date (#30174) * fix: Allow on Submit for Material Request Item Required Date * chore: whitespace Co-authored-by: Ankush Menat --- erpnext/stock/doctype/material_request/material_request.py | 3 +++ .../doctype/material_request_item/material_request_item.json | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/erpnext/stock/doctype/material_request/material_request.py b/erpnext/stock/doctype/material_request/material_request.py index 50d43171f80..341c83023a3 100644 --- a/erpnext/stock/doctype/material_request/material_request.py +++ b/erpnext/stock/doctype/material_request/material_request.py @@ -83,6 +83,9 @@ class MaterialRequest(BuyingController): self.reset_default_field_value("set_warehouse", "items", "warehouse") self.reset_default_field_value("set_from_warehouse", "items", "from_warehouse") + def before_update_after_submit(self): + self.validate_schedule_date() + def validate_material_request_type(self): """ Validate fields in accordance with selected type """ diff --git a/erpnext/stock/doctype/material_request_item/material_request_item.json b/erpnext/stock/doctype/material_request_item/material_request_item.json index 2bad42a0ebb..dd66cfff8be 100644 --- a/erpnext/stock/doctype/material_request_item/material_request_item.json +++ b/erpnext/stock/doctype/material_request_item/material_request_item.json @@ -177,6 +177,7 @@ "fieldtype": "Column Break" }, { + "allow_on_submit": 1, "bold": 1, "columns": 2, "fieldname": "schedule_date", @@ -459,7 +460,7 @@ "index_web_pages_for_search": 1, "istable": 1, "links": [], - "modified": "2021-11-03 14:40:24.409826", + "modified": "2022-03-10 18:42:42.705190", "modified_by": "Administrator", "module": "Stock", "name": "Material Request Item", From 7bcad019538b8d85717a4bc48bccd54ba90ed1f2 Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Sun, 20 Mar 2022 19:25:10 +0530 Subject: [PATCH 09/63] fix(UX): misc serial no selector + warehouse.py refactor (backport #30309) (#30310) * fix: set current qty as default qty for stock entry (cherry picked from commit f4c213379e03f09c59dac1c16efbafe00ae37e3f) * fix: filter serial nos by selected batch number (cherry picked from commit 5ec27c90552ab5c95ef734bb620a0e1bdd5256ee) * fix: skip already selected serials in sr selector (cherry picked from commit 0a533d6ccc7356ef8b7c10e1c581cf630f7c3121) * fix: sort serial nos before sending (cherry picked from commit 4f8bb91eae3ac6d3a3837a21be7f635a4044ccd0) * test: auto serial fetching (cherry picked from commit b9eec331e3b884a2da5ee6995cca1a7135b7c3b0) * refactor: batch no filter handling (cherry picked from commit a585dff6fd05c885c6b4c35892f48d1fdf644487) # Conflicts: # erpnext/stock/doctype/serial_no/serial_no.py * refactor: Use QB for serial fetching query (cherry picked from commit 4b695915f458a7acb5257d1208d91f23998727eb) # Conflicts: # erpnext/stock/doctype/serial_no/serial_no.py * refactor(warehouse): raw query to ORM (cherry picked from commit 953afda01bc74f930d844d426d00f9f8cadea897) * test: warehouse conversion and treeview test (cherry picked from commit 684d9d66d1bf98a010516f125507712a3d59b2c8) * perf: Single query to delete bins instead of `N` (cherry picked from commit 48595742338a5ca2cd429164a643ae70a8c63caf) * chore: resolve conflicts Co-authored-by: Ankush Menat --- .../js/utils/serial_no_batch_selector.js | 32 ++++-- erpnext/stock/doctype/serial_no/serial_no.py | 101 ++++++++++-------- .../stock/doctype/serial_no/test_serial_no.py | 58 +++++++++- .../stock/doctype/warehouse/test_warehouse.py | 31 +++++- erpnext/stock/doctype/warehouse/warehouse.py | 30 +++--- 5 files changed, 178 insertions(+), 74 deletions(-) diff --git a/erpnext/public/js/utils/serial_no_batch_selector.js b/erpnext/public/js/utils/serial_no_batch_selector.js index 16e3fa0abd1..26e559f672b 100644 --- a/erpnext/public/js/utils/serial_no_batch_selector.js +++ b/erpnext/public/js/utils/serial_no_batch_selector.js @@ -75,7 +75,7 @@ erpnext.SerialNoBatchSelector = Class.extend({ fieldtype:'Float', read_only: me.has_batch && !me.has_serial_no, label: __(me.has_batch && !me.has_serial_no ? 'Selected Qty' : 'Qty'), - default: flt(me.item.stock_qty), + default: flt(me.item.stock_qty) || flt(me.item.transfer_qty), }, ...get_pending_qty_fields(me), { @@ -94,14 +94,16 @@ erpnext.SerialNoBatchSelector = Class.extend({ description: __('Fetch Serial Numbers based on FIFO'), click: () => { let qty = this.dialog.fields_dict.qty.get_value(); + let already_selected_serial_nos = get_selected_serial_nos(me); let numbers = frappe.call({ method: "erpnext.stock.doctype.serial_no.serial_no.auto_fetch_serial_number", args: { qty: qty, item_code: me.item_code, warehouse: typeof me.warehouse_details.name == "string" ? me.warehouse_details.name : '', - batch_no: me.item.batch_no || null, - posting_date: me.frm.doc.posting_date || me.frm.doc.transaction_date + batch_nos: me.item.batch_no || null, + posting_date: me.frm.doc.posting_date || me.frm.doc.transaction_date, + exclude_sr_nos: already_selected_serial_nos } }); @@ -575,15 +577,29 @@ function get_pending_qty_fields(me) { return pending_qty_fields; } -function calc_total_selected_qty(me) { +// get all items with same item code except row for which selector is open. +function get_rows_with_same_item_code(me) { const { frm: { doc: { items }}, item: { name, item_code }} = me; - const totalSelectedQty = items - .filter( item => ( item.name !== name ) && ( item.item_code === item_code ) ) - .map( item => flt(item.qty) ) - .reduce( (i, j) => i + j, 0); + return items.filter(item => (item.name !== name) && (item.item_code === item_code)) +} + +function calc_total_selected_qty(me) { + const totalSelectedQty = get_rows_with_same_item_code(me) + .map(item => flt(item.qty)) + .reduce((i, j) => i + j, 0); return totalSelectedQty; } +function get_selected_serial_nos(me) { + const selected_serial_nos = get_rows_with_same_item_code(me) + .map(item => item.serial_no) + .filter(serial => serial) + .map(sr_no_string => sr_no_string.split('\n')) + .reduce((acc, arr) => acc.concat(arr), []) + .filter(serial => serial); + return selected_serial_nos; +}; + function check_can_calculate_pending_qty(me) { const { frm: { doc }, item } = me; const docChecks = doc.bom_no diff --git a/erpnext/stock/doctype/serial_no/serial_no.py b/erpnext/stock/doctype/serial_no/serial_no.py index 350d5fec50f..f97ebb97140 100644 --- a/erpnext/stock/doctype/serial_no/serial_no.py +++ b/erpnext/stock/doctype/serial_no/serial_no.py @@ -7,9 +7,17 @@ import json import frappe from frappe import ValidationError, _ from frappe.model.naming import make_autoname -from frappe.utils import add_days, cint, cstr, flt, get_link_to_form, getdate, nowdate -from six import string_types -from six.moves import map +from frappe.query_builder.functions import Coalesce +from frappe.utils import ( + add_days, + cint, + cstr, + flt, + get_link_to_form, + getdate, + nowdate, + safe_json_loads, +) from erpnext.controllers.stock_controller import StockController from erpnext.stock.get_item_details import get_reserved_qty_for_so @@ -583,30 +591,37 @@ def get_delivery_note_serial_no(item_code, qty, delivery_note): return serial_nos @frappe.whitelist() -def auto_fetch_serial_number(qty, item_code, warehouse, posting_date=None, batch_nos=None, for_doctype=None): - filters = { "item_code": item_code, "warehouse": warehouse } +def auto_fetch_serial_number(qty, item_code, warehouse, + posting_date=None, batch_nos=None, for_doctype=None, exclude_sr_nos=None): + + filters = frappe._dict({"item_code": item_code, "warehouse": warehouse}) + + if exclude_sr_nos is None: + exclude_sr_nos = [] + else: + exclude_sr_nos = get_serial_nos(clean_serial_no_string("\n".join(exclude_sr_nos))) if batch_nos: - try: - filters["batch_no"] = json.loads(batch_nos) if (type(json.loads(batch_nos)) == list) else [json.loads(batch_nos)] - except Exception: - filters["batch_no"] = [batch_nos] + batch_nos = safe_json_loads(batch_nos) + if isinstance(batch_nos, list): + filters.batch_no = batch_nos + elif isinstance(batch_nos, str): + filters.batch_no = [batch_nos] if posting_date: - filters["expiry_date"] = posting_date + filters.expiry_date = posting_date serial_numbers = [] if for_doctype == 'POS Invoice': - reserved_sr_nos = get_pos_reserved_serial_nos(filters) - serial_numbers = fetch_serial_numbers(filters, qty, do_not_include=reserved_sr_nos) - else: - serial_numbers = fetch_serial_numbers(filters, qty) + exclude_sr_nos.extend(get_pos_reserved_serial_nos(filters)) - return [d.get('name') for d in serial_numbers] + serial_numbers = fetch_serial_numbers(filters, qty, do_not_include=exclude_sr_nos) + + return sorted([d.get('name') for d in serial_numbers]) @frappe.whitelist() def get_pos_reserved_serial_nos(filters): - if isinstance(filters, string_types): + if isinstance(filters, str): filters = json.loads(filters) pos_transacted_sr_nos = frappe.db.sql("""select item.serial_no as serial_no @@ -629,37 +644,37 @@ def get_pos_reserved_serial_nos(filters): def fetch_serial_numbers(filters, qty, do_not_include=None): if do_not_include is None: do_not_include = [] - batch_join_selection = "" - batch_no_condition = "" + batch_nos = filters.get("batch_no") expiry_date = filters.get("expiry_date") + serial_no = frappe.qb.DocType("Serial No") + + query = ( + frappe.qb + .from_(serial_no) + .select(serial_no.name) + .where( + (serial_no.item_code == filters["item_code"]) + & (serial_no.warehouse == filters["warehouse"]) + & (Coalesce(serial_no.sales_invoice, "") == "") + & (Coalesce(serial_no.delivery_document_no, "") == "") + ) + .orderby(serial_no.creation) + .limit(qty or 1) + ) + + if do_not_include: + query = query.where(serial_no.name.notin(do_not_include)) + if batch_nos: - batch_no_condition = """and sr.batch_no in ({}) """.format(', '.join("'%s'" % d for d in batch_nos)) + query = query.where(serial_no.batch_no.isin(batch_nos)) if expiry_date: - batch_join_selection = "LEFT JOIN `tabBatch` batch on sr.batch_no = batch.name " - expiry_date_cond = "AND ifnull(batch.expiry_date, '2500-12-31') >= %(expiry_date)s " - batch_no_condition += expiry_date_cond - - excluded_sr_nos = ", ".join(["" + frappe.db.escape(sr) + "" for sr in do_not_include]) or "''" - serial_numbers = frappe.db.sql(""" - SELECT sr.name FROM `tabSerial No` sr {batch_join_selection} - WHERE - sr.name not in ({excluded_sr_nos}) AND - sr.item_code = %(item_code)s AND - sr.warehouse = %(warehouse)s AND - ifnull(sr.sales_invoice,'') = '' AND - ifnull(sr.delivery_document_no, '') = '' - {batch_no_condition} - ORDER BY - sr.creation - LIMIT - {qty} - """.format( - excluded_sr_nos=excluded_sr_nos, - qty=qty or 1, - batch_join_selection=batch_join_selection, - batch_no_condition=batch_no_condition - ), filters, as_dict=1) + batch = frappe.qb.DocType("Batch") + query = (query + .left_join(batch).on(serial_no.batch_no == batch.name) + .where(Coalesce(batch.expiry_date, "4000-12-31") >= expiry_date) + ) + serial_numbers = query.run(as_dict=True) return serial_numbers diff --git a/erpnext/stock/doctype/serial_no/test_serial_no.py b/erpnext/stock/doctype/serial_no/test_serial_no.py index 057a7d4c01f..cca63078402 100644 --- a/erpnext/stock/doctype/serial_no/test_serial_no.py +++ b/erpnext/stock/doctype/serial_no/test_serial_no.py @@ -6,10 +6,12 @@ import frappe +from frappe.tests.utils import FrappeTestCase from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note from erpnext.stock.doctype.item.test_item import make_item from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import make_purchase_receipt +from erpnext.stock.doctype.serial_no.serial_no import * from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry from erpnext.stock.doctype.stock_entry.test_stock_entry import make_serialized_item @@ -18,9 +20,6 @@ from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse test_dependencies = ["Item"] test_records = frappe.get_test_records('Serial No') -from frappe.tests.utils import FrappeTestCase - -from erpnext.stock.doctype.serial_no.serial_no import * class TestSerialNo(FrappeTestCase): @@ -242,3 +241,56 @@ class TestSerialNo(FrappeTestCase): ) self.assertEqual(value_diff, -113) + def test_auto_fetch(self): + item_code = make_item(properties={ + "has_serial_no": 1, + "has_batch_no": 1, + "create_new_batch": 1, + "serial_no_series": "TEST.#######" + }).name + warehouse = "_Test Warehouse - _TC" + + in1 = make_stock_entry(item_code=item_code, to_warehouse=warehouse, qty=5) + in2 = make_stock_entry(item_code=item_code, to_warehouse=warehouse, qty=5) + + in1.reload() + in2.reload() + + batch1 = in1.items[0].batch_no + batch2 = in2.items[0].batch_no + + batch_wise_serials = { + batch1 : get_serial_nos(in1.items[0].serial_no), + batch2: get_serial_nos(in2.items[0].serial_no) + } + + # Test FIFO + first_fetch = auto_fetch_serial_number(5, item_code, warehouse) + self.assertEqual(first_fetch, batch_wise_serials[batch1]) + + # partial FIFO + partial_fetch = auto_fetch_serial_number(2, item_code, warehouse) + self.assertTrue(set(partial_fetch).issubset(set(first_fetch)), + msg=f"{partial_fetch} should be subset of {first_fetch}") + + # exclusion + remaining = auto_fetch_serial_number(3, item_code, warehouse, exclude_sr_nos=partial_fetch) + self.assertEqual(sorted(remaining + partial_fetch), first_fetch) + + # batchwise + for batch, expected_serials in batch_wise_serials.items(): + fetched_sr = auto_fetch_serial_number(5, item_code, warehouse, batch_nos=batch) + self.assertEqual(fetched_sr, sorted(expected_serials)) + + # non existing warehouse + self.assertEqual(auto_fetch_serial_number(10, item_code, warehouse="Nonexisting"), []) + + # multi batch + all_serials = [sr for sr_list in batch_wise_serials.values() for sr in sr_list] + fetched_serials = auto_fetch_serial_number(10, item_code, warehouse, batch_nos=list(batch_wise_serials.keys())) + self.assertEqual(sorted(all_serials), fetched_serials) + + # expiry date + frappe.db.set_value("Batch", batch1, "expiry_date", "1980-01-01") + non_expired_serials = auto_fetch_serial_number(5, item_code, warehouse, posting_date="2021-01-01", batch_nos=batch1) + self.assertEqual(non_expired_serials, []) diff --git a/erpnext/stock/doctype/warehouse/test_warehouse.py b/erpnext/stock/doctype/warehouse/test_warehouse.py index cdb771935b0..08d7c993521 100644 --- a/erpnext/stock/doctype/warehouse/test_warehouse.py +++ b/erpnext/stock/doctype/warehouse/test_warehouse.py @@ -4,12 +4,12 @@ import frappe from frappe.test_runner import make_test_records from frappe.tests.utils import FrappeTestCase -from frappe.utils import cint import erpnext -from erpnext.accounts.doctype.account.test_account import create_account, get_inventory_account +from erpnext.accounts.doctype.account.test_account import create_account from erpnext.stock.doctype.item.test_item import create_item from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry +from erpnext.stock.doctype.warehouse.warehouse import convert_to_group_or_ledger, get_children test_records = frappe.get_test_records('Warehouse') @@ -65,6 +65,33 @@ class TestWarehouse(FrappeTestCase): f"{item} linked to {item_default.default_warehouse} in {warehouse_ids}." ) + def test_group_non_group_conversion(self): + + warehouse = frappe.get_doc("Warehouse", create_warehouse("TestGroupConversion")) + + convert_to_group_or_ledger(warehouse.name) + warehouse.reload() + self.assertEqual(warehouse.is_group, 1) + + child = create_warehouse("GroupWHChild", {"parent_warehouse": warehouse.name}) + # chid exists + self.assertRaises(frappe.ValidationError, convert_to_group_or_ledger, warehouse.name) + frappe.delete_doc("Warehouse", child) + + convert_to_group_or_ledger(warehouse.name) + warehouse.reload() + self.assertEqual(warehouse.is_group, 0) + + make_stock_entry(item_code="_Test Item", target=warehouse.name, qty=1) + # SLE exists + self.assertRaises(frappe.ValidationError, convert_to_group_or_ledger, warehouse.name) + + def test_get_children(self): + company = "_Test Company" + + children = get_children("Warehouse", parent=company, company=company, is_root=True) + self.assertTrue(any(wh['value'] == "_Test Warehouse - _TC" for wh in children)) + def create_warehouse(warehouse_name, properties=None, company=None): if not company: diff --git a/erpnext/stock/doctype/warehouse/warehouse.py b/erpnext/stock/doctype/warehouse/warehouse.py index 9cfad86f142..4c7f41dcb5e 100644 --- a/erpnext/stock/doctype/warehouse/warehouse.py +++ b/erpnext/stock/doctype/warehouse/warehouse.py @@ -41,14 +41,11 @@ class Warehouse(NestedSet): def on_trash(self): # delete bin - bins = frappe.db.sql("select * from `tabBin` where warehouse = %s", - self.name, as_dict=1) + bins = frappe.get_all("Bin", fields="*", filters={"warehouse": self.name}) for d in bins: if d['actual_qty'] or d['reserved_qty'] or d['ordered_qty'] or \ d['indented_qty'] or d['projected_qty'] or d['planned_qty']: throw(_("Warehouse {0} can not be deleted as quantity exists for Item {1}").format(self.name, d['item_code'])) - else: - frappe.db.sql("delete from `tabBin` where name = %s", d['name']) if self.check_if_sle_exists(): throw(_("Warehouse can not be deleted as stock ledger entry exists for this warehouse.")) @@ -56,16 +53,15 @@ class Warehouse(NestedSet): if self.check_if_child_exists(): throw(_("Child warehouse exists for this warehouse. You can not delete this warehouse.")) + frappe.db.delete("Bin", filters={"warehouse": self.name}) self.update_nsm_model() self.unlink_from_items() def check_if_sle_exists(self): - return frappe.db.sql("""select name from `tabStock Ledger Entry` - where warehouse = %s limit 1""", self.name) + return frappe.db.exists("Stock Ledger Entry", {"warehouse": self.name}) def check_if_child_exists(self): - return frappe.db.sql("""select name from `tabWarehouse` - where parent_warehouse = %s limit 1""", self.name) + return frappe.db.exists("Warehouse", {"parent_warehouse": self.name}) def convert_to_group_or_ledger(self): if self.is_group: @@ -92,10 +88,7 @@ class Warehouse(NestedSet): return 1 def unlink_from_items(self): - frappe.db.sql(""" - update `tabItem Default` - set default_warehouse=NULL - where default_warehouse=%s""", self.name) + frappe.db.set_value("Item Default", {"default_warehouse": self.name}, "default_warehouse", None) @frappe.whitelist() def get_children(doctype, parent=None, company=None, is_root=False): @@ -164,15 +157,16 @@ def add_node(): frappe.get_doc(args).insert() @frappe.whitelist() -def convert_to_group_or_ledger(): - args = frappe.form_dict - return frappe.get_doc("Warehouse", args.docname).convert_to_group_or_ledger() +def convert_to_group_or_ledger(docname=None): + if not docname: + docname = frappe.form_dict.docname + return frappe.get_doc("Warehouse", docname).convert_to_group_or_ledger() def get_child_warehouses(warehouse): - lft, rgt = frappe.get_cached_value("Warehouse", warehouse, ["lft", "rgt"]) + from frappe.utils.nestedset import get_descendants_of - return frappe.db.sql_list("""select name from `tabWarehouse` - where lft >= %s and rgt <= %s""", (lft, rgt)) + children = get_descendants_of("Warehouse", warehouse, ignore_permissions=True, order_by="lft") + return children + [warehouse] # append self for backward compatibility def get_warehouses_based_on_account(account, company=None): warehouses = [] From 3636e596d3443ec60bdce61f90b3d4ae03e9cbd8 Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Sun, 20 Mar 2022 20:24:40 +0530 Subject: [PATCH 10/63] refactor: remove redundant if-statement (#30311) (#30316) (cherry picked from commit 0a015b7f70039d8f0aeeb5aad2473d0d8846b0db) Co-authored-by: Raffael Meyer <14891507+barredterra@users.noreply.github.com> --- .../production_plan/production_plan.py | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/erpnext/manufacturing/doctype/production_plan/production_plan.py b/erpnext/manufacturing/doctype/production_plan/production_plan.py index 60771592da5..93e9c94da53 100644 --- a/erpnext/manufacturing/doctype/production_plan/production_plan.py +++ b/erpnext/manufacturing/doctype/production_plan/production_plan.py @@ -982,21 +982,21 @@ def get_materials_from_other_locations(item, warehouses, new_mr_items, company): required_qty = item.get("quantity") # get available material by transferring to production warehouse for d in locations: - if required_qty <=0: return + if required_qty <= 0: + return new_dict = copy.deepcopy(item) quantity = required_qty if d.get("qty") > required_qty else d.get("qty") - if required_qty > 0: - new_dict.update({ - "quantity": quantity, - "material_request_type": "Material Transfer", - "uom": new_dict.get("stock_uom"), # internal transfer should be in stock UOM - "from_warehouse": d.get("warehouse") - }) + new_dict.update({ + "quantity": quantity, + "material_request_type": "Material Transfer", + "uom": new_dict.get("stock_uom"), # internal transfer should be in stock UOM + "from_warehouse": d.get("warehouse") + }) - required_qty -= quantity - new_mr_items.append(new_dict) + required_qty -= quantity + new_mr_items.append(new_dict) # raise purchase request for remaining qty if required_qty: From dc8674fe0d23fe4047089a0a19f78c0a33b8361e Mon Sep 17 00:00:00 2001 From: Syed Mujeer Hashmi Date: Mon, 21 Mar 2022 08:42:28 +0530 Subject: [PATCH 11/63] fix: Allow draft PE, PA to link to Vital Signs (#29934) Signed-off-by: Syed Mujeer Hashmi Co-authored-by: Chillar Anand Co-authored-by: Chillar Anand --- .../inpatient_record/inpatient_record.json | 16 ++++------------ .../doctype/vital_signs/vital_signs.json | 4 +--- 2 files changed, 5 insertions(+), 15 deletions(-) diff --git a/erpnext/healthcare/doctype/inpatient_record/inpatient_record.json b/erpnext/healthcare/doctype/inpatient_record/inpatient_record.json index 03ecf4fb018..e826ecf80bb 100644 --- a/erpnext/healthcare/doctype/inpatient_record/inpatient_record.json +++ b/erpnext/healthcare/doctype/inpatient_record/inpatient_record.json @@ -24,13 +24,12 @@ "expected_discharge", "references", "admission_encounter", - "admission_practitioner", + "primary_practitioner", "medical_department", "admission_ordered_for", "expected_length_of_stay", "admission_service_unit_type", "cb_admission", - "primary_practitioner", "secondary_practitioner", "admission_instruction", "encounter_details_section", @@ -134,11 +133,11 @@ "read_only": 1 }, { + "fetch_from": "primary_practitioner.department", "fieldname": "medical_department", "fieldtype": "Link", "label": "Medical Department", - "options": "Medical Department", - "set_only_once": 1 + "options": "Medical Department" }, { "fieldname": "primary_practitioner", @@ -211,13 +210,6 @@ "fieldname": "cb_admission", "fieldtype": "Column Break" }, - { - "fieldname": "admission_practitioner", - "fieldtype": "Link", - "label": "Healthcare Practitioner", - "options": "Healthcare Practitioner", - "read_only": 1 - }, { "fieldname": "admission_encounter", "fieldtype": "Link", @@ -412,7 +404,7 @@ ], "index_web_pages_for_search": 1, "links": [], - "modified": "2021-08-09 22:49:07.419692", + "modified": "2022-02-22 12:15:02.843426", "modified_by": "Administrator", "module": "Healthcare", "name": "Inpatient Record", diff --git a/erpnext/healthcare/doctype/vital_signs/vital_signs.json b/erpnext/healthcare/doctype/vital_signs/vital_signs.json index a945032c7e0..6d6c351ec35 100644 --- a/erpnext/healthcare/doctype/vital_signs/vital_signs.json +++ b/erpnext/healthcare/doctype/vital_signs/vital_signs.json @@ -72,7 +72,6 @@ "fieldtype": "Link", "in_filter": 1, "label": "Patient Appointment", - "no_copy": 1, "options": "Patient Appointment", "print_hide": 1, "read_only": 1 @@ -82,7 +81,6 @@ "fieldtype": "Link", "in_filter": 1, "label": "Patient Encounter", - "no_copy": 1, "options": "Patient Encounter", "print_hide": 1, "read_only": 1 @@ -258,7 +256,7 @@ ], "is_submittable": 1, "links": [], - "modified": "2022-01-20 12:30:07.515185", + "modified": "2022-02-19 11:48:16.347334", "modified_by": "Administrator", "module": "Healthcare", "name": "Vital Signs", From 75458f90b5f562cec0bcf8fb6bb87f73f7684a67 Mon Sep 17 00:00:00 2001 From: Deepesh Garg Date: Fri, 18 Mar 2022 17:32:46 +0530 Subject: [PATCH 12/63] fix: Add permission for KSA Vat documents (cherry picked from commit 972d06555aea8a8e4aec3186f3844b942fa54d38) # Conflicts: # erpnext/patches.txt --- erpnext/patches.txt | 26 ++++++++++++++++++++ erpnext/patches/v13_0/enable_ksa_vat_docs.py | 12 +++++++++ 2 files changed, 38 insertions(+) create mode 100644 erpnext/patches/v13_0/enable_ksa_vat_docs.py diff --git a/erpnext/patches.txt b/erpnext/patches.txt index ccafb6bb564..c0006cfdb7a 100644 --- a/erpnext/patches.txt +++ b/erpnext/patches.txt @@ -340,6 +340,32 @@ erpnext.patches.v13_0.rename_ksa_qr_field erpnext.patches.v13_0.wipe_serial_no_field_for_0_qty erpnext.patches.v13_0.disable_ksa_print_format_for_others # 16-12-2021 erpnext.patches.v13_0.update_tax_category_for_rcm +<<<<<<< HEAD +======= +execute:frappe.delete_doc_if_exists('Workspace', 'ERPNext Integrations Settings') +erpnext.patches.v14_0.set_payroll_cost_centers +erpnext.patches.v13_0.agriculture_deprecation_warning +erpnext.patches.v13_0.hospitality_deprecation_warning +erpnext.patches.v13_0.update_asset_quantity_field +erpnext.patches.v13_0.delete_bank_reconciliation_detail +erpnext.patches.v13_0.enable_provisional_accounting +erpnext.patches.v13_0.non_profit_deprecation_warning +erpnext.patches.v13_0.enable_ksa_vat_docs #1 + +[post_model_sync] +erpnext.patches.v14_0.rename_ongoing_status_in_sla_documents +erpnext.patches.v14_0.add_default_exit_questionnaire_notification_template +erpnext.patches.v14_0.delete_shopify_doctypes +erpnext.patches.v14_0.delete_hub_doctypes +erpnext.patches.v14_0.delete_hospitality_doctypes # 20-01-2022 +erpnext.patches.v14_0.delete_agriculture_doctypes +erpnext.patches.v14_0.rearrange_company_fields +erpnext.patches.v14_0.update_leave_notification_template +erpnext.patches.v14_0.restore_einvoice_fields +erpnext.patches.v13_0.update_sane_transfer_against +erpnext.patches.v12_0.add_company_link_to_einvoice_settings +erpnext.patches.v14_0.migrate_cost_center_allocations +>>>>>>> 972d06555a (fix: Add permission for KSA Vat documents) erpnext.patches.v13_0.convert_to_website_item_in_item_card_group_template erpnext.patches.v13_0.agriculture_deprecation_warning erpnext.patches.v13_0.update_maintenance_schedule_field_in_visit diff --git a/erpnext/patches/v13_0/enable_ksa_vat_docs.py b/erpnext/patches/v13_0/enable_ksa_vat_docs.py new file mode 100644 index 00000000000..3f482620e16 --- /dev/null +++ b/erpnext/patches/v13_0/enable_ksa_vat_docs.py @@ -0,0 +1,12 @@ +import frappe + +from erpnext.regional.saudi_arabia.setup import add_permissions, add_print_formats + + +def execute(): + company = frappe.get_all('Company', filters = {'country': 'Saudi Arabia'}) + if not company: + return + + add_print_formats() + add_permissions() \ No newline at end of file From da09b641741948b74d802492663fee4c2001f067 Mon Sep 17 00:00:00 2001 From: Deepesh Garg <42651287+deepeshgarg007@users.noreply.github.com> Date: Mon, 21 Mar 2022 10:28:58 +0530 Subject: [PATCH 13/63] fix: Conflicts --- erpnext/patches.txt | 29 ++--------------------------- 1 file changed, 2 insertions(+), 27 deletions(-) diff --git a/erpnext/patches.txt b/erpnext/patches.txt index c0006cfdb7a..9e3c82bc5d3 100644 --- a/erpnext/patches.txt +++ b/erpnext/patches.txt @@ -340,32 +340,6 @@ erpnext.patches.v13_0.rename_ksa_qr_field erpnext.patches.v13_0.wipe_serial_no_field_for_0_qty erpnext.patches.v13_0.disable_ksa_print_format_for_others # 16-12-2021 erpnext.patches.v13_0.update_tax_category_for_rcm -<<<<<<< HEAD -======= -execute:frappe.delete_doc_if_exists('Workspace', 'ERPNext Integrations Settings') -erpnext.patches.v14_0.set_payroll_cost_centers -erpnext.patches.v13_0.agriculture_deprecation_warning -erpnext.patches.v13_0.hospitality_deprecation_warning -erpnext.patches.v13_0.update_asset_quantity_field -erpnext.patches.v13_0.delete_bank_reconciliation_detail -erpnext.patches.v13_0.enable_provisional_accounting -erpnext.patches.v13_0.non_profit_deprecation_warning -erpnext.patches.v13_0.enable_ksa_vat_docs #1 - -[post_model_sync] -erpnext.patches.v14_0.rename_ongoing_status_in_sla_documents -erpnext.patches.v14_0.add_default_exit_questionnaire_notification_template -erpnext.patches.v14_0.delete_shopify_doctypes -erpnext.patches.v14_0.delete_hub_doctypes -erpnext.patches.v14_0.delete_hospitality_doctypes # 20-01-2022 -erpnext.patches.v14_0.delete_agriculture_doctypes -erpnext.patches.v14_0.rearrange_company_fields -erpnext.patches.v14_0.update_leave_notification_template -erpnext.patches.v14_0.restore_einvoice_fields -erpnext.patches.v13_0.update_sane_transfer_against -erpnext.patches.v12_0.add_company_link_to_einvoice_settings -erpnext.patches.v14_0.migrate_cost_center_allocations ->>>>>>> 972d06555a (fix: Add permission for KSA Vat documents) erpnext.patches.v13_0.convert_to_website_item_in_item_card_group_template erpnext.patches.v13_0.agriculture_deprecation_warning erpnext.patches.v13_0.update_maintenance_schedule_field_in_visit @@ -379,4 +353,5 @@ erpnext.patches.v13_0.amazon_mws_deprecation_warning erpnext.patches.v13_0.set_work_order_qty_in_so_from_mr erpnext.patches.v13_0.update_accounts_in_loan_docs erpnext.patches.v13_0.remove_unknown_links_to_prod_plan_items -erpnext.patches.v13_0.rename_non_profit_fields \ No newline at end of file +erpnext.patches.v13_0.rename_non_profit_fields +erpnext.patches.v13_0.enable_ksa_vat_docs #1 From 4dd6a99b69faff122b17dbc8215f035b150119e8 Mon Sep 17 00:00:00 2001 From: Saqib Ansari Date: Thu, 17 Mar 2022 11:56:10 +0530 Subject: [PATCH 14/63] fix: custom cash flow mapper doesn't show any data (cherry picked from commit 119273e633ec8e56c7d5c4649ef81c3deeb5f7d2) --- .../report/cash_flow/custom_cash_flow.py | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/erpnext/accounts/report/cash_flow/custom_cash_flow.py b/erpnext/accounts/report/cash_flow/custom_cash_flow.py index 45d147e7a21..ec0c9a7c7ea 100644 --- a/erpnext/accounts/report/cash_flow/custom_cash_flow.py +++ b/erpnext/accounts/report/cash_flow/custom_cash_flow.py @@ -30,12 +30,12 @@ def get_mappers_from_db(): def get_accounts_in_mappers(mapping_names): return frappe.db.sql(''' select cfma.name, cfm.label, cfm.is_working_capital, cfm.is_income_tax_liability, - cfm.is_income_tax_expense, cfm.is_finance_cost, cfm.is_finance_cost_adjustment + cfm.is_income_tax_expense, cfm.is_finance_cost, cfm.is_finance_cost_adjustment, cfma.account from `tabCash Flow Mapping Accounts` cfma join `tabCash Flow Mapping` cfm on cfma.parent=cfm.name where cfma.parent in (%s) order by cfm.is_working_capital - ''', (', '.join('"%s"' % d for d in mapping_names))) + ''', (', '.join('%s' % d for d in mapping_names))) def setup_mappers(mappers): @@ -57,31 +57,31 @@ def setup_mappers(mappers): account_types = [ dict( - name=account[0], label=account[1], is_working_capital=account[2], + name=account[0], account_name=account[7], label=account[1], is_working_capital=account[2], is_income_tax_liability=account[3], is_income_tax_expense=account[4] ) for account in accounts if not account[3]] finance_costs_adjustments = [ dict( - name=account[0], label=account[1], is_finance_cost=account[5], + name=account[0], account_name=account[7], label=account[1], is_finance_cost=account[5], is_finance_cost_adjustment=account[6] ) for account in accounts if account[6]] tax_liabilities = [ dict( - name=account[0], label=account[1], is_income_tax_liability=account[3], + name=account[0], account_name=account[7], label=account[1], is_income_tax_liability=account[3], is_income_tax_expense=account[4] ) for account in accounts if account[3]] tax_expenses = [ dict( - name=account[0], label=account[1], is_income_tax_liability=account[3], + name=account[0], account_name=account[7], label=account[1], is_income_tax_liability=account[3], is_income_tax_expense=account[4] ) for account in accounts if account[4]] finance_costs = [ dict( - name=account[0], label=account[1], is_finance_cost=account[5]) + name=account[0], account_name=account[7], label=account[1], is_finance_cost=account[5]) for account in accounts if account[5]] account_types_labels = sorted( @@ -124,27 +124,27 @@ def setup_mappers(mappers): ) for label in account_types_labels: - names = [d['name'] for d in account_types if d['label'] == label[0]] + names = [d['account_name'] for d in account_types if d['label'] == label[0]] m = dict(label=label[0], names=names, is_working_capital=label[1]) mapping['account_types'].append(m) for label in fc_adjustment_labels: - names = [d['name'] for d in finance_costs_adjustments if d['label'] == label[0]] + names = [d['account_name'] for d in finance_costs_adjustments if d['label'] == label[0]] m = dict(label=label[0], names=names) mapping['finance_costs_adjustments'].append(m) for label in unique_liability_labels: - names = [d['name'] for d in tax_liabilities if d['label'] == label[0]] + names = [d['account_name'] for d in tax_liabilities if d['label'] == label[0]] m = dict(label=label[0], names=names, tax_liability=label[1], tax_expense=label[2]) mapping['tax_liabilities'].append(m) for label in unique_expense_labels: - names = [d['name'] for d in tax_expenses if d['label'] == label[0]] + names = [d['account_name'] for d in tax_expenses if d['label'] == label[0]] m = dict(label=label[0], names=names, tax_liability=label[1], tax_expense=label[2]) mapping['tax_expenses'].append(m) for label in unique_finance_costs_labels: - names = [d['name'] for d in finance_costs if d['label'] == label[0]] + names = [d['account_name'] for d in finance_costs if d['label'] == label[0]] m = dict(label=label[0], names=names, is_finance_cost=label[1]) mapping['finance_costs'].append(m) @@ -378,7 +378,7 @@ def _get_account_type_based_data(filters, account_names, period_list, accumulate total = 0 for period in period_list: start_date = get_start_date(period, accumulated_values, company) - accounts = ', '.join('"%s"' % d for d in account_names) + accounts = ', '.join('%s' % d for d in account_names) if opening_balances: date_info = dict(date=start_date) From 8f6333cd40c1bbf76dc880275961a689fa4d1abb Mon Sep 17 00:00:00 2001 From: Saqib Ansari Date: Fri, 18 Mar 2022 14:26:33 +0530 Subject: [PATCH 15/63] refactor: convert raw sql to frappe.qb (cherry picked from commit 00bfee97c766e771a1ab0b57d223ba9e87b70e9a) --- .../report/cash_flow/custom_cash_flow.py | 89 ++++++++++++------- 1 file changed, 56 insertions(+), 33 deletions(-) diff --git a/erpnext/accounts/report/cash_flow/custom_cash_flow.py b/erpnext/accounts/report/cash_flow/custom_cash_flow.py index ec0c9a7c7ea..20f7fcfb1b3 100644 --- a/erpnext/accounts/report/cash_flow/custom_cash_flow.py +++ b/erpnext/accounts/report/cash_flow/custom_cash_flow.py @@ -4,7 +4,8 @@ import frappe from frappe import _ -from frappe.utils import add_to_date +from frappe.query_builder.functions import Sum +from frappe.utils import add_to_date, get_date_str from erpnext.accounts.report.financial_statements import get_columns, get_data, get_period_list from erpnext.accounts.report.profit_and_loss_statement.profit_and_loss_statement import ( @@ -28,15 +29,22 @@ def get_mappers_from_db(): def get_accounts_in_mappers(mapping_names): - return frappe.db.sql(''' - select cfma.name, cfm.label, cfm.is_working_capital, cfm.is_income_tax_liability, - cfm.is_income_tax_expense, cfm.is_finance_cost, cfm.is_finance_cost_adjustment, cfma.account - from `tabCash Flow Mapping Accounts` cfma - join `tabCash Flow Mapping` cfm on cfma.parent=cfm.name - where cfma.parent in (%s) - order by cfm.is_working_capital - ''', (', '.join('%s' % d for d in mapping_names))) + cfm = frappe.qb.DocType('Cash Flow Mapping') + cfma = frappe.qb.DocType('Cash Flow Mapping Accounts') + result = ( + frappe.qb + .select( + cfma.name, cfm.label, cfm.is_working_capital, + cfm.is_income_tax_liability, cfm.is_income_tax_expense, + cfm.is_finance_cost, cfm.is_finance_cost_adjustment, cfma.account + ) + .from_(cfm) + .join(cfma) + .on(cfm.name == cfma.parent) + .where(cfma.parent.isin(mapping_names)) + ).run() + return result def setup_mappers(mappers): cash_flow_accounts = [] @@ -371,14 +379,30 @@ def execute(filters=None): def _get_account_type_based_data(filters, account_names, period_list, accumulated_values, opening_balances=0): + if not account_names or not account_names[0] or not type(account_names[0]) == str: + # only proceed if account_names is a list of account names + return {} + from erpnext.accounts.report.cash_flow.cash_flow import get_start_date company = filters.company data = {} total = 0 + GLEntry = frappe.qb.DocType('GL Entry') + Account = frappe.qb.DocType('Account') + for period in period_list: start_date = get_start_date(period, accumulated_values, company) - accounts = ', '.join('%s' % d for d in account_names) + + account_subquery = ( + frappe.qb.from_(Account) + .where( + (Account.name.isin(account_names)) | + (Account.parent_account.isin(account_names)) + ) + .select(Account.name) + .as_("account_subquery") + ) if opening_balances: date_info = dict(date=start_date) @@ -395,32 +419,31 @@ def _get_account_type_based_data(filters, account_names, period_list, accumulate else: start, end = add_to_date(**date_info), add_to_date(**date_info) - gl_sum = frappe.db.sql_list(""" - select sum(credit) - sum(debit) - from `tabGL Entry` - where company=%s and posting_date >= %s and posting_date <= %s - and voucher_type != 'Period Closing Voucher' - and account in ( SELECT name FROM tabAccount WHERE name IN (%s) - OR parent_account IN (%s)) - """, (company, start, end, accounts, accounts)) - else: - gl_sum = frappe.db.sql_list(""" - select sum(credit) - sum(debit) - from `tabGL Entry` - where company=%s and posting_date >= %s and posting_date <= %s - and voucher_type != 'Period Closing Voucher' - and account in ( SELECT name FROM tabAccount WHERE name IN (%s) - OR parent_account IN (%s)) - """, (company, start_date if accumulated_values else period['from_date'], - period['to_date'], accounts, accounts)) + start, end = get_date_str(start), get_date_str(end) - if gl_sum and gl_sum[0]: - amount = gl_sum[0] else: - amount = 0 + start, end = start_date if accumulated_values else period['from_date'], period['to_date'] + start, end = get_date_str(start), get_date_str(end) - total += amount - data.setdefault(period["key"], amount) + result = ( + frappe.qb.from_(GLEntry) + .select(Sum(GLEntry.credit) - Sum(GLEntry.debit)) + .where( + (GLEntry.company == company) & + (GLEntry.posting_date >= start) & + (GLEntry.posting_date <= end) & + (GLEntry.voucher_type != 'Period Closing Voucher') & + (GLEntry.account.isin(account_subquery)) + ) + ).run() + + if result and result[0]: + gl_sum = result[0][0] + else: + gl_sum = 0 + + total += gl_sum + data.setdefault(period["key"], gl_sum) data["total"] = total return data From 1b5e936d27b8848e9d652c52aba84ef2b7eb4854 Mon Sep 17 00:00:00 2001 From: Deepesh Garg Date: Mon, 21 Mar 2022 09:42:28 +0530 Subject: [PATCH 16/63] fix: P&L account validation on cancellation (cherry picked from commit 2ff67902833283e120237435be3d53f8da8df2c4) --- erpnext/accounts/doctype/gl_entry/gl_entry.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/erpnext/accounts/doctype/gl_entry/gl_entry.py b/erpnext/accounts/doctype/gl_entry/gl_entry.py index f184b95a92d..0267ae84965 100644 --- a/erpnext/accounts/doctype/gl_entry/gl_entry.py +++ b/erpnext/accounts/doctype/gl_entry/gl_entry.py @@ -135,7 +135,7 @@ class GLEntry(Document): def check_pl_account(self): if self.is_opening=='Yes' and \ - frappe.db.get_value("Account", self.account, "report_type")=="Profit and Loss": + frappe.db.get_value("Account", self.account, "report_type")=="Profit and Loss" and not self.is_cancelled: frappe.throw(_("{0} {1}: 'Profit and Loss' type account {2} not allowed in Opening Entry") .format(self.voucher_type, self.voucher_no, self.account)) From 71d6209a290b0e85e5eae49fb0741e68c0e0dbdc Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Mon, 21 Mar 2022 12:29:21 +0530 Subject: [PATCH 17/63] fix: disable deferred naming on SLE/GLE if hash method is used. (#30286) (#30315) * fix: dont rename GLE/SLE that dont have naming series * test: tests for deferred naming of ledgers (cherry picked from commit c2aad115c19338998be81b4c47f1cd2f695b96cf) Co-authored-by: Ankush Menat --- erpnext/accounts/doctype/gl_entry/gl_entry.py | 2 + .../stock_ledger_entry/stock_ledger_entry.py | 2 + .../test_stock_ledger_entry.py | 61 +++++++++++++++++++ 3 files changed, 65 insertions(+) diff --git a/erpnext/accounts/doctype/gl_entry/gl_entry.py b/erpnext/accounts/doctype/gl_entry/gl_entry.py index 0267ae84965..36276023ecd 100644 --- a/erpnext/accounts/doctype/gl_entry/gl_entry.py +++ b/erpnext/accounts/doctype/gl_entry/gl_entry.py @@ -33,6 +33,8 @@ class GLEntry(Document): name will be changed using autoname options (in a scheduled job) """ self.name = frappe.generate_hash(txt="", length=10) + if self.meta.autoname == "hash": + self.to_rename = 0 def validate(self): self.flags.ignore_submit_comment = True diff --git a/erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py b/erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py index 39ca97a47bc..29a0d078692 100644 --- a/erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py +++ b/erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py @@ -27,6 +27,8 @@ class StockLedgerEntry(Document): name will be changed using autoname options (in a scheduled job) """ self.name = frappe.generate_hash(txt="", length=10) + if self.meta.autoname == "hash": + self.to_rename = 0 def validate(self): self.flags.ignore_submit_comment = True diff --git a/erpnext/stock/doctype/stock_ledger_entry/test_stock_ledger_entry.py b/erpnext/stock/doctype/stock_ledger_entry/test_stock_ledger_entry.py index ad78fba347b..1c3e0bfc229 100644 --- a/erpnext/stock/doctype/stock_ledger_entry/test_stock_ledger_entry.py +++ b/erpnext/stock/doctype/stock_ledger_entry/test_stock_ledger_entry.py @@ -5,9 +5,11 @@ import json import frappe from frappe.core.page.permission_manager.permission_manager import reset +from frappe.custom.doctype.property_setter.property_setter import make_property_setter from frappe.tests.utils import FrappeTestCase, change_settings from frappe.utils import add_days, today +from erpnext.accounts.doctype.gl_entry.gl_entry import rename_gle_sle_docs from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note from erpnext.stock.doctype.item.test_item import make_item from erpnext.stock.doctype.landed_cost_voucher.test_landed_cost_voucher import ( @@ -529,3 +531,62 @@ def create_items(): make_item(d, properties=properties) return items + + +class TestDeferredNaming(FrappeTestCase): + + @classmethod + def setUpClass(cls) -> None: + super().setUpClass() + cls.gle_autoname = frappe.get_meta("GL Entry").autoname + cls.sle_autoname = frappe.get_meta("Stock Ledger Entry").autoname + + def setUp(self) -> None: + self.item = make_item().name + self.warehouse = "Stores - TCP1" + self.company = "_Test Company with perpetual inventory" + + def tearDown(self) -> None: + make_property_setter(doctype="GL Entry", for_doctype=True, + property="autoname", value=self.gle_autoname, property_type="Data", fieldname=None) + make_property_setter(doctype="Stock Ledger Entry", for_doctype=True, + property="autoname", value=self.sle_autoname, property_type="Data", fieldname=None) + + # since deferred naming autocommits, commit all changes to avoid flake + frappe.db.commit() # nosemgrep + + @staticmethod + def get_gle_sles(se): + filters = {"voucher_type": se.doctype, "voucher_no": se.name} + gle = set(frappe.get_list("GL Entry", filters, pluck="name")) + sle = set(frappe.get_list("Stock Ledger Entry", filters, pluck="name")) + return gle, sle + + def test_deferred_naming(self): + se = make_stock_entry(item_code=self.item, to_warehouse=self.warehouse, + qty=10, rate=100, company=self.company) + + gle, sle = self.get_gle_sles(se) + rename_gle_sle_docs() + renamed_gle, renamed_sle = self.get_gle_sles(se) + + self.assertFalse(gle & renamed_gle, msg="GLEs not renamed") + self.assertFalse(sle & renamed_sle, msg="SLEs not renamed") + se.cancel() + + def test_hash_naming(self): + # disable naming series + for doctype in ("GL Entry", "Stock Ledger Entry"): + make_property_setter(doctype=doctype, for_doctype=True, + property="autoname", value="hash", property_type="Data", fieldname=None) + + se = make_stock_entry(item_code=self.item, to_warehouse=self.warehouse, + qty=10, rate=100, company=self.company) + + gle, sle = self.get_gle_sles(se) + rename_gle_sle_docs() + renamed_gle, renamed_sle = self.get_gle_sles(se) + + self.assertEqual(gle, renamed_gle, msg="GLEs are renamed while using hash naming") + self.assertEqual(sle, renamed_sle, msg="SLEs are renamed while using hash naming") + se.cancel() From 9abd22b4088b70ce23b80f91feab66c28cca6465 Mon Sep 17 00:00:00 2001 From: Nabin Hait Date: Mon, 21 Mar 2022 14:20:15 +0530 Subject: [PATCH 18/63] fix: Payment Request Amount calculation in case of multicurrency (#30254) --- erpnext/accounts/doctype/payment_request/payment_request.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/erpnext/accounts/doctype/payment_request/payment_request.py b/erpnext/accounts/doctype/payment_request/payment_request.py index 1a833a4008e..5cf534faba1 100644 --- a/erpnext/accounts/doctype/payment_request/payment_request.py +++ b/erpnext/accounts/doctype/payment_request/payment_request.py @@ -394,7 +394,10 @@ def get_amount(ref_doc, payment_account=None): """get amount based on doctype""" dt = ref_doc.doctype if dt in ["Sales Order", "Purchase Order"]: - grand_total = flt(ref_doc.grand_total) - flt(ref_doc.advance_paid) + if ref_doc.party_account_currency == ref_doc.currency: + grand_total = flt(ref_doc.grand_total) - flt(ref_doc.advance_paid) + else: + grand_total = flt(ref_doc.grand_total) - flt(ref_doc.advance_paid) / ref_doc.conversion_rate elif dt in ["Sales Invoice", "Purchase Invoice"]: if ref_doc.party_account_currency == ref_doc.currency: From c5f257da00e1c490571e303f2eb790773cbabd9c Mon Sep 17 00:00:00 2001 From: Nabin Hait Date: Mon, 21 Mar 2022 14:22:10 +0530 Subject: [PATCH 19/63] fix: While creating Payment Request from other forms, open a new Payment Request form without saving (#30228) --- erpnext/accounts/doctype/payment_request/payment_request.py | 2 +- .../accounts/doctype/payment_request/test_payment_request.py | 1 + erpnext/accounts/doctype/pos_invoice/pos_invoice.py | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/erpnext/accounts/doctype/payment_request/payment_request.py b/erpnext/accounts/doctype/payment_request/payment_request.py index 5cf534faba1..f77b060ee29 100644 --- a/erpnext/accounts/doctype/payment_request/payment_request.py +++ b/erpnext/accounts/doctype/payment_request/payment_request.py @@ -376,8 +376,8 @@ def make_payment_request(**args): if args.order_type == "Shopping Cart" or args.mute_email: pr.flags.mute_email = True - pr.insert(ignore_permissions=True) if args.submit_doc: + pr.insert(ignore_permissions=True) pr.submit() if args.order_type == "Shopping Cart": diff --git a/erpnext/accounts/doctype/payment_request/test_payment_request.py b/erpnext/accounts/doctype/payment_request/test_payment_request.py index f679ccfe4ff..cc70a96e742 100644 --- a/erpnext/accounts/doctype/payment_request/test_payment_request.py +++ b/erpnext/accounts/doctype/payment_request/test_payment_request.py @@ -128,6 +128,7 @@ class TestPaymentRequest(unittest.TestCase): pr1 = make_payment_request(dt="Sales Order", dn=so.name, recipient_id="nabin@erpnext.com", return_doc=1) pr1.grand_total = 200 + pr1.insert() pr1.submit() # Make a 2nd Payment Request diff --git a/erpnext/accounts/doctype/pos_invoice/pos_invoice.py b/erpnext/accounts/doctype/pos_invoice/pos_invoice.py index 466b2833fe1..431036abc18 100644 --- a/erpnext/accounts/doctype/pos_invoice/pos_invoice.py +++ b/erpnext/accounts/doctype/pos_invoice/pos_invoice.py @@ -456,6 +456,7 @@ class POSInvoice(SalesInvoice): pay_req = self.get_existing_payment_request(pay) if not pay_req: pay_req = self.get_new_payment_request(pay) + pay_req.insert() pay_req.submit() else: pay_req.request_phone_payment() From cedabd7242265f354e94d4e4b526db7dbd3d5dda Mon Sep 17 00:00:00 2001 From: Nabin Hait Date: Mon, 21 Mar 2022 14:23:31 +0530 Subject: [PATCH 20/63] fix: Future recurring period calculation for additional salary (#29581) * fix: Future recurring period calculation for addl salary * fix: future recurring period calculation Co-authored-by: Rucha Mahabal --- .../doctype/salary_slip/salary_slip.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/erpnext/payroll/doctype/salary_slip/salary_slip.py b/erpnext/payroll/doctype/salary_slip/salary_slip.py index ade6cc77636..2691680f578 100644 --- a/erpnext/payroll/doctype/salary_slip/salary_slip.py +++ b/erpnext/payroll/doctype/salary_slip/salary_slip.py @@ -781,11 +781,12 @@ class SalarySlip(TransactionBase): previous_total_paid_taxes = self.get_tax_paid_in_period(payroll_period.start_date, self.start_date, tax_component) # get taxable_earnings for current period (all days) - current_taxable_earnings = self.get_taxable_earnings(tax_slab.allow_tax_exemption) + current_taxable_earnings = self.get_taxable_earnings(tax_slab.allow_tax_exemption, payroll_period=payroll_period) future_structured_taxable_earnings = current_taxable_earnings.taxable_earnings * (math.ceil(remaining_sub_periods) - 1) # get taxable_earnings, addition_earnings for current actual payment days - current_taxable_earnings_for_payment_days = self.get_taxable_earnings(tax_slab.allow_tax_exemption, based_on_payment_days=1) + current_taxable_earnings_for_payment_days = self.get_taxable_earnings(tax_slab.allow_tax_exemption, + based_on_payment_days=1, payroll_period=payroll_period) current_structured_taxable_earnings = current_taxable_earnings_for_payment_days.taxable_earnings current_additional_earnings = current_taxable_earnings_for_payment_days.additional_income current_additional_earnings_with_full_tax = current_taxable_earnings_for_payment_days.additional_income_with_full_tax @@ -911,7 +912,7 @@ class SalarySlip(TransactionBase): return total_tax_paid - def get_taxable_earnings(self, allow_tax_exemption=False, based_on_payment_days=0): + def get_taxable_earnings(self, allow_tax_exemption=False, based_on_payment_days=0, payroll_period=None): joining_date, relieving_date = self.get_joining_and_relieving_dates() taxable_earnings = 0 @@ -938,7 +939,7 @@ class SalarySlip(TransactionBase): # Get additional amount based on future recurring additional salary if additional_amount and earning.is_recurring_additional_salary: additional_income += self.get_future_recurring_additional_amount(earning.additional_salary, - earning.additional_amount) # Used earning.additional_amount to consider the amount for the full month + earning.additional_amount, payroll_period) # Used earning.additional_amount to consider the amount for the full month if earning.deduct_full_tax_on_selected_payroll_date: additional_income_with_full_tax += additional_amount @@ -955,7 +956,7 @@ class SalarySlip(TransactionBase): if additional_amount and ded.is_recurring_additional_salary: additional_income -= self.get_future_recurring_additional_amount(ded.additional_salary, - ded.additional_amount) # Used ded.additional_amount to consider the amount for the full month + ded.additional_amount, payroll_period) # Used ded.additional_amount to consider the amount for the full month return frappe._dict({ "taxable_earnings": taxable_earnings, @@ -964,12 +965,18 @@ class SalarySlip(TransactionBase): "flexi_benefits": flexi_benefits }) - def get_future_recurring_additional_amount(self, additional_salary, monthly_additional_amount): + def get_future_recurring_additional_amount(self, additional_salary, monthly_additional_amount, payroll_period): future_recurring_additional_amount = 0 to_date = frappe.db.get_value("Additional Salary", additional_salary, 'to_date') # future month count excluding current from_date, to_date = getdate(self.start_date), getdate(to_date) + + # If recurring period end date is beyond the payroll period, + # last day of payroll period should be considered for recurring period calculation + if getdate(to_date) > getdate(payroll_period.end_date): + to_date = getdate(payroll_period.end_date) + future_recurring_period = ((to_date.year - from_date.year) * 12) + (to_date.month - from_date.month) if future_recurring_period > 0: From 34d27f1855d68f6cd97a559af91bd945f79ad75d Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Mon, 21 Mar 2022 15:39:04 +0530 Subject: [PATCH 21/63] fix: clear "Retain Sample" and "Max Sample Quantity" in Item card if Has Batch No is uncheck (backport #30307) (#30314) * fix: clear "Retain Sample" and "Max Sample Quantity" in Item card if Has Batch No is uncheck (#30307) (cherry picked from commit ca8d7576911c49139c556a00352aa6b5deda1d5b) # Conflicts: # erpnext/stock/doctype/item/test_item.py * chore: conflicts * refactor: correct usage for test decorator Co-authored-by: HENRY Florian Co-authored-by: Ankush Menat --- erpnext/stock/doctype/item/item.py | 8 ++++++++ erpnext/stock/doctype/item/test_item.py | 14 ++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/erpnext/stock/doctype/item/item.py b/erpnext/stock/doctype/item/item.py index efcaa90198c..c7835930021 100644 --- a/erpnext/stock/doctype/item/item.py +++ b/erpnext/stock/doctype/item/item.py @@ -108,6 +108,7 @@ class Item(Document): self.validate_variant_attributes() self.validate_variant_based_on_change() self.validate_fixed_asset() + self.clear_retain_sample() self.validate_retain_sample() self.validate_uom_conversion_factor() self.validate_customer_provided_part() @@ -210,6 +211,13 @@ class Item(Document): frappe.throw(_("{0} Retain Sample is based on batch, please check Has Batch No to retain sample of item").format( self.item_code)) + def clear_retain_sample(self): + if not self.has_batch_no: + self.retain_sample = None + + if not self.retain_sample: + self.sample_quantity = None + def add_default_uom_in_conversion_factor_table(self): if not self.is_new() and self.has_value_changed("stock_uom"): self.uoms = [] diff --git a/erpnext/stock/doctype/item/test_item.py b/erpnext/stock/doctype/item/test_item.py index a50ced006cc..9e8bf02a707 100644 --- a/erpnext/stock/doctype/item/test_item.py +++ b/erpnext/stock/doctype/item/test_item.py @@ -622,6 +622,20 @@ class TestItem(FrappeTestCase): item.item_group = "All Item Groups" item.save() # if item code saved without item_code then series worked + @change_settings("Stock Settings", {"sample_retention_warehouse": "_Test Warehouse - _TC"}) + def test_retain_sample(self): + item = make_item("_TestRetainSample", {'has_batch_no': 1, 'retain_sample': 1, 'sample_quantity': 1}) + + self.assertEqual(item.has_batch_no, 1) + self.assertEqual(item.retain_sample, 1) + self.assertEqual(item.sample_quantity, 1) + + item.has_batch_no = None + item.save() + self.assertEqual(item.retain_sample, None) + self.assertEqual(item.sample_quantity, None) + item.delete() + def set_item_variant_settings(fields): doc = frappe.get_doc('Item Variant Settings') From 3ca90cc3c701d1c24e976d8b633d2ed37fdc4546 Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Mon, 21 Mar 2022 15:53:08 +0530 Subject: [PATCH 22/63] fix(ux): warning for disabled carry forwarding in Policy Assignment (backport #30331) (#30333) Co-authored-by: Rucha Mahabal --- .../leave_policy_assignment.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/erpnext/hr/doctype/leave_policy_assignment/leave_policy_assignment.py b/erpnext/hr/doctype/leave_policy_assignment/leave_policy_assignment.py index 6e6943f71aa..ff1668003e7 100644 --- a/erpnext/hr/doctype/leave_policy_assignment/leave_policy_assignment.py +++ b/erpnext/hr/doctype/leave_policy_assignment/leave_policy_assignment.py @@ -8,14 +8,15 @@ from math import ceil import frappe from frappe import _, bold from frappe.model.document import Document -from frappe.utils import date_diff, flt, formatdate, get_last_day, getdate +from frappe.utils import date_diff, flt, formatdate, get_last_day, get_link_to_form, getdate from six import string_types class LeavePolicyAssignment(Document): def validate(self): - self.validate_policy_assignment_overlap() self.set_dates() + self.validate_policy_assignment_overlap() + self.warn_about_carry_forwarding() def on_submit(self): self.grant_leave_alloc_for_employee() @@ -39,6 +40,20 @@ class LeavePolicyAssignment(Document): frappe.throw(_("Leave Policy: {0} already assigned for Employee {1} for period {2} to {3}") .format(bold(self.leave_policy), bold(self.employee), bold(formatdate(self.effective_from)), bold(formatdate(self.effective_to)))) + def warn_about_carry_forwarding(self): + if not self.carry_forward: + return + + leave_types = get_leave_type_details() + leave_policy = frappe.get_doc("Leave Policy", self.leave_policy) + + for policy in leave_policy.leave_policy_details: + leave_type = leave_types.get(policy.leave_type) + if not leave_type.is_carry_forward: + msg = _("Leaves for the Leave Type {0} won't be carry-forwarded since carry-forwarding is disabled.").format( + frappe.bold(get_link_to_form("Leave Type", leave_type.name))) + frappe.msgprint(msg, indicator="orange", alert=True) + @frappe.whitelist() def grant_leave_alloc_for_employee(self): if self.leaves_allocated: From 7cba4975efe45e99966863f167e8cc4488b015e7 Mon Sep 17 00:00:00 2001 From: Deepesh Garg Date: Mon, 21 Mar 2022 21:28:41 +0530 Subject: [PATCH 23/63] fix: Taxes not getting fetched from item tax template --- .../public/js/controllers/taxes_and_totals.js | 20 ------------------ erpnext/public/js/controllers/transaction.js | 21 +++++++++++++++++++ 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/erpnext/public/js/controllers/taxes_and_totals.js b/erpnext/public/js/controllers/taxes_and_totals.js index 8068879810f..087b87c3432 100644 --- a/erpnext/public/js/controllers/taxes_and_totals.js +++ b/erpnext/public/js/controllers/taxes_and_totals.js @@ -278,26 +278,6 @@ erpnext.taxes_and_totals = erpnext.payments.extend({ } }, - add_taxes_from_item_tax_template: function(item_tax_map) { - let me = this; - - if (item_tax_map && cint(frappe.defaults.get_default("add_taxes_from_item_tax_template"))) { - if (typeof (item_tax_map) == "string") { - item_tax_map = JSON.parse(item_tax_map); - } - - $.each(item_tax_map, function(tax, rate) { - let found = (me.frm.doc.taxes || []).find(d => d.account_head === tax); - if (!found) { - let child = frappe.model.add_child(me.frm.doc, "taxes"); - child.charge_type = "On Net Total"; - child.account_head = tax; - child.rate = 0; - } - }); - } - }, - calculate_taxes: function() { var me = this; this.frm.doc.rounding_adjustment = 0; diff --git a/erpnext/public/js/controllers/transaction.js b/erpnext/public/js/controllers/transaction.js index a89776250f2..58d66690c3b 100644 --- a/erpnext/public/js/controllers/transaction.js +++ b/erpnext/public/js/controllers/transaction.js @@ -736,6 +736,26 @@ erpnext.TransactionController = erpnext.taxes_and_totals.extend({ }); }, + add_taxes_from_item_tax_template: function(item_tax_map) { + let me = this; + + if (item_tax_map && cint(frappe.defaults.get_default("add_taxes_from_item_tax_template"))) { + if (typeof (item_tax_map) == "string") { + item_tax_map = JSON.parse(item_tax_map); + } + + $.each(item_tax_map, function(tax, rate) { + let found = (me.frm.doc.taxes || []).find(d => d.account_head === tax); + if (!found) { + let child = frappe.model.add_child(me.frm.doc, "taxes"); + child.charge_type = "On Net Total"; + child.account_head = tax; + child.rate = 0; + } + }); + } + }, + serial_no: function(doc, cdt, cdn) { var me = this; var item = frappe.get_doc(cdt, cdn); @@ -1863,6 +1883,7 @@ erpnext.TransactionController = erpnext.taxes_and_totals.extend({ callback: function(r) { if(!r.exc) { item.item_tax_rate = r.message; + me.add_taxes_from_item_tax_template(item.item_tax_rate); me.calculate_taxes_and_totals(); } } From 37134b04d8b482302cdf15d46ec7e6849aa48649 Mon Sep 17 00:00:00 2001 From: marination Date: Mon, 21 Mar 2022 17:53:18 +0530 Subject: [PATCH 24/63] fix: Product Filters Lookup - bind the right classes to the filter lookup field - make class names more descriptive - make filter lookup field more visible with white bg and border - bind lookup input field js in `views.js` - make filter lookup field functioning for atribute filters too - added placeholder to lookup field (cherry picked from commit f6e64c2cacf097db4174e4a3e0d3728af8082b94) # Conflicts: # erpnext/templates/includes/macros.html --- erpnext/e_commerce/product_ui/views.js | 16 ++++++++++++++++ erpnext/public/scss/shopping_cart.scss | 9 +++++++++ erpnext/templates/generators/item_group.html | 18 ------------------ erpnext/templates/includes/macros.html | 15 ++++++++++----- erpnext/www/all-products/index.html | 18 ------------------ 5 files changed, 35 insertions(+), 41 deletions(-) diff --git a/erpnext/e_commerce/product_ui/views.js b/erpnext/e_commerce/product_ui/views.js index cc51718c47f..eab1699538e 100644 --- a/erpnext/e_commerce/product_ui/views.js +++ b/erpnext/e_commerce/product_ui/views.js @@ -424,6 +424,22 @@ erpnext.ProductView = class { me.change_route_with_filters(); }); + + // bind filter lookup input box + $('.filter-lookup-input').on('keydown', frappe.utils.debounce((e) => { + const $input = $(e.target); + const keyword = ($input.val() || '').toLowerCase(); + const $filter_options = $input.next('.filter-options'); + + $filter_options.find('.filter-lookup-wrapper').show(); + $filter_options.find('.filter-lookup-wrapper').each((i, el) => { + const $el = $(el); + const value = $el.data('value').toLowerCase(); + if (!value.includes(keyword)) { + $el.hide(); + } + }); + }, 300)); } change_route_with_filters() { diff --git a/erpnext/public/scss/shopping_cart.scss b/erpnext/public/scss/shopping_cart.scss index ff2482d3f64..e083729fad5 100644 --- a/erpnext/public/scss/shopping_cart.scss +++ b/erpnext/public/scss/shopping_cart.scss @@ -264,6 +264,15 @@ body.product-page { font-size: 13px; } + .filter-lookup-input { + background-color: white; + border: 1px solid var(--gray-300); + + &:focus { + border: 1px solid var(--primary); + } + } + .filter-label { font-size: 11px; font-weight: 600; diff --git a/erpnext/templates/generators/item_group.html b/erpnext/templates/generators/item_group.html index 218481581c5..3926f77b1fa 100644 --- a/erpnext/templates/generators/item_group.html +++ b/erpnext/templates/generators/item_group.html @@ -52,24 +52,6 @@ - diff --git a/erpnext/templates/includes/macros.html b/erpnext/templates/includes/macros.html index 892d62513e2..666b5579f7f 100644 --- a/erpnext/templates/includes/macros.html +++ b/erpnext/templates/includes/macros.html @@ -300,13 +300,13 @@ {% if values | len > 20 %} - + {% endif %} {% if values %}
{% for value in values %} -
+