From 333c62de72b1e47a15285b463ec6715cbf46bc40 Mon Sep 17 00:00:00 2001 From: Rohit Waghchaure Date: Mon, 6 Jun 2022 01:19:45 +0530 Subject: [PATCH 01/21] fix: transferred batches are not fetched while making Manufacture stock entry --- .../stock/doctype/stock_entry/stock_entry.py | 223 ++++++++++-------- 1 file changed, 120 insertions(+), 103 deletions(-) diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.py b/erpnext/stock/doctype/stock_entry/stock_entry.py index f1df54dd6a..293c2e54f5 100644 --- a/erpnext/stock/doctype/stock_entry/stock_entry.py +++ b/erpnext/stock/doctype/stock_entry/stock_entry.py @@ -1656,118 +1656,58 @@ class StockEntry(StockController): ) def get_transfered_raw_materials(self): - transferred_materials = frappe.db.sql( - """ - select - item_name, original_item, item_code, sum(qty) as qty, sed.t_warehouse as warehouse, - description, stock_uom, expense_account, cost_center - from `tabStock Entry` se,`tabStock Entry Detail` sed - where - se.name = sed.parent and se.docstatus=1 and se.purpose='Material Transfer for Manufacture' - and se.work_order= %s and ifnull(sed.t_warehouse, '') != '' - group by sed.item_code, sed.t_warehouse - """, + available_materials = get_available_materials(self.work_order) + + wo_data = frappe.db.get_value( + "Work Order", self.work_order, + ["qty", "produced_qty", "material_transferred_for_manufacturing as trans_qty"], as_dict=1, ) - materials_already_backflushed = frappe.db.sql( - """ - select - item_code, sed.s_warehouse as warehouse, sum(qty) as qty - from - `tabStock Entry` se, `tabStock Entry Detail` sed - where - se.name = sed.parent and se.docstatus=1 - and (se.purpose='Manufacture' or se.purpose='Material Consumption for Manufacture') - and se.work_order= %s and ifnull(sed.s_warehouse, '') != '' - group by sed.item_code, sed.s_warehouse - """, - self.work_order, - as_dict=1, - ) - - backflushed_materials = {} - for d in materials_already_backflushed: - backflushed_materials.setdefault(d.item_code, []).append({d.warehouse: d.qty}) - - po_qty = frappe.db.sql( - """select qty, produced_qty, material_transferred_for_manufacturing from - `tabWork Order` where name=%s""", - self.work_order, - as_dict=1, - )[0] - - manufacturing_qty = flt(po_qty.qty) or 1 - produced_qty = flt(po_qty.produced_qty) - trans_qty = flt(po_qty.material_transferred_for_manufacturing) or 1 - - for item in transferred_materials: - qty = item.qty - item_code = item.original_item or item.item_code - req_items = frappe.get_all( - "Work Order Item", - filters={"parent": self.work_order, "item_code": item_code}, - fields=["required_qty", "consumed_qty"], + for key, row in available_materials.items(): + qty = (flt(row.qty) * flt(self.fg_completed_qty)) / ( + flt(wo_data.trans_qty) - flt(wo_data.produced_qty) ) - req_qty = flt(req_items[0].required_qty) if req_items else flt(4) - req_qty_each = flt(req_qty / manufacturing_qty) - consumed_qty = flt(req_items[0].consumed_qty) if req_items else 0 - - if trans_qty and manufacturing_qty > (produced_qty + flt(self.fg_completed_qty)): - if qty >= req_qty: - qty = (req_qty / trans_qty) * flt(self.fg_completed_qty) - else: - qty = qty - consumed_qty - - if self.purpose == "Manufacture": - # If Material Consumption is booked, must pull only remaining components to finish product - if consumed_qty != 0: - remaining_qty = consumed_qty - (produced_qty * req_qty_each) - exhaust_qty = req_qty_each * produced_qty - if remaining_qty > exhaust_qty: - if (remaining_qty / (req_qty_each * flt(self.fg_completed_qty))) >= 1: - qty = 0 - else: - qty = (req_qty_each * flt(self.fg_completed_qty)) - remaining_qty - else: - if self.flags.backflush_based_on == "Material Transferred for Manufacture": - qty = (item.qty / trans_qty) * flt(self.fg_completed_qty) - else: - qty = req_qty_each * flt(self.fg_completed_qty) - - elif backflushed_materials.get(item.item_code): - precision = frappe.get_precision("Stock Entry Detail", "qty") - for d in backflushed_materials.get(item.item_code): - if d.get(item.warehouse) > 0: - if qty > req_qty: - qty = ( - (flt(qty, precision) - flt(d.get(item.warehouse), precision)) - / (flt(trans_qty, precision) - flt(produced_qty, precision)) - ) * flt(self.fg_completed_qty) - - d[item.warehouse] -= qty - + item = row.item_details if cint(frappe.get_cached_value("UOM", item.stock_uom, "must_be_whole_number")): qty = frappe.utils.ceil(qty) - if qty > 0: - self.add_to_stock_entry_detail( - { - item.item_code: { - "from_warehouse": item.warehouse, - "to_warehouse": "", - "qty": qty, - "item_name": item.item_name, - "description": item.description, - "stock_uom": item.stock_uom, - "expense_account": item.expense_account, - "cost_center": item.buying_cost_center, - "original_item": item.original_item, - } - } - ) + if row.batch_details: + for batch_no, batch_qty in row.batch_details.items(): + if qty <= 0: + continue + + if batch_qty > qty: + batch_qty = qty + + item.batch_no = batch_no + self.update_item_in_stock_entry_detail(row, item, batch_qty) + + row.batch_details[batch_no] -= batch_qty + qty -= batch_qty + else: + self.update_item_in_stock_entry_detail(row, item, qty) + + def update_item_in_stock_entry_detail(self, row, item, qty): + ste_item_details = { + "from_warehouse": item.warehouse, + "to_warehouse": "", + "qty": qty, + "item_name": item.item_name, + "batch_no": item.batch_no, + "description": item.description, + "stock_uom": item.stock_uom, + "expense_account": item.expense_account, + "cost_center": item.buying_cost_center, + "original_item": item.original_item, + } + + if item.serial_no: + ste_item_details["serial_no"] = "\n".join(item.serial_no[0 : cint(qty)]) + + self.add_to_stock_entry_detail({item.item_code: ste_item_details}) def get_pending_raw_materials(self, backflush_based_on=None): """ @@ -2521,3 +2461,80 @@ def get_supplied_items(purchase_order): ) return supplied_item_details + + +def get_available_materials(work_order) -> dict: + data = get_stock_entry_data(work_order) + + available_materials = {} + for row in data: + key = (row.item_code, row.warehouse) + if row.purpose != "Material Transfer for Manufacture": + key = (row.item_code, row.s_warehouse) + + if key not in available_materials: + available_materials.setdefault( + key, + frappe._dict( + {"item_details": row, "batch_details": defaultdict(float), "qty": 0, "serial_nos": []} + ), + ) + + item_data = available_materials[key] + + if row.purpose == "Material Transfer for Manufacture": + item_data.qty += row.qty + if row.batch_no: + item_data.batch_details[row.batch_no] += row.qty + + if row.serial_no: + item_data.serial_nos.extend(get_serial_nos(row.serial_no)) + else: + # Consume raw material qty in case of 'Manufacture' or 'Material Consumption for Manufacture' + + item_data.qty -= row.qty + if row.batch_no: + item_data.batch_details[row.batch_no] -= row.qty + + if row.serial_no: + for serial_no in get_serial_nos(row.serial_no): + item_data.serial_nos.remove(serial_no) + + return available_materials + + +def get_stock_entry_data(work_order): + stock_entry = frappe.qb.DocType("Stock Entry") + stock_entry_detail = frappe.qb.DocType("Stock Entry Detail") + + return ( + frappe.qb.from_(stock_entry) + .from_(stock_entry_detail) + .select( + stock_entry_detail.item_name, + stock_entry_detail.original_item, + stock_entry_detail.item_code, + stock_entry_detail.qty, + (stock_entry_detail.t_warehouse).as_("warehouse"), + (stock_entry_detail.s_warehouse).as_("s_warehouse"), + stock_entry_detail.description, + stock_entry_detail.stock_uom, + stock_entry_detail.expense_account, + stock_entry_detail.cost_center, + stock_entry_detail.batch_no, + stock_entry_detail.serial_no, + stock_entry.purpose, + ) + .where( + (stock_entry.name == stock_entry_detail.parent) + & (stock_entry.work_order == work_order) + & (stock_entry.docstatus == 1) + & (stock_entry_detail.s_warehouse.isnotnull()) + & ( + stock_entry.purpose.isin( + ["Manufacture", "Material Consumption for Manufacture", "Material Transfer for Manufacture"] + ) + ) + ) + .orderby(stock_entry.creation, stock_entry_detail.item_code, stock_entry_detail.idx) + ).run(as_dict=1, debug=1) From d94ff3ede8ca1d57b1ad869a31bbc6bf93fa8a72 Mon Sep 17 00:00:00 2001 From: Rohit Waghchaure Date: Mon, 6 Jun 2022 16:07:17 +0530 Subject: [PATCH 02/21] test: test cases to cover batch, serialized raw materials --- .../doctype/work_order/test_work_order.py | 277 +++++++++++++++++- .../stock/doctype/stock_entry/stock_entry.py | 56 ++-- 2 files changed, 303 insertions(+), 30 deletions(-) diff --git a/erpnext/manufacturing/doctype/work_order/test_work_order.py b/erpnext/manufacturing/doctype/work_order/test_work_order.py index 2aba48231b..bd19dec504 100644 --- a/erpnext/manufacturing/doctype/work_order/test_work_order.py +++ b/erpnext/manufacturing/doctype/work_order/test_work_order.py @@ -1,6 +1,8 @@ # Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt +import copy + import frappe from frappe.tests.utils import FrappeTestCase, change_settings, timeout from frappe.utils import add_days, add_months, cint, flt, now, today @@ -19,6 +21,7 @@ from erpnext.manufacturing.doctype.work_order.work_order import ( ) from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order from erpnext.stock.doctype.item.test_item import create_item, make_item +from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos from erpnext.stock.doctype.stock_entry import test_stock_entry from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse from erpnext.stock.utils import get_bin @@ -28,6 +31,7 @@ class TestWorkOrder(FrappeTestCase): def setUp(self): self.warehouse = "_Test Warehouse 2 - _TC" self.item = "_Test Item" + prepare_data_for_backflush_based_on_materials_transferred() def tearDown(self): frappe.db.rollback() @@ -518,6 +522,8 @@ class TestWorkOrder(FrappeTestCase): work_order.cancel() def test_work_order_with_non_transfer_item(self): + frappe.db.set_value("Manufacturing Settings", None, "backflush_raw_materials_based_on", "BOM") + items = {"Finished Good Transfer Item": 1, "_Test FG Item": 1, "_Test FG Item 1": 0} for item, allow_transfer in items.items(): make_item(item, {"include_item_in_manufacturing": allow_transfer}) @@ -1062,7 +1068,7 @@ class TestWorkOrder(FrappeTestCase): sm = frappe.get_doc(make_stock_entry(wo_order.name, "Material Transfer for Manufacture", 100)) for row in sm.get("items"): if row.get("item_code") == "_Test Item": - row.qty = 110 + row.qty = 120 sm.submit() cancel_stock_entry.append(sm.name) @@ -1070,21 +1076,21 @@ class TestWorkOrder(FrappeTestCase): s = frappe.get_doc(make_stock_entry(wo_order.name, "Manufacture", 90)) for row in s.get("items"): if row.get("item_code") == "_Test Item": - self.assertEqual(row.get("qty"), 100) + self.assertEqual(row.get("qty"), 108) s.submit() cancel_stock_entry.append(s.name) s1 = frappe.get_doc(make_stock_entry(wo_order.name, "Manufacture", 5)) for row in s1.get("items"): if row.get("item_code") == "_Test Item": - self.assertEqual(row.get("qty"), 5) + self.assertEqual(row.get("qty"), 6) s1.submit() cancel_stock_entry.append(s1.name) s2 = frappe.get_doc(make_stock_entry(wo_order.name, "Manufacture", 5)) for row in s2.get("items"): if row.get("item_code") == "_Test Item": - self.assertEqual(row.get("qty"), 5) + self.assertEqual(row.get("qty"), 6) cancel_stock_entry.reverse() for ste in cancel_stock_entry: @@ -1194,6 +1200,269 @@ class TestWorkOrder(FrappeTestCase): self.assertEqual(work_order.required_items[0].transferred_qty, 1) self.assertEqual(work_order.required_items[1].transferred_qty, 2) + def test_backflushed_batch_raw_materials_based_on_transferred(self): + frappe.db.set_value( + "Manufacturing Settings", + None, + "backflush_raw_materials_based_on", + "Material Transferred for Manufacture", + ) + + batch_item = "Test Batch MCC Keyboard" + fg_item = "Test FG Item with Batch Raw Materials" + + ste_doc = test_stock_entry.make_stock_entry( + item_code=batch_item, target="Stores - _TC", qty=2, basic_rate=100, do_not_save=True + ) + + ste_doc.append( + "items", + { + "item_code": batch_item, + "item_name": batch_item, + "description": batch_item, + "basic_rate": 100, + "t_warehouse": "Stores - _TC", + "qty": 2, + "uom": "Nos", + "stock_uom": "Nos", + "conversion_factor": 1, + }, + ) + + # Inward raw materials in Stores warehouse + ste_doc.insert() + ste_doc.submit() + + batch_list = [row.batch_no for row in ste_doc.items] + + wo_doc = make_wo_order_test_record(production_item=fg_item, qty=4) + transferred_ste_doc = frappe.get_doc( + make_stock_entry(wo_doc.name, "Material Transfer for Manufacture", 4) + ) + + transferred_ste_doc.items[0].qty = 2 + transferred_ste_doc.items[0].batch_no = batch_list[0] + + new_row = copy.deepcopy(transferred_ste_doc.items[0]) + new_row.name = "" + new_row.batch_no = batch_list[1] + + # Transferred two batches from Stores to WIP Warehouse + transferred_ste_doc.append("items", new_row) + transferred_ste_doc.submit() + + # First Manufacture stock entry + manufacture_ste_doc1 = frappe.get_doc(make_stock_entry(wo_doc.name, "Manufacture", 1)) + + # Batch no should be same as transferred Batch no + self.assertEqual(manufacture_ste_doc1.items[0].batch_no, batch_list[0]) + self.assertEqual(manufacture_ste_doc1.items[0].qty, 1) + + manufacture_ste_doc1.submit() + + # Second Manufacture stock entry + manufacture_ste_doc2 = frappe.get_doc(make_stock_entry(wo_doc.name, "Manufacture", 2)) + + # Batch no should be same as transferred Batch no + self.assertEqual(manufacture_ste_doc2.items[0].batch_no, batch_list[0]) + self.assertEqual(manufacture_ste_doc2.items[0].qty, 1) + self.assertEqual(manufacture_ste_doc2.items[1].batch_no, batch_list[1]) + self.assertEqual(manufacture_ste_doc2.items[1].qty, 1) + + def test_backflushed_serial_no_raw_materials_based_on_transferred(self): + frappe.db.set_value( + "Manufacturing Settings", + None, + "backflush_raw_materials_based_on", + "Material Transferred for Manufacture", + ) + + sn_item = "Test Serial No BTT Headphone" + fg_item = "Test FG Item with Serial No Raw Materials" + + ste_doc = test_stock_entry.make_stock_entry( + item_code=sn_item, target="Stores - _TC", qty=4, basic_rate=100, do_not_save=True + ) + + # Inward raw materials in Stores warehouse + ste_doc.submit() + + serial_nos_list = sorted(get_serial_nos(ste_doc.items[0].serial_no)) + + wo_doc = make_wo_order_test_record(production_item=fg_item, qty=4) + transferred_ste_doc = frappe.get_doc( + make_stock_entry(wo_doc.name, "Material Transfer for Manufacture", 4) + ) + + transferred_ste_doc.items[0].serial_no = "\n".join(serial_nos_list) + transferred_ste_doc.submit() + + # First Manufacture stock entry + manufacture_ste_doc1 = frappe.get_doc(make_stock_entry(wo_doc.name, "Manufacture", 1)) + + # Serial nos should be same as transferred Serial nos + self.assertEqual(get_serial_nos(manufacture_ste_doc1.items[0].serial_no), serial_nos_list[0:1]) + self.assertEqual(manufacture_ste_doc1.items[0].qty, 1) + + manufacture_ste_doc1.submit() + + # Second Manufacture stock entry + manufacture_ste_doc2 = frappe.get_doc(make_stock_entry(wo_doc.name, "Manufacture", 2)) + + # Serial nos should be same as transferred Serial nos + self.assertEqual(get_serial_nos(manufacture_ste_doc2.items[0].serial_no), serial_nos_list[1:3]) + self.assertEqual(manufacture_ste_doc2.items[0].qty, 2) + + def test_backflushed_serial_no_batch_raw_materials_based_on_transferred(self): + frappe.db.set_value( + "Manufacturing Settings", + None, + "backflush_raw_materials_based_on", + "Material Transferred for Manufacture", + ) + + sn_batch_item = "Test Batch Serial No WebCam" + fg_item = "Test FG Item with Serial & Batch No Raw Materials" + + ste_doc = test_stock_entry.make_stock_entry( + item_code=sn_batch_item, target="Stores - _TC", qty=2, basic_rate=100, do_not_save=True + ) + + ste_doc.append( + "items", + { + "item_code": sn_batch_item, + "item_name": sn_batch_item, + "description": sn_batch_item, + "basic_rate": 100, + "t_warehouse": "Stores - _TC", + "qty": 2, + "uom": "Nos", + "stock_uom": "Nos", + "conversion_factor": 1, + }, + ) + + # Inward raw materials in Stores warehouse + ste_doc.insert() + ste_doc.submit() + + batch_dict = {row.batch_no: get_serial_nos(row.serial_no) for row in ste_doc.items} + batches = list(batch_dict.keys()) + + wo_doc = make_wo_order_test_record(production_item=fg_item, qty=4) + transferred_ste_doc = frappe.get_doc( + make_stock_entry(wo_doc.name, "Material Transfer for Manufacture", 4) + ) + + transferred_ste_doc.items[0].qty = 2 + transferred_ste_doc.items[0].batch_no = batches[0] + transferred_ste_doc.items[0].serial_no = "\n".join(batch_dict.get(batches[0])) + + new_row = copy.deepcopy(transferred_ste_doc.items[0]) + new_row.name = "" + new_row.batch_no = batches[1] + new_row.serial_no = "\n".join(batch_dict.get(batches[1])) + + # Transferred two batches from Stores to WIP Warehouse + transferred_ste_doc.append("items", new_row) + transferred_ste_doc.submit() + + # First Manufacture stock entry + manufacture_ste_doc1 = frappe.get_doc(make_stock_entry(wo_doc.name, "Manufacture", 1)) + + # Batch no & Serial Nos should be same as transferred Batch no & Serial Nos + batch_no = manufacture_ste_doc1.items[0].batch_no + self.assertEqual( + get_serial_nos(manufacture_ste_doc1.items[0].serial_no)[0], batch_dict.get(batch_no)[0] + ) + self.assertEqual(manufacture_ste_doc1.items[0].qty, 1) + + manufacture_ste_doc1.submit() + + # Second Manufacture stock entry + manufacture_ste_doc2 = frappe.get_doc(make_stock_entry(wo_doc.name, "Manufacture", 2)) + + # Batch no & Serial Nos should be same as transferred Batch no & Serial Nos + batch_no = manufacture_ste_doc2.items[0].batch_no + self.assertEqual( + get_serial_nos(manufacture_ste_doc2.items[0].serial_no)[0], batch_dict.get(batch_no)[1] + ) + self.assertEqual(manufacture_ste_doc2.items[0].qty, 1) + + batch_no = manufacture_ste_doc2.items[1].batch_no + self.assertEqual( + get_serial_nos(manufacture_ste_doc2.items[1].serial_no)[0], batch_dict.get(batch_no)[0] + ) + self.assertEqual(manufacture_ste_doc2.items[1].qty, 1) + + +def prepare_data_for_backflush_based_on_materials_transferred(): + batch_item_doc = make_item( + "Test Batch MCC Keyboard", + { + "is_stock_item": 1, + "has_batch_no": 1, + "create_new_batch": 1, + "batch_number_series": "TBMK.#####", + "valuation_rate": 100, + "stock_uom": "Nos", + }, + ) + + item = make_item( + "Test FG Item with Batch Raw Materials", + { + "is_stock_item": 1, + }, + ) + + make_bom(item=item.name, source_warehouse="Stores - _TC", raw_materials=[batch_item_doc.name]) + + sn_item_doc = make_item( + "Test Serial No BTT Headphone", + { + "is_stock_item": 1, + "has_serial_no": 1, + "serial_no_series": "TSBH.#####", + "valuation_rate": 100, + "stock_uom": "Nos", + }, + ) + + item = make_item( + "Test FG Item with Serial No Raw Materials", + { + "is_stock_item": 1, + }, + ) + + make_bom(item=item.name, source_warehouse="Stores - _TC", raw_materials=[sn_item_doc.name]) + + sn_batch_item_doc = make_item( + "Test Batch Serial No WebCam", + { + "is_stock_item": 1, + "has_batch_no": 1, + "create_new_batch": 1, + "batch_number_series": "TBSW.#####", + "has_serial_no": 1, + "serial_no_series": "TBSWC.#####", + "valuation_rate": 100, + "stock_uom": "Nos", + }, + ) + + item = make_item( + "Test FG Item with Serial & Batch No Raw Materials", + { + "is_stock_item": 1, + }, + ) + + make_bom(item=item.name, source_warehouse="Stores - _TC", raw_materials=[sn_batch_item_doc.name]) + def update_job_card(job_card, jc_qty=None): employee = frappe.db.get_value("Employee", {"status": "Active"}, "name") diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.py b/erpnext/stock/doctype/stock_entry/stock_entry.py index 293c2e54f5..08ce83b707 100644 --- a/erpnext/stock/doctype/stock_entry/stock_entry.py +++ b/erpnext/stock/doctype/stock_entry/stock_entry.py @@ -596,21 +596,6 @@ class StockEntry(StockController): title=_("Insufficient Stock"), ) - def set_serial_nos(self, work_order): - previous_se = frappe.db.get_value( - "Stock Entry", - {"work_order": work_order, "purpose": "Material Transfer for Manufacture"}, - "name", - ) - - for d in self.get("items"): - transferred_serial_no = frappe.db.get_value( - "Stock Entry Detail", {"parent": previous_se, "item_code": d.item_code}, "serial_no" - ) - - if transferred_serial_no: - d.serial_no = transferred_serial_no - @frappe.whitelist() def get_stock_and_rate(self): """ @@ -1321,7 +1306,7 @@ class StockEntry(StockController): and not self.pro_doc.skip_transfer and self.flags.backflush_based_on == "Material Transferred for Manufacture" ): - self.get_transfered_raw_materials() + self.add_transfered_raw_materials_in_items() elif ( self.work_order @@ -1365,7 +1350,6 @@ class StockEntry(StockController): # fetch the serial_no of the first stock entry for the second stock entry if self.work_order and self.purpose == "Manufacture": - self.set_serial_nos(self.work_order) work_order = frappe.get_doc("Work Order", self.work_order) add_additional_cost(self, work_order) @@ -1655,7 +1639,7 @@ class StockEntry(StockController): } ) - def get_transfered_raw_materials(self): + def add_transfered_raw_materials_in_items(self) -> None: available_materials = get_available_materials(self.work_order) wo_data = frappe.db.get_value( @@ -1666,9 +1650,11 @@ class StockEntry(StockController): ) for key, row in available_materials.items(): - qty = (flt(row.qty) * flt(self.fg_completed_qty)) / ( - flt(wo_data.trans_qty) - flt(wo_data.produced_qty) - ) + remaining_qty_to_produce = flt(wo_data.trans_qty) - flt(wo_data.produced_qty) + if remaining_qty_to_produce <= 0: + continue + + qty = (flt(row.qty) * flt(self.fg_completed_qty)) / remaining_qty_to_produce item = row.item_details if cint(frappe.get_cached_value("UOM", item.stock_uom, "must_be_whole_number")): @@ -1676,7 +1662,7 @@ class StockEntry(StockController): if row.batch_details: for batch_no, batch_qty in row.batch_details.items(): - if qty <= 0: + if qty <= 0 or batch_qty <= 0: continue if batch_qty > qty: @@ -1690,7 +1676,7 @@ class StockEntry(StockController): else: self.update_item_in_stock_entry_detail(row, item, qty) - def update_item_in_stock_entry_detail(self, row, item, qty): + def update_item_in_stock_entry_detail(self, row, item, qty) -> None: ste_item_details = { "from_warehouse": item.warehouse, "to_warehouse": "", @@ -1704,11 +1690,28 @@ class StockEntry(StockController): "original_item": item.original_item, } - if item.serial_no: - ste_item_details["serial_no"] = "\n".join(item.serial_no[0 : cint(qty)]) + if row.serial_nos: + serial_nos = row.serial_nos + if item.batch_no: + serial_nos = self.get_serial_nos_based_on_transferred_batch(item.batch_no, row.serial_nos) + + serial_nos = serial_nos[0 : cint(qty)] + ste_item_details["serial_no"] = "\n".join(serial_nos) + + # remove consumed serial nos from list + for sn in serial_nos: + row.serial_nos.remove(sn) self.add_to_stock_entry_detail({item.item_code: ste_item_details}) + @staticmethod + def get_serial_nos_based_on_transferred_batch(batch_no, serial_nos) -> list: + serial_nos = frappe.get_all( + "Serial No", filters={"batch_no": batch_no, "name": ("in", serial_nos)}, order_by="creation" + ) + + return [d.name for d in serial_nos] + def get_pending_raw_materials(self, backflush_based_on=None): """ issue (item quantity) that is pending to issue or desire to transfer, @@ -2489,6 +2492,7 @@ def get_available_materials(work_order) -> dict: if row.serial_no: item_data.serial_nos.extend(get_serial_nos(row.serial_no)) + item_data.serial_nos.sort() else: # Consume raw material qty in case of 'Manufacture' or 'Material Consumption for Manufacture' @@ -2537,4 +2541,4 @@ def get_stock_entry_data(work_order): ) ) .orderby(stock_entry.creation, stock_entry_detail.item_code, stock_entry_detail.idx) - ).run(as_dict=1, debug=1) + ).run(as_dict=1) From 65b21ee7d61e5bb9744b5545d625140897afd35c Mon Sep 17 00:00:00 2001 From: Ankush Menat Date: Tue, 7 Jun 2022 14:49:24 +0530 Subject: [PATCH 03/21] fix: internal transfer GLE validation --- erpnext/controllers/stock_controller.py | 2 +- .../selling/doctype/customer/test_customer.py | 6 +++++ .../delivery_note/test_delivery_note.py | 27 +++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/erpnext/controllers/stock_controller.py b/erpnext/controllers/stock_controller.py index feec42f43a..e90a4f6241 100644 --- a/erpnext/controllers/stock_controller.py +++ b/erpnext/controllers/stock_controller.py @@ -166,7 +166,7 @@ class StockController(AccountsController): "against": warehouse_account[sle.warehouse]["account"], "cost_center": item_row.cost_center, "remarks": self.get("remarks") or _("Accounting Entry for Stock"), - "credit": flt(sle.stock_value_difference, precision), + "debit": -1 * flt(sle.stock_value_difference, precision), "project": item_row.get("project") or self.get("project"), "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No", }, diff --git a/erpnext/selling/doctype/customer/test_customer.py b/erpnext/selling/doctype/customer/test_customer.py index 24587564cf..7dc3fab623 100644 --- a/erpnext/selling/doctype/customer/test_customer.py +++ b/erpnext/selling/doctype/customer/test_customer.py @@ -375,6 +375,12 @@ def create_internal_customer( if not allowed_to_interact_with: allowed_to_interact_with = represents_company + exisiting_representative = frappe.db.get_value( + "Customer", {"represents_company": represents_company} + ) + if exisiting_representative: + return exisiting_representative + if not frappe.db.exists("Customer", customer_name): customer = frappe.get_doc( { diff --git a/erpnext/stock/doctype/delivery_note/test_delivery_note.py b/erpnext/stock/doctype/delivery_note/test_delivery_note.py index fffcdca380..6bcab737b3 100644 --- a/erpnext/stock/doctype/delivery_note/test_delivery_note.py +++ b/erpnext/stock/doctype/delivery_note/test_delivery_note.py @@ -1064,6 +1064,33 @@ class TestDeliveryNote(FrappeTestCase): self.assertEqual(dn.items[0].rate, rate) + def test_internal_transfer_precision_gle(self): + from erpnext.selling.doctype.customer.test_customer import create_internal_customer + + item = make_item(properties={"valuation_method": "Moving Average"}).name + company = "_Test Company with perpetual inventory" + warehouse = "Stores - TCP1" + target = "Finished Goods - TCP1" + customer = create_internal_customer(represents_company=company) + + # average rate = 128.015 + rates = [101.45, 150.46, 138.25, 121.9] + + for rate in rates: + make_stock_entry(item_code=item, target=warehouse, qty=1, rate=rate) + + dn = create_delivery_note( + item_code=item, + company=company, + customer=customer, + qty=4, + warehouse=warehouse, + target_warehouse=target, + ) + self.assertFalse( + frappe.db.exists("GL Entry", {"voucher_no": dn.name, "voucher_type": dn.doctype}) + ) + def create_delivery_note(**args): dn = frappe.new_doc("Delivery Note") From d05d15346a22de311cf16f437e80804207b4fe60 Mon Sep 17 00:00:00 2001 From: Deepesh Garg Date: Tue, 14 Jun 2022 12:50:49 +0530 Subject: [PATCH 04/21] fix: Conversion rate validation for multi-currency invoices --- .../doctype/purchase_invoice/purchase_invoice.py | 11 ----------- .../accounts/doctype/sales_invoice/sales_invoice.py | 1 + erpnext/controllers/accounts_controller.py | 11 +++++++++++ 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py index 23ad223e77..4e0d1c966d 100644 --- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py +++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py @@ -165,17 +165,6 @@ class PurchaseInvoice(BuyingController): super(PurchaseInvoice, self).set_missing_values(for_validate) - def check_conversion_rate(self): - default_currency = erpnext.get_company_currency(self.company) - if not default_currency: - throw(_("Please enter default currency in Company Master")) - if ( - (self.currency == default_currency and flt(self.conversion_rate) != 1.00) - or not self.conversion_rate - or (self.currency != default_currency and flt(self.conversion_rate) == 1.00) - ): - throw(_("Conversion rate cannot be 0 or 1")) - def validate_credit_to_acc(self): if not self.credit_to: self.credit_to = get_party_account("Supplier", self.supplier, self.company) diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py index a580d45acc..1a3164b0d9 100644 --- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py +++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py @@ -114,6 +114,7 @@ class SalesInvoice(SellingController): self.set_income_account_for_fixed_assets() self.validate_item_cost_centers() self.validate_income_account() + self.check_conversion_rate() validate_inter_company_party( self.doctype, self.customer, self.company, self.inter_company_invoice_reference diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py index 854c0d00f5..389d7cc983 100644 --- a/erpnext/controllers/accounts_controller.py +++ b/erpnext/controllers/accounts_controller.py @@ -1838,6 +1838,17 @@ class AccountsController(TransactionBase): jv.save() jv.submit() + def check_conversion_rate(self): + default_currency = erpnext.get_company_currency(self.company) + if not default_currency: + throw(_("Please enter default currency in Company Master")) + if ( + (self.currency == default_currency and flt(self.conversion_rate) != 1.00) + or not self.conversion_rate + or (self.currency != default_currency and flt(self.conversion_rate) == 1.00) + ): + throw(_("Conversion rate cannot be 0 or 1")) + @frappe.whitelist() def get_tax_rate(account_head): From 0097a2b60c9b0fbdc69a5f460a5edee5f8354578 Mon Sep 17 00:00:00 2001 From: "Nihantra C. Patel" <99652762+nihantra@users.noreply.github.com> Date: Fri, 17 Jun 2022 18:35:11 +0530 Subject: [PATCH 05/21] Update bank_clearance_summary.py --- .../report/bank_clearance_summary/bank_clearance_summary.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py b/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py index 20f7643a1c..9d2deea523 100644 --- a/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py +++ b/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py @@ -43,7 +43,7 @@ def get_columns(): "options": "Account", "width": 170, }, - {"label": _("Amount"), "fieldname": "amount", "width": 120}, + {"label": _("Amount"), "fieldname": "amount", "fieldtype": "Currency", "width": 120}, ] return columns From 0320b59ea615b372c9d627db54d272607b104878 Mon Sep 17 00:00:00 2001 From: marination Date: Mon, 20 Jun 2022 16:25:34 +0530 Subject: [PATCH 06/21] chore: Clear Progress section for completed logs & `on_submit` UX - Delete `BOM Update Batch` table on 'Completed' log, to save space - Hide Progress section on 'Completed' log - Enqueue `on_submit` for 'Update Cost' job, getting leaf boms could take time for huge DBs. Users have to wait for screen to unfreeze. - Add error handling to `process_boms_cost_level_wise` (Called via cron job and on submit, both in background) --- .../bom_update_log/bom_update_log.json | 10 ++-- .../doctype/bom_update_log/bom_update_log.py | 59 +++++++++++-------- 2 files changed, 42 insertions(+), 27 deletions(-) diff --git a/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.json b/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.json index c32e383b08..a926e69ee6 100644 --- a/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.json +++ b/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.json @@ -7,11 +7,11 @@ "editable_grid": 1, "engine": "InnoDB", "field_order": [ - "current_bom", - "new_bom", - "column_break_3", "update_type", "status", + "column_break_3", + "current_bom", + "new_bom", "error_log", "progress_section", "current_level", @@ -37,6 +37,7 @@ "options": "BOM" }, { + "depends_on": "eval:doc.update_type === \"Replace BOM\"", "fieldname": "column_break_3", "fieldtype": "Column Break" }, @@ -87,6 +88,7 @@ "options": "BOM Update Batch" }, { + "depends_on": "eval:doc.status !== \"Completed\"", "fieldname": "current_level", "fieldtype": "Int", "label": "Current Level" @@ -96,7 +98,7 @@ "index_web_pages_for_search": 1, "is_submittable": 1, "links": [], - "modified": "2022-06-06 15:15:23.883251", + "modified": "2022-06-20 15:43:55.696388", "modified_by": "Administrator", "module": "Manufacturing", "name": "BOM Update Log", diff --git a/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.py b/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.py index 9c9c24044a..af5ff8e1c2 100644 --- a/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.py +++ b/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.py @@ -77,7 +77,11 @@ class BOMUpdateLog(Document): now=frappe.flags.in_test, ) else: - process_boms_cost_level_wise(self) + frappe.enqueue( + method="erpnext.manufacturing.doctype.bom_update_log.bom_update_log.process_boms_cost_level_wise", + update_doc=self, + now=frappe.flags.in_test, + ) def run_replace_bom_job( @@ -112,28 +116,31 @@ def process_boms_cost_level_wise( current_boms = {} values = {} - if update_doc.status == "Queued": - # First level yet to process. On Submit. - current_level = 0 - current_boms = get_leaf_boms() - values = { - "processed_boms": json.dumps({}), - "status": "In Progress", - "current_level": current_level, - } - else: - # Resume next level. via Cron Job. - if not parent_boms: - return + try: + if update_doc.status == "Queued": + # First level yet to process. On Submit. + current_level = 0 + current_boms = get_leaf_boms() + values = { + "processed_boms": json.dumps({}), + "status": "In Progress", + "current_level": current_level, + } + else: + # Resume next level. via Cron Job. + if not parent_boms: + return - current_level = cint(update_doc.current_level) + 1 + current_level = cint(update_doc.current_level) + 1 - # Process the next level BOMs. Stage parents as current BOMs. - current_boms = parent_boms.copy() - values = {"current_level": current_level} + # Process the next level BOMs. Stage parents as current BOMs. + current_boms = parent_boms.copy() + values = {"current_level": current_level} - set_values_in_log(update_doc.name, values, commit=True) - queue_bom_cost_jobs(current_boms, update_doc, current_level) + set_values_in_log(update_doc.name, values, commit=True) + queue_bom_cost_jobs(current_boms, update_doc, current_level) + except Exception: + handle_exception(update_doc) def queue_bom_cost_jobs( @@ -199,16 +206,22 @@ def resume_bom_cost_update_jobs(): current_boms, processed_boms = get_processed_current_boms(log, bom_batches) parent_boms = get_next_higher_level_boms(child_boms=current_boms, processed_boms=processed_boms) - # Unset processed BOMs if log is complete, it is used for next level BOMs + # Unset processed BOMs (it is used for next level BOMs) & change status if log is complete + status = "Completed" if not parent_boms else "In Progress" + processed_boms = json.dumps([] if not parent_boms else processed_boms) set_values_in_log( log.name, values={ - "processed_boms": json.dumps([] if not parent_boms else processed_boms), - "status": "Completed" if not parent_boms else "In Progress", + "processed_boms": processed_boms, + "status": status, }, commit=True, ) + # clear progress section + if status == "Completed": + frappe.db.delete("BOM Update Batch", {"parent": log.name}) + if parent_boms: # there is a next level to process process_boms_cost_level_wise( update_doc=frappe.get_doc("BOM Update Log", log.name), parent_boms=parent_boms From 8f373930448af79e7222eb78eb7d8c364a4b7fd0 Mon Sep 17 00:00:00 2001 From: Deepesh Garg Date: Mon, 20 Jun 2022 22:00:32 +0530 Subject: [PATCH 07/21] test: Add test case --- .../doctype/sales_invoice/test_sales_invoice.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py index b8154dd1f9..1b20c29f94 100644 --- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py +++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py @@ -1583,6 +1583,17 @@ class TestSalesInvoice(unittest.TestCase): self.assertTrue(gle) + def test_invoice_exchange_rate(self): + si = create_sales_invoice( + customer="_Test Customer USD", + debit_to="_Test Receivable USD - _TC", + currency="USD", + conversion_rate=1, + do_not_save=1, + ) + + self.assertRaises(frappe.ValidationError, si.save) + def test_invalid_currency(self): # Customer currency = USD From 4cf2225a29c0d1c1a1967de20c78b411f055bf53 Mon Sep 17 00:00:00 2001 From: marination Date: Tue, 21 Jun 2022 14:03:05 +0530 Subject: [PATCH 08/21] chore: Implement Log clearing interface in BOM Update Log - Implement Log clearing interface in BOM Update Log - Add additional info in sidebar: Log clearing only happens for 'Update Cost' type logs - 'Replace BOM' logs have important info and is used in BOM timeline, so we'll let users decide if they wanna keep or discard it --- .../doctype/bom_update_log/bom_update_log.py | 13 ++++++++++++ .../bom_update_log/bom_update_log_list.js | 21 +++++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.py b/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.py index af5ff8e1c2..c3f52d4583 100644 --- a/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.py +++ b/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.py @@ -6,6 +6,8 @@ from typing import Any, Dict, List, Optional, Tuple, Union import frappe from frappe import _ from frappe.model.document import Document +from frappe.query_builder import DocType, Interval +from frappe.query_builder.functions import Now from frappe.utils import cint, cstr from erpnext.manufacturing.doctype.bom_update_log.bom_updation_utils import ( @@ -22,6 +24,17 @@ class BOMMissingError(frappe.ValidationError): class BOMUpdateLog(Document): + @staticmethod + def clear_old_logs(days=None): + days = days or 90 + table = DocType("BOM Update Log") + frappe.db.delete( + table, + filters=( + (table.modified < (Now() - Interval(days=days))) & (table.update_type == "Update Cost") + ), + ) + def validate(self): if self.update_type == "Replace BOM": self.validate_boms_are_specified() diff --git a/erpnext/manufacturing/doctype/bom_update_log/bom_update_log_list.js b/erpnext/manufacturing/doctype/bom_update_log/bom_update_log_list.js index e39b5637c7..bc709d8fc4 100644 --- a/erpnext/manufacturing/doctype/bom_update_log/bom_update_log_list.js +++ b/erpnext/manufacturing/doctype/bom_update_log/bom_update_log_list.js @@ -1,6 +1,6 @@ frappe.listview_settings['BOM Update Log'] = { add_fields: ["status"], - get_indicator: function(doc) { + get_indicator: (doc) => { let status_map = { "Queued": "orange", "In Progress": "blue", @@ -9,5 +9,22 @@ frappe.listview_settings['BOM Update Log'] = { }; return [__(doc.status), status_map[doc.status], "status,=," + doc.status]; - } + }, + onload: () => { + if (!frappe.model.can_write("Log Settings")) { + return; + } + + let sidebar_entry = $( + '' + ).appendTo(cur_list.page.sidebar); + let message = __("Note: Automatic log deletion only applies to logs of type Update Cost"); + $(`
${message}
`).appendTo(sidebar_entry); + + frappe.require("logtypes.bundle.js", () => { + frappe.utils.logtypes.show_log_retention_message(cur_list.doctype); + }); + + + }, }; \ No newline at end of file From dc2830da4d35045377425a8e84fd8a19eb48134f Mon Sep 17 00:00:00 2001 From: s-aga-r Date: Tue, 21 Jun 2022 13:58:00 +0530 Subject: [PATCH 09/21] fix: set default_bom for item --- erpnext/manufacturing/doctype/bom/bom.py | 1 + erpnext/manufacturing/doctype/bom/test_bom.py | 36 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/erpnext/manufacturing/doctype/bom/bom.py b/erpnext/manufacturing/doctype/bom/bom.py index 4c88eca8f6..b29f6710e1 100644 --- a/erpnext/manufacturing/doctype/bom/bom.py +++ b/erpnext/manufacturing/doctype/bom/bom.py @@ -445,6 +445,7 @@ class BOM(WebsiteGenerator): and self.is_active ): frappe.db.set(self, "is_default", 1) + frappe.db.set_value("Item", self.item, "default_bom", self.name) else: frappe.db.set(self, "is_default", 0) item = frappe.get_doc("Item", self.item) diff --git a/erpnext/manufacturing/doctype/bom/test_bom.py b/erpnext/manufacturing/doctype/bom/test_bom.py index 182a20c6bb..860512c91d 100644 --- a/erpnext/manufacturing/doctype/bom/test_bom.py +++ b/erpnext/manufacturing/doctype/bom/test_bom.py @@ -559,6 +559,42 @@ class TestBOM(FrappeTestCase): bom.submit() self.assertEqual(bom.items[0].rate, 42) + def test_set_default_bom_for_item_having_single_bom(self): + from erpnext.stock.doctype.item.test_item import make_item + + fg_item = make_item(properties={"is_stock_item": 1}) + bom_item = make_item(properties={"is_stock_item": 1}) + + # Step 1: Create BOM + bom = frappe.new_doc("BOM") + bom.item = fg_item.item_code + bom.quantity = 1 + bom.append( + "items", + { + "item_code": bom_item.item_code, + "qty": 1, + "uom": bom_item.stock_uom, + "stock_uom": bom_item.stock_uom, + "rate": 100.0, + }, + ) + bom.save() + bom.submit() + self.assertEqual(frappe.get_value("Item", fg_item.item_code, "default_bom"), bom.name) + + # Step 2: Uncheck is_active field + bom.is_active = 0 + bom.save() + bom.reload() + self.assertIsNone(frappe.get_value("Item", fg_item.item_code, "default_bom")) + + # Step 3: Check is_active field + bom.is_active = 1 + bom.save() + bom.reload() + self.assertEqual(frappe.get_value("Item", fg_item.item_code, "default_bom"), bom.name) + def get_default_bom(item_code="_Test FG Item 2"): return frappe.db.get_value("BOM", {"item": item_code, "is_active": 1, "is_default": 1}) From ce1b4e40a15eb88a715d0fd25089ceb8df5f3cde Mon Sep 17 00:00:00 2001 From: Vladislav Date: Tue, 21 Jun 2022 16:55:05 +0300 Subject: [PATCH 10/21] fix: update ru translate (#31404) * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv fix logic * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv * Update ru.csv --- erpnext/translations/ru.csv | 84 ++++++++++++++++++------------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/erpnext/translations/ru.csv b/erpnext/translations/ru.csv index 743b29493c..a4bfb86c01 100644 --- a/erpnext/translations/ru.csv +++ b/erpnext/translations/ru.csv @@ -44,7 +44,7 @@ Accessable Value,Доступная стоимость, Account,Аккаунт, Account Number,Номер аккаунта, Account Number {0} already used in account {1},"Номер счета {0}, уже использованный в учетной записи {1}", -Account Pay Only,Счет Оплатить только, +Account Pay Only,Только оплатить счет, Account Type,Тип учетной записи, Account Type for {0} must be {1},Тип счета для {0} должен быть {1}, "Account balance already in Credit, you are not allowed to set 'Balance Must Be' as 'Debit'","Баланс счета в Кредите, запрещена установка 'Баланс должен быть' как 'Дебет'", @@ -117,7 +117,7 @@ Add Item,Добавить продукт, Add Items,Добавить продукты, Add Leads,Добавить лид, Add Multiple Tasks,Добавить несколько задач, -Add Row,Добавить ряд, +Add Row,Добавить строку, Add Sales Partners,Добавить партнеров по продажам, Add Serial No,Добавить серийный номер, Add Students,Добавить студентов, @@ -692,7 +692,7 @@ Created {0} scorecards for {1} between: ,Созданы {0} оценочные Creating Company and Importing Chart of Accounts,Создание компании и импорт плана счетов, Creating Fees,Создание сборов, Creating Payment Entries......,Создание платежных записей......, -Creating Salary Slips...,Создание зарплатных листков..., +Creating Salary Slips...,Создание зарплатных ведомостей..., Creating student groups,Создание групп студентов, Creating {0} Invoice,Создание {0} счета, Credit,Кредит, @@ -995,7 +995,7 @@ Expenses,Расходы, Expenses Included In Asset Valuation,"Расходы, включенные в оценку активов", Expenses Included In Valuation,"Затрат, включаемых в оценке", Expired Batches,Просроченные партии, -Expires On,Годен до, +Expires On,Актуален до, Expiring On,Срок действия, Expiry (In Days),Срок действия (в днях), Explore,Обзор, @@ -1411,7 +1411,7 @@ Lab Test UOM,Лабораторная проверка UOM, Lab Tests and Vital Signs,Лабораторные тесты и жизненные знаки, Lab result datetime cannot be before testing datetime,Лабораторный результат datetime не может быть до тестирования даты и времени, Lab testing datetime cannot be before collection datetime,Лабораторное тестирование datetime не может быть до даты сбора данных, -Label,Ярлык, +Label,Метка, Laboratory,Лаборатория, Language Name,Название языка, Large,Большой, @@ -2874,7 +2874,7 @@ Supplier Id,Id поставщика, Supplier Invoice Date cannot be greater than Posting Date,"Дата Поставщик Счет не может быть больше, чем Дата публикации", Supplier Invoice No,Поставщик Счет №, Supplier Invoice No exists in Purchase Invoice {0},Номер счета поставщика отсутствует в счете на покупку {0}, -Supplier Name,наименование поставщика, +Supplier Name,Наименование поставщика, Supplier Part No,Деталь поставщика №, Supplier Quotation,Предложение поставщика, Supplier Scorecard,Оценочная карта поставщика, @@ -3091,7 +3091,7 @@ Total Payment Amount in Payment Schedule must be equal to Grand / Rounded Total, Total Payments,Всего платежей, Total Present,Итого Текущая, Total Qty,Общее количество, -Total Quantity,Общая численность, +Total Quantity,Общее количество, Total Revenue,Общий доход, Total Student,Всего учеников, Total Target,Всего целей, @@ -3498,7 +3498,7 @@ Postal,Почтовый, Postal Code,Почтовый индекс, Previous,Предыдущая, Provider,Поставщик, -Read Only,Только чтения, +Read Only,Только чтение, Recipient,Сторона-реципиент, Reviews,Отзывы, Sender,Отправитель, @@ -3879,7 +3879,7 @@ On Lead Creation,Создание лида, On Supplier Creation,Создание поставщика, On Customer Creation,Создание клиента, Only .csv and .xlsx files are supported currently,В настоящее время поддерживаются только файлы .csv и .xlsx, -Only expired allocation can be cancelled,Только истекшее распределение может быть отменено, +Only expired allocation can be cancelled,Отменить можно только просроченное распределение, Only users with the {0} role can create backdated leave applications,Только пользователи с ролью {0} могут создавать оставленные приложения с задним сроком действия, Open,Открыт, Open Contact,Открытый контакт, @@ -4046,7 +4046,7 @@ Server Error,Ошибка сервера, Service Level Agreement has been changed to {0}.,Соглашение об уровне обслуживания изменено на {0}., Service Level Agreement was reset.,Соглашение об уровне обслуживания было сброшено., Service Level Agreement with Entity Type {0} and Entity {1} already exists.,Соглашение об уровне обслуживания с типом объекта {0} и объектом {1} уже существует., -Set,Задать, +Set,Комплект, Set Meta Tags,Установить метатеги, Set {0} in company {1},Установить {0} в компании {1}, Setup,Настройки, @@ -4059,7 +4059,7 @@ Show Stock Ageing Data,Показать данные о старении зап Show Warehouse-wise Stock,Показать складской запас, Size,Размер, Something went wrong while evaluating the quiz.,Что-то пошло не так при оценке теста., -Sr,Sr, +Sr,№, Start,Начать, Start Date cannot be before the current date,Дата начала не может быть раньше текущей даты, Start Time,Время начала, @@ -4513,7 +4513,7 @@ Mandatory For Profit and Loss Account,Обязательно для счета Accounting Period,Период учета, Period Name,Название периода, Closed Documents,Закрытые документы, -Accounts Settings,Настройки аккаунта, +Accounts Settings,Настройка счетов, Settings for Accounts,Настройки для счетов, Make Accounting Entry For Every Stock Movement,Создавать бухгалтерские проводки при каждом перемещении запасов, Users with this role are allowed to set frozen accounts and create / modify accounting entries against frozen accounts,"Пользователи с этой ролью могут замороживать счета, а также создавать / изменять бухгалтерские проводки замороженных счетов", @@ -5084,8 +5084,8 @@ Allow Zero Valuation Rate,Разрешить нулевую оценку, Item Tax Rate,Ставка налогов на продукт, Tax detail table fetched from item master as a string and stored in this field.\nUsed for Taxes and Charges,Налоговый Подробная таблица выбирается из мастера элемента в виде строки и хранится в этой области.\n Используется по налогам и сборам, Purchase Order Item,Заказ товара, -Purchase Receipt Detail,Деталь квитанции о покупке, -Item Weight Details,Деталь Вес Подробности, +Purchase Receipt Detail,Сведения о квитанции о покупке, +Item Weight Details,Сведения о весе товара, Weight Per Unit,Вес на единицу, Total Weight,Общий вес, Weight UOM,Вес Единица измерения, @@ -5198,7 +5198,7 @@ Address and Contacts,Адрес и контакты, Contact List,Список контактов, Hidden list maintaining the list of contacts linked to Shareholder,"Скрытый список, поддерживающий список контактов, связанных с Акционером", Specify conditions to calculate shipping amount,Укажите условия для расчета суммы доставки, -Shipping Rule Label,Название правила доставки, +Shipping Rule Label,Метка правила доставки, example: Next Day Shipping,Пример: доставка на следующий день, Shipping Rule Type,Тип правила доставки, Shipping Account,Счет доставки, @@ -5236,7 +5236,7 @@ Billing Interval,Интервал выставления счетов, Billing Interval Count,Счет интервала фактурирования, "Number of intervals for the interval field e.g if Interval is 'Days' and Billing Interval Count is 3, invoices will be generated every 3 days","Количество интервалов для поля интервалов, например, если Interval является «Days», а количество интервалов фактурирования - 3, счета-фактуры будут генерироваться каждые 3 дня", Payment Plan,Платежный план, -Subscription Plan Detail,Деталь плана подписки, +Subscription Plan Detail,Сведения о плана подписки, Plan,План, Subscription Settings,Настройки подписки, Grace Period,Льготный период, @@ -5802,7 +5802,7 @@ Make Academic Term Mandatory,Сделать академический срок Skip User creation for new Student,Пропустить создание пользователя для нового студента, "By default, a new User is created for every new Student. If enabled, no new User will be created when a new Student is created.","По умолчанию для каждого нового Студента создается новый Пользователь. Если этот параметр включен, при создании нового Студента новый Пользователь не создается.", Instructor Records to be created by,Записи инструкторов должны быть созданы, -Employee Number,Общее число сотрудников, +Employee Number,Номер сотрудника, Fee Category,Категория платы, Fee Component,Компонент платы, Fees Category,Категория плат, @@ -6196,7 +6196,7 @@ Inpatient Occupancy,Стационарное размещение, Occupancy Status,Статус занятости, Vacant,Вакантно, Occupied,Занято, -Item Details,Детальная информация о товаре, +Item Details,Детальная информация о продукте, UOM Conversion in Hours,Преобразование UOM в часы, Rate / UOM,Скорость / UOM, Change in Item,Изменение продукта, @@ -6868,8 +6868,8 @@ Only Tax Impact (Cannot Claim But Part of Taxable Income),Только нало Create Separate Payment Entry Against Benefit Claim,Создать отдельную заявку на подачу заявки на получение пособия, Condition and Formula,Состояние и формула, Amount based on formula,Сумма на основе формулы, -Formula,формула, -Salary Detail,Заработная плата: Подробности, +Formula,Формула, +Salary Detail,Подробно об заработной плате, Component,Компонент, Do not include in total,Не включать в общей сложности, Default Amount,По умолчанию количество, @@ -6891,7 +6891,7 @@ Total Principal Amount,Общая сумма, Total Interest Amount,Общая сумма процентов, Total Loan Repayment,Общая сумма погашения кредита, net pay info,Чистая информация платить, -Gross Pay - Total Deduction - Loan Repayment,Gross Pay - Итого Вычет - Погашение кредита, +Gross Pay - Total Deduction - Loan Repayment,Валовая заработная плата - Общий вычет - Погашение кредита, Total in words,Всего в словах, Net Pay (in words) will be visible once you save the Salary Slip.,"Чистая плата (прописью) будет видна, как только вы сохраните зарплатную ведомость.", Salary Component for timesheet based payroll.,Компонент заработной платы для расчета зарплаты на основе расписания., @@ -6961,7 +6961,7 @@ Trainer Email,Электронная почта тренера, Attendees,Присутствующие, Employee Emails,Электронные почты сотрудников, Training Event Employee,Обучение сотрудников Событие, -Invited,приглашенный, +Invited,Приглашенный, Feedback Submitted,Отзыв отправлен, Optional,Необязательный, Training Result Employee,Результат обучения сотрудника, @@ -7185,7 +7185,7 @@ Ordered Quantity,Заказанное количество, Item to be manufactured or repacked,Продукт должен быть произведен или переупакован, Quantity of item obtained after manufacturing / repacking from given quantities of raw materials,Количество пункта получены после изготовления / переупаковка от заданных величин сырья, Set rate of sub-assembly item based on BOM,Установить скорость сборки на основе спецификации, -Allow Alternative Item,Разрешить альтернативный элемент, +Allow Alternative Item,Разрешить альтернативный продукт, Item UOM,Единиц продукта, Conversion Rate,Коэффициент конверсии, Rate Of Materials Based On,Оценить материалов на основе, @@ -7600,7 +7600,7 @@ Invoices with no Place Of Supply,Счета без места поставки, Import Supplier Invoice,Импортная накладная поставщика, Invoice Series,Серия счетов, Upload XML Invoices,Загрузить XML-счета, -Zip File,Zip-файл, +Zip File,Zip файл, Import Invoices,Импорт счетов, Click on Import Invoices button once the zip file has been attached to the document. Any errors related to processing will be shown in the Error Log.,"Нажмите кнопку «Импортировать счета-фактуры», когда файл zip прикреплен к документу. Любые ошибки, связанные с обработкой, будут отображаться в журнале ошибок.", Lower Deduction Certificate,Свидетельство о нижнем удержании, @@ -7635,7 +7635,7 @@ Restaurant Order Entry Item,Номер заказа заказа рестора Served,Подается, Restaurant Reservation,Бронирование ресторанов, Waitlisted,Лист ожидания, -No Show,Нет шоу, +No Show,Не показывать, No of People,Нет людей, Reservation Time,Время резервирования, Reservation End Time,Время окончания бронирования, @@ -7873,8 +7873,8 @@ Disable In Words,Отключить в словах, "If disable, 'In Words' field will not be visible in any transaction","Если отключить, "В словах" поле не будет видно в любой сделке", Item Classification,Продуктовая классификация, General Settings,Основные настройки, -Item Group Name,Пункт Название группы, -Parent Item Group,Родитель Пункт Группа, +Item Group Name,Название группы продуктов, +Parent Item Group,Родительская группа продукта, Item Group Defaults,Элемент группы по умолчанию, Item Tax,Налог на продукт, Check this if you want to show in website,"Проверьте это, если вы хотите показать в веб-сайт", @@ -7971,13 +7971,13 @@ Customs Tariff Number,Номер таможенного тарифа, Tariff Number,Тарифный номер, Delivery To,Доставка, MAT-DN-.YYYY.-,MAT-DN-.YYYY.-, -Is Return,Является Вернуться, +Is Return,Возврат, Issue Credit Note,Кредитная кредитная карта, -Return Against Delivery Note,Вернуться На накладной, -Customer's Purchase Order No,Клиентам Заказ Нет, +Return Against Delivery Note,Возврат по накладной, +Customer's Purchase Order No,Заказ клиента №, Billing Address Name,Название адреса для выставления счета, Required only for sample item.,Требуется только для образца пункта., -"If you have created a standard template in Sales Taxes and Charges Template, select one and click on the button below.","Если вы создали стандартный шаблон в шаблонах Налоги с налогами и сбором платежей, выберите его и нажмите кнопку ниже.", +"If you have created a standard template in Sales Taxes and Charges Template, select one and click on the button below.","Если вы создали стандартный шаблон в Шаблоне налогов и сборов с продаж, выберите его и нажмите кнопку ниже.", In Words will be visible once you save the Delivery Note.,По словам будет виден только вы сохраните накладной., In Words (Export) will be visible once you save the Delivery Note.,В Слов (Экспорт) будут видны только вы сохраните накладной., Transporter Info,Информация для транспортировки, @@ -7991,8 +7991,8 @@ Installation Status,Состояние установки, Excise Page Number,Количество Акцизный Страница, Instructions,Инструкции, From Warehouse,Со склада, -Against Sales Order,По Сделке, -Against Sales Order Item,По Продукту Сделки, +Against Sales Order,По сделке, +Against Sales Order Item,По позиции сделки, Against Sales Invoice,Повторная накладная, Against Sales Invoice Item,Счет на продажу продукта, Available Batch Qty at From Warehouse,Доступные Пакетная Кол-во на со склада, @@ -8008,7 +8008,7 @@ Delivery Stop,Остановить доставку, Lock,Заблокировано, Visited,Посещен, Order Information,запросить информацию, -Contact Information,Контакты, +Contact Information,Контактная информация, Email sent to,Письмо отправлено, Dispatch Information,Информация о доставке, Estimated Arrival,Ожидаемое прибытие, @@ -8121,7 +8121,7 @@ Two-way,Двусторонний, Alternative Item Name,Альтернативное название продукта, Attribute Name,Название атрибута, Numeric Values,Числовые значения, -From Range,От хребта, +From Range,Из диапазона, Increment,Приращение, To Range,В диапазоне, Item Attribute Values,Пункт значений атрибутов, @@ -8143,7 +8143,7 @@ Default Supplier,Поставщик по умолчанию, Default Expense Account,Счет учета затрат по умолчанию, Sales Defaults,По умолчанию, Default Selling Cost Center,По умолчанию Продажа Стоимость центр, -Item Manufacturer,Пункт Производитель, +Item Manufacturer,Производитель товара, Item Price,Цена продукта, Packing Unit,Упаковочный блок, Quantity that must be bought or sold per UOM,"Количество, которое необходимо купить или продать за UOM", @@ -8177,7 +8177,7 @@ Purchase Receipts,Покупка Поступления, Purchase Receipt Items,Покупка продуктов, Get Items From Purchase Receipts,Получить продукты из покупки., Distribute Charges Based On,Распределите платежи на основе, -Landed Cost Help,Земельные Стоимость Помощь, +Landed Cost Help,Справка по стоимости доставки, Manufacturers used in Items,Производители использовали в пунктах, Limited to 12 characters,Ограничено до 12 символов, MAT-MR-.YYYY.-,МАТ-MR-.YYYY.-, @@ -8186,13 +8186,13 @@ Transferred,Переданы, % Ordered,% заказано, Terms and Conditions Content,Условия Содержимое, Quantity and Warehouse,Количество и Склад, -Lead Time Date,Время и Дата Лида, -Min Order Qty,Минимальный заказ Кол-во, +Lead Time Date,Дата выполнения заказа, +Min Order Qty,Минимальное количество для заказа, Packed Item,Упаковано, To Warehouse (Optional),На склад (Необязательно), Actual Batch Quantity,Фактическое количество партий, Prevdoc DocType,Prevdoc DocType, -Parent Detail docname,Родитель Деталь DOCNAME, +Parent Detail docname,Сведения о родителе docname, "Generate packing slips for packages to be delivered. Used to notify package number, package contents and its weight.","Создаёт упаковочные листы к упаковкам для доставки. Содержит номер упаковки, перечень содержимого и вес.", Indicates that the package is a part of this delivery (Only Draft),"Указывает, что пакет является частью этой поставки (только проект)", MAT-PAC-.YYYY.-,MAT-PAC-.YYYY.-, @@ -8353,7 +8353,7 @@ Automatically Set Serial Nos based on FIFO,Автоматически устан Auto Material Request,Автоматический запрос материалов, Inter Warehouse Transfer Settings,Настройки передачи между складами, Freeze Stock Entries,Замораживание поступления запасов, -Stock Frozen Upto,остатки заморожены до, +Stock Frozen Upto,Остатки заморожены до, Batch Identification,Идентификация партии, Use Naming Series,Использовать серийный номер, Naming Series Prefix,Префикс Идентификации по Имени, @@ -8372,7 +8372,7 @@ Issue Split From,Выпуск Сплит От, Service Level,Уровень обслуживания, Response By,Ответ от, Response By Variance,Ответ по отклонениям, -Ongoing,постоянный, +Ongoing,Постоянный, Resolution By,Разрешение по, Resolution By Variance,Разрешение по отклонениям, Service Level Agreement Creation,Создание соглашения об уровне обслуживания, From 5826b7b0718a1838746eb9755bb001308ed9a642 Mon Sep 17 00:00:00 2001 From: ruthra kumar Date: Tue, 21 Jun 2022 19:50:50 +0530 Subject: [PATCH 11/21] fix: identify empty values "" in against_voucher columns --- erpnext/patches/v14_0/migrate_gl_to_payment_ledger.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/erpnext/patches/v14_0/migrate_gl_to_payment_ledger.py b/erpnext/patches/v14_0/migrate_gl_to_payment_ledger.py index 1e0d20d059..e15aa4a1f4 100644 --- a/erpnext/patches/v14_0/migrate_gl_to_payment_ledger.py +++ b/erpnext/patches/v14_0/migrate_gl_to_payment_ledger.py @@ -1,6 +1,6 @@ import frappe from frappe import qb -from frappe.query_builder import Case +from frappe.query_builder import Case, CustomFunction from frappe.query_builder.custom import ConstantColumn from frappe.query_builder.functions import IfNull @@ -87,6 +87,7 @@ def execute(): gl = qb.DocType("GL Entry") account = qb.DocType("Account") + ifelse = CustomFunction("IF", ["condition", "then", "else"]) gl_entries = ( qb.from_(gl) @@ -96,8 +97,12 @@ def execute(): gl.star, ConstantColumn(1).as_("docstatus"), account.account_type.as_("account_type"), - IfNull(gl.against_voucher_type, gl.voucher_type).as_("against_voucher_type"), - IfNull(gl.against_voucher, gl.voucher_no).as_("against_voucher_no"), + IfNull( + ifelse(gl.against_voucher_type == "", None, gl.against_voucher_type), gl.voucher_type + ).as_("against_voucher_type"), + IfNull(ifelse(gl.against_voucher == "", None, gl.against_voucher), gl.voucher_no).as_( + "against_voucher_no" + ), # convert debit/credit to amount Case() .when(account.account_type == "Receivable", gl.debit - gl.credit) From 8b1ff96e30e88f6a8c9dabed097efeac310645c1 Mon Sep 17 00:00:00 2001 From: hrzzz Date: Tue, 21 Jun 2022 15:10:19 -0300 Subject: [PATCH 12/21] fix: translation for filter status on report --- .../report/purchase_order_analysis/purchase_order_analysis.js | 1 + .../selling/report/sales_order_analysis/sales_order_analysis.js | 1 + 2 files changed, 2 insertions(+) diff --git a/erpnext/buying/report/purchase_order_analysis/purchase_order_analysis.js b/erpnext/buying/report/purchase_order_analysis/purchase_order_analysis.js index ca3be03da6..721e54e46f 100644 --- a/erpnext/buying/report/purchase_order_analysis/purchase_order_analysis.js +++ b/erpnext/buying/report/purchase_order_analysis/purchase_order_analysis.js @@ -59,6 +59,7 @@ frappe.query_reports["Purchase Order Analysis"] = { for (let option of status){ options.push({ "value": option, + "label": __(option), "description": "" }) } diff --git a/erpnext/selling/report/sales_order_analysis/sales_order_analysis.js b/erpnext/selling/report/sales_order_analysis/sales_order_analysis.js index 76a5bb51ca..91748bc7be 100644 --- a/erpnext/selling/report/sales_order_analysis/sales_order_analysis.js +++ b/erpnext/selling/report/sales_order_analysis/sales_order_analysis.js @@ -55,6 +55,7 @@ frappe.query_reports["Sales Order Analysis"] = { for (let option of status){ options.push({ "value": option, + "label": __(option), "description": "" }) } From 00807abe314344fec1ec636ac5f281473589f7f1 Mon Sep 17 00:00:00 2001 From: s-aga-r Date: Wed, 22 Jun 2022 10:48:49 +0530 Subject: [PATCH 13/21] fix: add UOM validation for planned-qty --- .../production_plan/production_plan.py | 2 ++ .../production_plan/test_production_plan.py | 25 +++++++++++++------ 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/erpnext/manufacturing/doctype/production_plan/production_plan.py b/erpnext/manufacturing/doctype/production_plan/production_plan.py index 8a28454af2..a73b9bcc69 100644 --- a/erpnext/manufacturing/doctype/production_plan/production_plan.py +++ b/erpnext/manufacturing/doctype/production_plan/production_plan.py @@ -25,6 +25,7 @@ from erpnext.manufacturing.doctype.bom.bom import get_children as get_bom_childr from erpnext.manufacturing.doctype.bom.bom import validate_bom_no from erpnext.manufacturing.doctype.work_order.work_order import get_item_details from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults +from erpnext.utilities.transaction_base import validate_uom_is_integer class ProductionPlan(Document): @@ -33,6 +34,7 @@ class ProductionPlan(Document): self.calculate_total_planned_qty() self.set_status() self._rename_temporary_references() + validate_uom_is_integer(self, "stock_uom", "planned_qty") def set_pending_qty_in_row_without_reference(self): "Set Pending Qty in independent rows (not from SO or MR)." diff --git a/erpnext/manufacturing/doctype/production_plan/test_production_plan.py b/erpnext/manufacturing/doctype/production_plan/test_production_plan.py index e88049d810..040e791e00 100644 --- a/erpnext/manufacturing/doctype/production_plan/test_production_plan.py +++ b/erpnext/manufacturing/doctype/production_plan/test_production_plan.py @@ -679,15 +679,23 @@ class TestProductionPlan(FrappeTestCase): self.assertFalse(pp.all_items_completed()) def test_production_plan_planned_qty(self): - pln = create_production_plan(item_code="_Test FG Item", planned_qty=0.55) - pln.make_work_order() - work_order = frappe.db.get_value("Work Order", {"production_plan": pln.name}, "name") - wo_doc = frappe.get_doc("Work Order", work_order) - wo_doc.update( - {"wip_warehouse": "Work In Progress - _TC", "fg_warehouse": "Finished Goods - _TC"} + # Case 1: When Planned Qty is non-integer and UOM is integer. + from erpnext.utilities.transaction_base import UOMMustBeIntegerError + + self.assertRaises( + UOMMustBeIntegerError, create_production_plan, item_code="_Test FG Item", planned_qty=0.55 ) - wo_doc.submit() - self.assertEqual(wo_doc.qty, 0.55) + + # Case 2: When Planned Qty is non-integer and UOM is also non-integer. + from erpnext.stock.doctype.item.test_item import make_item + + fg_item = make_item(properties={"is_stock_item": 1, "stock_uom": "_Test UOM 1"}).name + bom_item = make_item().name + + make_bom(item=fg_item, raw_materials=[bom_item], source_warehouse="_Test Warehouse - _TC") + + pln = create_production_plan(item_code=fg_item, planned_qty=0.55, stock_uom="_Test UOM 1") + self.assertEqual(pln.po_items[0].planned_qty, 0.55) def test_temporary_name_relinking(self): @@ -751,6 +759,7 @@ def create_production_plan(**args): "bom_no": frappe.db.get_value("Item", args.item_code, "default_bom"), "planned_qty": args.planned_qty or 1, "planned_start_date": args.planned_start_date or now_datetime(), + "stock_uom": args.stock_uom or "Nos", }, ) From ab13a178b55218c6a9295cb793e6f6deee5c07a2 Mon Sep 17 00:00:00 2001 From: GangaManoj Date: Wed, 22 Jun 2022 21:24:22 +0530 Subject: [PATCH 14/21] fix: Replace asset life with total no of depreciations --- erpnext/assets/doctype/asset/asset.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/erpnext/assets/doctype/asset/asset.py b/erpnext/assets/doctype/asset/asset.py index 257488dfc3..650411c3aa 100644 --- a/erpnext/assets/doctype/asset/asset.py +++ b/erpnext/assets/doctype/asset/asset.py @@ -849,14 +849,10 @@ class Asset(AccountsController): if args.get("rate_of_depreciation") and on_validate: return args.get("rate_of_depreciation") - no_of_years = ( - flt(args.get("total_number_of_depreciations") * flt(args.get("frequency_of_depreciation"))) - / 12 - ) value = flt(args.get("expected_value_after_useful_life")) / flt(self.gross_purchase_amount) # square root of flt(salvage_value) / flt(asset_cost) - depreciation_rate = math.pow(value, 1.0 / flt(no_of_years, 2)) + depreciation_rate = math.pow(value, 1.0 / flt(args.get("total_number_of_depreciations"), 2)) return 100 * (1 - flt(depreciation_rate, float_precision)) From 2d9153ea3058abb849527dd5c34aa056e2a25d3a Mon Sep 17 00:00:00 2001 From: GangaManoj Date: Wed, 22 Jun 2022 21:24:46 +0530 Subject: [PATCH 15/21] fix: Remove misleading comment --- erpnext/assets/doctype/asset/asset.py | 1 - 1 file changed, 1 deletion(-) diff --git a/erpnext/assets/doctype/asset/asset.py b/erpnext/assets/doctype/asset/asset.py index 650411c3aa..cf556a659c 100644 --- a/erpnext/assets/doctype/asset/asset.py +++ b/erpnext/assets/doctype/asset/asset.py @@ -851,7 +851,6 @@ class Asset(AccountsController): value = flt(args.get("expected_value_after_useful_life")) / flt(self.gross_purchase_amount) - # square root of flt(salvage_value) / flt(asset_cost) depreciation_rate = math.pow(value, 1.0 / flt(args.get("total_number_of_depreciations"), 2)) return 100 * (1 - flt(depreciation_rate, float_precision)) From b07aae4da5f186e6c4b9714e13bf9ef3a7a53ec7 Mon Sep 17 00:00:00 2001 From: GangaManoj Date: Wed, 22 Jun 2022 21:33:17 +0530 Subject: [PATCH 16/21] fix: Correct pro-rata amount calculation --- erpnext/assets/doctype/asset/asset.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/erpnext/assets/doctype/asset/asset.py b/erpnext/assets/doctype/asset/asset.py index cf556a659c..88c462e1df 100644 --- a/erpnext/assets/doctype/asset/asset.py +++ b/erpnext/assets/doctype/asset/asset.py @@ -860,6 +860,14 @@ class Asset(AccountsController): months = month_diff(to_date, from_date) total_days = get_total_days(to_date, row.frequency_of_depreciation) + print("\n"*10) + print("from_date: ", from_date) + print("to_date: ", to_date) + print("\n") + print("days: ", days) + print("total_days: ", total_days) + print("\n"*10) + return (depreciation_amount * flt(days)) / flt(total_days), days, months @@ -1100,8 +1108,16 @@ def is_cwip_accounting_enabled(asset_category): def get_total_days(date, frequency): period_start_date = add_months(date, cint(frequency) * -1) + if is_last_day_of_the_month(date): + period_start_date = get_last_day(period_start_date) + return date_diff(date, period_start_date) +def is_last_day_of_the_month(date): + last_day_of_the_month = get_last_day(date) + + return getdate(last_day_of_the_month) == getdate(date) + @erpnext.allow_regional def get_depreciation_amount(asset, depreciable_value, row): From 154e258ad097e750512592fbccac0d15d4667f59 Mon Sep 17 00:00:00 2001 From: GangaManoj Date: Wed, 22 Jun 2022 21:39:39 +0530 Subject: [PATCH 17/21] fix: Get last day of the monthif depr posting date is the last day of its month --- erpnext/assets/doctype/asset/asset.py | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/erpnext/assets/doctype/asset/asset.py b/erpnext/assets/doctype/asset/asset.py index 88c462e1df..fc1e7afd3a 100644 --- a/erpnext/assets/doctype/asset/asset.py +++ b/erpnext/assets/doctype/asset/asset.py @@ -252,6 +252,7 @@ class Asset(AccountsController): number_of_pending_depreciations += 1 skip_row = False + should_get_last_day = is_last_day_of_the_month(finance_book.depreciation_start_date) for n in range(start[finance_book.idx - 1], number_of_pending_depreciations): # If depreciation is already completed (for double declining balance) @@ -265,6 +266,9 @@ class Asset(AccountsController): finance_book.depreciation_start_date, n * cint(finance_book.frequency_of_depreciation) ) + if should_get_last_day: + schedule_date = get_last_day(schedule_date) + # schedule date will be a year later from start date # so monthly schedule date is calculated by removing 11 months from it monthly_schedule_date = add_months(schedule_date, -finance_book.frequency_of_depreciation + 1) @@ -860,14 +864,6 @@ class Asset(AccountsController): months = month_diff(to_date, from_date) total_days = get_total_days(to_date, row.frequency_of_depreciation) - print("\n"*10) - print("from_date: ", from_date) - print("to_date: ", to_date) - print("\n") - print("days: ", days) - print("total_days: ", total_days) - print("\n"*10) - return (depreciation_amount * flt(days)) / flt(total_days), days, months From e62beaefc1cb5db9656be6cd0b354bd368e5f971 Mon Sep 17 00:00:00 2001 From: GangaManoj Date: Wed, 22 Jun 2022 22:23:01 +0530 Subject: [PATCH 18/21] test: Test if final day of the month is taken if depr_start_date is the last day of its month --- erpnext/assets/doctype/asset/test_asset.py | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/erpnext/assets/doctype/asset/test_asset.py b/erpnext/assets/doctype/asset/test_asset.py index e759ad0719..7ef47d280c 100644 --- a/erpnext/assets/doctype/asset/test_asset.py +++ b/erpnext/assets/doctype/asset/test_asset.py @@ -1333,6 +1333,32 @@ class TestDepreciationBasics(AssetSetup): asset.cost_center = "Main - _TC" asset.submit() + def test_depreciation_on_final_day_of_the_month(self): + """Tests if final day of the month is picked each time, if the depreciation start date is the last day of the month.""" + + asset = create_asset( + item_code="Macbook Pro", + calculate_depreciation=1, + purchase_date="2020-01-30", + available_for_use_date="2020-02-15", + depreciation_start_date="2020-02-29", + frequency_of_depreciation=1, + total_number_of_depreciations=5, + submit=1, + ) + + expected_dates = [ + "2020-02-29", + "2020-03-31", + "2020-04-30", + "2020-05-31", + "2020-06-30", + "2020-07-15", + ] + + for i, schedule in enumerate(asset.schedules): + self.assertEqual(getdate(expected_dates[i]), getdate(schedule.schedule_date)) + def create_asset_data(): if not frappe.db.exists("Asset Category", "Computers"): From 2b7ab72a72fc8482f569a7a3edc303d78e7e762e Mon Sep 17 00:00:00 2001 From: GangaManoj Date: Wed, 22 Jun 2022 22:46:48 +0530 Subject: [PATCH 19/21] fix: Convert string to datetime object --- erpnext/assets/doctype/asset/test_asset.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/erpnext/assets/doctype/asset/test_asset.py b/erpnext/assets/doctype/asset/test_asset.py index 7ef47d280c..f1be08cb7f 100644 --- a/erpnext/assets/doctype/asset/test_asset.py +++ b/erpnext/assets/doctype/asset/test_asset.py @@ -838,7 +838,7 @@ class TestDepreciationBasics(AssetSetup): expected_values = [["2020-12-31", 30000.0], ["2021-12-31", 30000.0], ["2022-12-31", 30000.0]] for i, schedule in enumerate(asset.schedules): - self.assertEqual(expected_values[i][0], schedule.schedule_date) + self.assertEqual(getdate(expected_values[i][0]), schedule.schedule_date) self.assertEqual(expected_values[i][1], schedule.depreciation_amount) def test_set_accumulated_depreciation(self): From 1b1786532afb9298db6a8c5f8770d4a5b9fba71b Mon Sep 17 00:00:00 2001 From: GangaManoj Date: Wed, 22 Jun 2022 22:53:25 +0530 Subject: [PATCH 20/21] test: Test monthly depreciation by Written Down Value method --- erpnext/assets/doctype/asset/test_asset.py | 33 ++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/erpnext/assets/doctype/asset/test_asset.py b/erpnext/assets/doctype/asset/test_asset.py index f1be08cb7f..58fd40088f 100644 --- a/erpnext/assets/doctype/asset/test_asset.py +++ b/erpnext/assets/doctype/asset/test_asset.py @@ -707,6 +707,39 @@ class TestDepreciationMethods(AssetSetup): self.assertEqual(schedules, expected_schedules) + def test_monthly_depreciation_by_wdv_method(self): + asset = create_asset( + calculate_depreciation=1, + available_for_use_date="2022-02-15", + purchase_date="2022-02-15", + depreciation_method="Written Down Value", + gross_purchase_amount=10000, + expected_value_after_useful_life=5000, + depreciation_start_date="2022-02-28", + total_number_of_depreciations=5, + frequency_of_depreciation=1, + ) + + expected_schedules = [ + ["2022-02-28", 645.0, 645.0], + ["2022-03-31", 1206.8, 1851.8], + ["2022-04-30", 1051.12, 2902.92], + ["2022-05-31", 915.52, 3818.44], + ["2022-06-30", 797.42, 4615.86], + ["2022-07-15", 384.14, 5000.0] + ] + + schedules = [ + [ + cstr(d.schedule_date), + flt(d.depreciation_amount, 2), + flt(d.accumulated_depreciation_amount, 2), + ] + for d in asset.get("schedules") + ] + + self.assertEqual(schedules, expected_schedules) + def test_discounted_wdv_depreciation_rate_for_indian_region(self): # set indian company company_flag = frappe.flags.company From 416d578290d8c9c1b2e387954164306266bf8ebc Mon Sep 17 00:00:00 2001 From: GangaManoj Date: Wed, 22 Jun 2022 23:29:03 +0530 Subject: [PATCH 21/21] fix: Add missing comma --- erpnext/assets/doctype/asset/asset.py | 1 + erpnext/assets/doctype/asset/test_asset.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/erpnext/assets/doctype/asset/asset.py b/erpnext/assets/doctype/asset/asset.py index fc1e7afd3a..a880c2f391 100644 --- a/erpnext/assets/doctype/asset/asset.py +++ b/erpnext/assets/doctype/asset/asset.py @@ -1109,6 +1109,7 @@ def get_total_days(date, frequency): return date_diff(date, period_start_date) + def is_last_day_of_the_month(date): last_day_of_the_month = get_last_day(date) diff --git a/erpnext/assets/doctype/asset/test_asset.py b/erpnext/assets/doctype/asset/test_asset.py index 58fd40088f..f8a8fc551d 100644 --- a/erpnext/assets/doctype/asset/test_asset.py +++ b/erpnext/assets/doctype/asset/test_asset.py @@ -726,7 +726,7 @@ class TestDepreciationMethods(AssetSetup): ["2022-04-30", 1051.12, 2902.92], ["2022-05-31", 915.52, 3818.44], ["2022-06-30", 797.42, 4615.86], - ["2022-07-15", 384.14, 5000.0] + ["2022-07-15", 384.14, 5000.0], ] schedules = [