- {{__("Suppliies made to Composition Taxable Persons")}} |
+ {{__("Supplies made to Composition Taxable Persons")}} |
{% for row in data.inter_sup.comp_details %}
{% if row %}
diff --git a/erpnext/regional/doctype/gstr_3b_report/gstr_3b_report.py b/erpnext/regional/doctype/gstr_3b_report/gstr_3b_report.py
index a49996d107..a5dd5a2e09 100644
--- a/erpnext/regional/doctype/gstr_3b_report/gstr_3b_report.py
+++ b/erpnext/regional/doctype/gstr_3b_report/gstr_3b_report.py
@@ -172,7 +172,6 @@ class GSTR3BReport(Document):
self.json_output = frappe.as_json(self.report_dict)
def set_inward_nil_exempt(self, inward_nil_exempt):
-
self.report_dict["inward_sup"]["isup_details"][0]["inter"] = flt(inward_nil_exempt.get("gst").get("inter"), 2)
self.report_dict["inward_sup"]["isup_details"][0]["intra"] = flt(inward_nil_exempt.get("gst").get("intra"), 2)
self.report_dict["inward_sup"]["isup_details"][1]["inter"] = flt(inward_nil_exempt.get("non_gst").get("inter"), 2)
@@ -238,7 +237,6 @@ class GSTR3BReport(Document):
self.report_dict[supply_type][supply_category]["txval"] += flt(txval, 2)
def set_inter_state_supply(self, inter_state_supply):
-
osup_det = self.report_dict["sup_details"]["osup_det"]
for key, value in iteritems(inter_state_supply):
@@ -352,10 +350,18 @@ class GSTR3BReport(Document):
inward_nil_exempt = frappe.db.sql(""" select p.place_of_supply, sum(i.base_amount) as base_amount,
i.is_nil_exempt, i.is_non_gst from `tabPurchase Invoice` p , `tabPurchase Invoice Item` i
where p.docstatus = 1 and p.name = i.parent
+ and p.gst_category != 'Registered Composition'
and (i.is_nil_exempt = 1 or i.is_non_gst = 1) and
month(p.posting_date) = %s and year(p.posting_date) = %s and p.company = %s and p.company_gstin = %s
group by p.place_of_supply, i.is_nil_exempt, i.is_non_gst""", (self.month_no, self.year, self.company, self.gst_details.get("gstin")), as_dict=1)
+ inward_nil_exempt += frappe.db.sql("""SELECT sum(base_net_total) as base_amount, gst_category, place_of_supply
+ FROM `tabPurchase Invoice`
+ WHERE docstatus = 1 and gst_category = 'Registered Composition'
+ and month(posting_date) = %s and year(posting_date) = %s
+ and company = %s and company_gstin = %s
+ group by place_of_supply""", (self.month_no, self.year, self.company, self.gst_details.get("gstin")), as_dict=1)
+
inward_nil_exempt_details = {
"gst": {
"intra": 0.0,
@@ -369,9 +375,11 @@ class GSTR3BReport(Document):
for d in inward_nil_exempt:
if d.place_of_supply:
- if d.is_nil_exempt == 1 and state == d.place_of_supply.split("-")[1]:
+ if (d.is_nil_exempt == 1 or d.get('gst_category') == 'Registered Composition') \
+ and state == d.place_of_supply.split("-")[1]:
inward_nil_exempt_details["gst"]["intra"] += d.base_amount
- elif d.is_nil_exempt == 1 and state != d.place_of_supply.split("-")[1]:
+ elif (d.is_nil_exempt == 1 or d.get('gst_category') == 'Registered Composition') \
+ and state != d.place_of_supply.split("-")[1]:
inward_nil_exempt_details["gst"]["inter"] += d.base_amount
elif d.is_non_gst == 1 and state == d.place_of_supply.split("-")[1]:
inward_nil_exempt_details["non_gst"]["intra"] += d.base_amount
diff --git a/erpnext/regional/doctype/gstr_3b_report/test_gstr_3b_report.py b/erpnext/regional/doctype/gstr_3b_report/test_gstr_3b_report.py
index 023b4ed22b..ef8af24c42 100644
--- a/erpnext/regional/doctype/gstr_3b_report/test_gstr_3b_report.py
+++ b/erpnext/regional/doctype/gstr_3b_report/test_gstr_3b_report.py
@@ -64,7 +64,7 @@ class TestGSTR3BReport(unittest.TestCase):
self.assertEqual(output["sup_details"]["osup_zero"]["iamt"], 18),
self.assertEqual(output["inter_sup"]["unreg_details"][0]["iamt"], 18),
self.assertEqual(output["sup_details"]["osup_nil_exmp"]["txval"], 100),
- self.assertEqual(output["inward_sup"]["isup_details"][0]["inter"], 250)
+ self.assertEqual(output["inward_sup"]["isup_details"][0]["intra"], 250)
self.assertEqual(output["itc_elg"]["itc_avl"][4]["samt"], 22.50)
self.assertEqual(output["itc_elg"]["itc_avl"][4]["camt"], 22.50)
@@ -228,6 +228,19 @@ def create_purchase_invoices():
pi1.submit()
+ pi2 = make_purchase_invoice(company="_Test Company GST",
+ customer = '_Test Registered Supplier',
+ currency = 'INR',
+ item = 'Milk',
+ warehouse = 'Finished Goods - _GST',
+ expense_account = 'Cost of Goods Sold - _GST',
+ cost_center = 'Main - _GST',
+ rate=250,
+ qty=1,
+ do_not_save=1
+ )
+ pi2.submit()
+
def make_suppliers():
if not frappe.db.exists("Supplier", "_Test Registered Supplier"):
frappe.get_doc({
diff --git a/erpnext/regional/report/gstr_2/gstr_2.py b/erpnext/regional/report/gstr_2/gstr_2.py
index f899349ccc..616c2b853d 100644
--- a/erpnext/regional/report/gstr_2/gstr_2.py
+++ b/erpnext/regional/report/gstr_2/gstr_2.py
@@ -44,7 +44,7 @@ class Gstr2Report(Gstr1Report):
for inv, items_based_on_rate in self.items_based_on_tax_rate.items():
invoice_details = self.invoices.get(inv)
for rate, items in items_based_on_rate.items():
- if rate:
+ if rate or invoice_details.get('gst_category') == 'Registered Composition':
if inv not in self.igst_invoices:
rate = rate / 2
row, taxable_value = self.get_row_data_for_invoice(inv, invoice_details, rate, items)
@@ -86,7 +86,7 @@ class Gstr2Report(Gstr1Report):
conditions += opts[1]
if self.filters.get("type_of_business") == "B2B":
- conditions += "and ifnull(gst_category, '') in ('Registered Regular', 'Deemed Export', 'SEZ') and is_return != 1 "
+ conditions += "and ifnull(gst_category, '') in ('Registered Regular', 'Deemed Export', 'SEZ', 'Registered Composition') and is_return != 1 "
elif self.filters.get("type_of_business") == "CDNR":
conditions += """ and is_return = 1 """
From 45eccfafc1e9357a85445c4b2c2aabe62872cf36 Mon Sep 17 00:00:00 2001
From: Prssanna Desai
Date: Wed, 31 Mar 2021 16:16:00 +0530
Subject: [PATCH 106/207] fix: do not set standard link in Sales Invoice as
custom (#25096)
---
erpnext/accounts/doctype/sales_invoice/sales_invoice.json | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
index 720a9175e6..d382386a32 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
@@ -1952,13 +1952,12 @@
"is_submittable": 1,
"links": [
{
- "custom": 1,
"group": "Reference",
"link_doctype": "POS Invoice",
"link_fieldname": "consolidated_invoice"
}
],
- "modified": "2021-02-01 15:42:26.261540",
+ "modified": "2021-03-31 15:42:26.261540",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Sales Invoice",
From 11e9ae3841a6f6b13a82c4292b15af045d84a2b8 Mon Sep 17 00:00:00 2001
From: Jannat Patel <31363128+pateljannat@users.noreply.github.com>
Date: Wed, 31 Mar 2021 16:24:08 +0530
Subject: [PATCH 107/207] fix: delivery note print error (#25080)
---
erpnext/stock/doctype/delivery_note/delivery_note.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.py b/erpnext/stock/doctype/delivery_note/delivery_note.py
index 35443906c8..d326a04173 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.py
@@ -101,7 +101,7 @@ class DeliveryNote(SellingController):
for f in fieldname:
toggle_print_hide(self.meta if key == "parent" else item_meta, f)
- super(DeliveryNote, self).before_print()
+ super(DeliveryNote, self).before_print(settings)
def set_actual_qty(self):
for d in self.get('items'):
From 4e07695a08a7fa7fe86f5d9babcb06c3546d25cd Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Wed, 31 Mar 2021 18:33:27 +0530
Subject: [PATCH 108/207] test: use insert instead of save (#25045)
* test: use insert instead of save
* test: use do_not_save
---
.../bank_transaction/test_bank_transaction.py | 36 +++++--------------
1 file changed, 8 insertions(+), 28 deletions(-)
diff --git a/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py b/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py
index 3b14e4efa0..17e39d562a 100644
--- a/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py
+++ b/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py
@@ -15,12 +15,14 @@ from erpnext.accounts.doctype.pos_profile.test_pos_profile import make_pos_profi
test_dependencies = ["Item", "Cost Center"]
class TestBankTransaction(unittest.TestCase):
- def setUp(self):
+ @classmethod
+ def setUpClass(cls):
make_pos_profile()
add_transactions()
add_vouchers()
- def tearDown(self):
+ @classmethod
+ def tearDownClass(cls):
for bt in frappe.get_all("Bank Transaction"):
doc = frappe.get_doc("Bank Transaction", bt.name)
doc.cancel()
@@ -33,9 +35,6 @@ class TestBankTransaction(unittest.TestCase):
# Delete POS Profile
frappe.db.sql("delete from `tabPOS Profile`")
- frappe.flags.test_bank_transactions_created = False
- frappe.flags.test_payments_created = False
-
# This test checks if ERPNext is able to provide a linked payment for a bank transaction based on the amount of the bank transaction.
def test_linked_payments(self):
bank_transaction = frappe.get_doc("Bank Transaction", dict(description="Re 95282925234 FE/000002917 AT171513000281183046 Conrad Electronic"))
@@ -44,8 +43,8 @@ class TestBankTransaction(unittest.TestCase):
# This test validates a simple reconciliation leading to the clearance of the bank transaction and the payment
def test_reconcile(self):
- bank_transaction = frappe.get_doc("Bank Transaction", dict(description="1512567 BG/000002918 OPSKATTUZWXXX AT776000000098709837 Herr G"))
- payment = frappe.get_doc("Payment Entry", dict(party="Mr G", paid_amount=1200))
+ bank_transaction = frappe.get_doc("Bank Transaction", dict(description="1512567 BG/000003025 OPSKATTUZWXXX AT776000000098709849 Herr G"))
+ payment = frappe.get_doc("Payment Entry", dict(party="Mr G", paid_amount=1700))
vouchers = json.dumps([{
"payment_doctype":"Payment Entry",
"payment_name":payment.name,
@@ -116,10 +115,6 @@ def create_bank_account(bank_name="Citi Bank", account_name="_Test Bank - _TC"):
pass
def add_transactions():
- if frappe.flags.test_bank_transactions_created:
- return
-
- frappe.set_user("Administrator")
create_bank_account()
doc = frappe.get_doc({
@@ -172,14 +167,8 @@ def add_transactions():
}).insert()
doc.submit()
- frappe.flags.test_bank_transactions_created = True
def add_vouchers():
- if frappe.flags.test_payments_created:
- return
-
- frappe.set_user("Administrator")
-
try:
frappe.get_doc({
"doctype": "Supplier",
@@ -272,13 +261,6 @@ def add_vouchers():
except frappe.DuplicateEntryError:
pass
- si = create_sales_invoice(customer="Fayva", qty=1, rate=109080)
- pe = get_payment_entry("Sales Invoice", si.name, bank_account="_Test Bank - _TC")
- pe.reference_no = "Fayva Oct 18"
- pe.reference_date = "2018-10-29"
- pe.insert()
- pe.submit()
-
mode_of_payment = frappe.get_doc({
"doctype": "Mode of Payment",
"name": "Cash"
@@ -291,14 +273,12 @@ def add_vouchers():
})
mode_of_payment.save()
- si = create_sales_invoice(customer="Fayva", qty=1, rate=109080, do_not_submit=1)
+ si = create_sales_invoice(customer="Fayva", qty=1, rate=109080, do_not_save=1)
si.is_pos = 1
si.append("payments", {
"mode_of_payment": "Cash",
"account": "_Test Bank - _TC",
"amount": 109080
})
- si.save()
+ si.insert()
si.submit()
-
- frappe.flags.test_payments_created = True
From 27f48739d47b20a6efc3495f071f69d46fee6beb Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Wed, 31 Mar 2021 18:49:03 +0530
Subject: [PATCH 109/207] test: pass force parameter to avoid LinkExistsError
(#25100)
---
.../doctype/plaid_settings/test_plaid_settings.py | 11 +++--------
1 file changed, 3 insertions(+), 8 deletions(-)
diff --git a/erpnext/erpnext_integrations/doctype/plaid_settings/test_plaid_settings.py b/erpnext/erpnext_integrations/doctype/plaid_settings/test_plaid_settings.py
index 3c906374c4..e2243eabde 100644
--- a/erpnext/erpnext_integrations/doctype/plaid_settings/test_plaid_settings.py
+++ b/erpnext/erpnext_integrations/doctype/plaid_settings/test_plaid_settings.py
@@ -23,14 +23,9 @@ class TestPlaidSettings(unittest.TestCase):
doc.cancel()
doc.delete()
- for ba in frappe.get_all("Bank Account"):
- frappe.get_doc("Bank Account", ba.name).delete()
-
- for at in frappe.get_all("Bank Account Type"):
- frappe.get_doc("Bank Account Type", at.name).delete()
-
- for ast in frappe.get_all("Bank Account Subtype"):
- frappe.get_doc("Bank Account Subtype", ast.name).delete()
+ for doctype in ("Bank Account", "Bank Account Type", "Bank Account Subtype"):
+ for d in frappe.get_all(doctype):
+ frappe.delete_doc(doctype, d.name, force=True)
def test_plaid_disabled(self):
frappe.db.set_value("Plaid Settings", None, "enabled", 0)
From fb9ce3f37bd1aa8e62a92bddffc99d6bd203ae9e Mon Sep 17 00:00:00 2001
From: Anuja P
Date: Wed, 31 Mar 2021 19:26:42 +0530
Subject: [PATCH 110/207] fix: Picked Qty conversion from Stock Qty to item Qty
in DN
---
erpnext/stock/doctype/pick_list/pick_list.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/stock/doctype/pick_list/pick_list.py b/erpnext/stock/doctype/pick_list/pick_list.py
index 61b72092e7..5e529f56ae 100644
--- a/erpnext/stock/doctype/pick_list/pick_list.py
+++ b/erpnext/stock/doctype/pick_list/pick_list.py
@@ -346,7 +346,7 @@ def create_delivery_note(source_name, target_doc=None):
if dn_item:
dn_item.warehouse = location.warehouse
- dn_item.qty = location.picked_qty
+ dn_item.qty = location.picked_qty / location.conversion_factor
dn_item.batch_no = location.batch_no
dn_item.serial_no = location.serial_no
From 1033cf72f6c66e91d07231e037bc744afcf0eaf2 Mon Sep 17 00:00:00 2001
From: Anupam Kumar
Date: Wed, 31 Mar 2021 19:39:45 +0530
Subject: [PATCH 111/207] fix: added flag for dont_fetch_price_list_rate in
transaction (#25041)
---
erpnext/public/js/controllers/transaction.js | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/erpnext/public/js/controllers/transaction.js b/erpnext/public/js/controllers/transaction.js
index 32d371d682..21a20a7bce 100644
--- a/erpnext/public/js/controllers/transaction.js
+++ b/erpnext/public/js/controllers/transaction.js
@@ -1167,6 +1167,11 @@ erpnext.TransactionController = erpnext.taxes_and_totals.extend({
this.calculate_net_weight();
}
+ // for handling customization not to fetch price list rate
+ if(frappe.flags.dont_fetch_price_list_rate) {
+ return
+ }
+
if (!dont_fetch_price_list_rate &&
frappe.meta.has_field(doc.doctype, "price_list_currency")) {
this.apply_price_list(item, true);
From 777745f1e07651c1c89afc1200bf2723125d277a Mon Sep 17 00:00:00 2001
From: Ankush Menat
Date: Tue, 30 Mar 2021 13:06:17 +0530
Subject: [PATCH 112/207] fix: do not fetch stopped MR in production plan
- Ignore stopped MR while using fetch button
- Add filter on field inside child table.
Related issue: ISS-20-21-10757
---
.../doctype/production_plan/production_plan.js | 12 +++++++++++-
.../doctype/production_plan/production_plan.py | 2 +-
2 files changed, 12 insertions(+), 2 deletions(-)
diff --git a/erpnext/manufacturing/doctype/production_plan/production_plan.js b/erpnext/manufacturing/doctype/production_plan/production_plan.js
index 15ec6209c1..288c1d0cd6 100644
--- a/erpnext/manufacturing/doctype/production_plan/production_plan.js
+++ b/erpnext/manufacturing/doctype/production_plan/production_plan.js
@@ -25,6 +25,16 @@ frappe.ui.form.on('Production Plan', {
}
});
+ frm.set_query('material_request', 'material_requests', function() {
+ return {
+ filters: {
+ material_request_type: "Manufacture",
+ docstatus: 1,
+ status: ["!=", "Stopped"],
+ }
+ };
+ });
+
frm.fields_dict['po_items'].grid.get_field('item_code').get_query = function(doc) {
return {
query: "erpnext.controllers.queries.item_query",
@@ -370,4 +380,4 @@ cur_frm.fields_dict['sales_orders'].grid.get_field("sales_order").get_query = fu
['Sales Order','docstatus', '=' ,1]
]
}
-};
\ No newline at end of file
+};
diff --git a/erpnext/manufacturing/doctype/production_plan/production_plan.py b/erpnext/manufacturing/doctype/production_plan/production_plan.py
index 05b328c9e8..cef2d8be7a 100644
--- a/erpnext/manufacturing/doctype/production_plan/production_plan.py
+++ b/erpnext/manufacturing/doctype/production_plan/production_plan.py
@@ -70,7 +70,7 @@ class ProductionPlan(Document):
from `tabMaterial Request` mr, `tabMaterial Request Item` mr_item
where mr_item.parent = mr.name
and mr.material_request_type = "Manufacture"
- and mr.docstatus = 1 and mr.company = %(company)s
+ and mr.docstatus = 1 and mr.status != "Stopped" and mr.company = %(company)s
and mr_item.qty > ifnull(mr_item.ordered_qty,0) {0} {1}
and (exists (select name from `tabBOM` bom where bom.item=mr_item.item_code
and bom.is_active = 1))
From 2d86eb3ab14bfc243fc158fef5c008f8f5095e1d Mon Sep 17 00:00:00 2001
From: Deepesh Garg
Date: Wed, 31 Mar 2021 19:57:50 +0530
Subject: [PATCH 113/207] fix: Hide serial and batch selector in Stock Entry
---
erpnext/stock/doctype/stock_entry/stock_entry.js | 10 +++++++++-
1 file changed, 9 insertions(+), 1 deletion(-)
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.js b/erpnext/stock/doctype/stock_entry/stock_entry.js
index 64dcbed1d8..bdd572d3a5 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.js
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.js
@@ -100,6 +100,13 @@ frappe.ui.form.on('Stock Entry', {
frm.add_fetch("bom_no", "inspection_required", "inspection_required");
erpnext.accounts.dimensions.setup_dimension_filters(frm, frm.doctype);
+
+ frappe.db.get_single_value('Stock Settings', 'disable_serial_no_and_batch_selector')
+ .then((value) => {
+ if (value) {
+ frappe.flags.hide_serial_batch_dialog = true;
+ }
+ });
},
setup_quality_inspection: function(frm) {
@@ -721,7 +728,8 @@ frappe.ui.form.on('Stock Entry Detail', {
no_batch_serial_number_value = !d.batch_no;
}
- if (no_batch_serial_number_value) {
+ console.log(frappe.flags.hide_serial_batch_dialog, "$#$#$#");
+ if (no_batch_serial_number_value && !frappe.flags.hide_serial_batch_dialog) {
erpnext.stock.select_batch_and_serial_no(frm, d);
}
}
From a1d09320936e3b32d422e5b639994dad9c866de2 Mon Sep 17 00:00:00 2001
From: Anuja P
Date: Wed, 31 Mar 2021 19:59:28 +0530
Subject: [PATCH 114/207] fix: suggested changes
---
erpnext/stock/doctype/pick_list/pick_list.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/stock/doctype/pick_list/pick_list.py b/erpnext/stock/doctype/pick_list/pick_list.py
index 5e529f56ae..755fa615bb 100644
--- a/erpnext/stock/doctype/pick_list/pick_list.py
+++ b/erpnext/stock/doctype/pick_list/pick_list.py
@@ -346,7 +346,7 @@ def create_delivery_note(source_name, target_doc=None):
if dn_item:
dn_item.warehouse = location.warehouse
- dn_item.qty = location.picked_qty / location.conversion_factor
+ 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
From 9f7bb14ea1f1d527b57abf9d452b29eb09fe8783 Mon Sep 17 00:00:00 2001
From: Deepesh Garg
Date: Wed, 31 Mar 2021 20:01:00 +0530
Subject: [PATCH 115/207] fix: Remove console
---
erpnext/stock/doctype/stock_entry/stock_entry.js | 1 -
1 file changed, 1 deletion(-)
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.js b/erpnext/stock/doctype/stock_entry/stock_entry.js
index bdd572d3a5..98246fb024 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.js
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.js
@@ -728,7 +728,6 @@ frappe.ui.form.on('Stock Entry Detail', {
no_batch_serial_number_value = !d.batch_no;
}
- console.log(frappe.flags.hide_serial_batch_dialog, "$#$#$#");
if (no_batch_serial_number_value && !frappe.flags.hide_serial_batch_dialog) {
erpnext.stock.select_batch_and_serial_no(frm, d);
}
From 7665a85039ff664d57f931f55c066493a47f2942 Mon Sep 17 00:00:00 2001
From: marination
Date: Wed, 31 Mar 2021 21:03:55 +0530
Subject: [PATCH 116/207] fix: Run Patches to updated Reserved, Requested and
Ordered Qty
---
erpnext/patches.txt | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 69c5a37b15..aabefb85e7 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -99,7 +99,7 @@ execute:frappe.delete_doc("DocType", "Purchase Request")
execute:frappe.delete_doc("DocType", "Purchase Request Item")
erpnext.patches.v4_2.recalculate_bom_cost
erpnext.patches.v4_2.fix_gl_entries_for_stock_transactions
-erpnext.patches.v4_2.update_requested_and_ordered_qty
+erpnext.patches.v4_2.update_requested_and_ordered_qty #2021-03-31
execute:frappe.rename_doc("DocType", "Support Ticket", "Issue", force=True)
erpnext.patches.v4_4.make_email_accounts
execute:frappe.delete_doc("DocType", "Contact Control")
@@ -208,7 +208,7 @@ erpnext.patches.v5_7.update_item_description_based_on_item_master
erpnext.patches.v5_7.item_template_attributes
execute:frappe.delete_doc_if_exists("DocType", "Manage Variants")
execute:frappe.delete_doc_if_exists("DocType", "Manage Variants Item")
-erpnext.patches.v4_2.repost_reserved_qty #2016-04-15
+erpnext.patches.v4_2.repost_reserved_qty #2021-03-31
erpnext.patches.v5_4.update_purchase_cost_against_project
erpnext.patches.v5_8.update_order_reference_in_return_entries
erpnext.patches.v5_8.add_credit_note_print_heading
From f3c34aa6aeb68521e375c2517a02ed171f9ebbb3 Mon Sep 17 00:00:00 2001
From: Prssanna Desai
Date: Wed, 31 Mar 2021 21:52:48 +0530
Subject: [PATCH 117/207] fix: don't set "Company:company:default_currency" as
default for currency link fields (#25095)
* fix: don't set Company:company:default_currency as default for currency link fields
* fix: Company:company:default_currency and refactor
Co-authored-by: Afshan <33727827+AfshanKhan@users.noreply.github.com>
Co-authored-by: Afshan
---
.../employee_advance/employee_advance.json | 3 +--
.../leave_encashment/leave_encashment.json | 3 +--
.../additional_salary/additional_salary.json | 3 +--
.../employee_benefit_application.json | 3 +--
.../employee_benefit_claim.js | 1 -
.../employee_benefit_claim.json | 5 ++--
.../employee_incentive.json | 3 +--
.../employee_tax_exemption_declaration.js | 21 +++++++++++++++++
.../employee_tax_exemption_declaration.json | 4 ++--
...employee_tax_exemption_proof_submission.js | 23 ++++++++++++++++++-
...ployee_tax_exemption_proof_submission.json | 4 ++--
.../income_tax_slab/income_tax_slab.json | 4 ++--
.../retention_bonus/retention_bonus.json | 3 +--
.../doctype/salary_slip/salary_slip.json | 3 +--
.../salary_structure/salary_structure.json | 2 +-
.../salary_structure_assignment.json | 3 +--
16 files changed, 60 insertions(+), 28 deletions(-)
diff --git a/erpnext/hr/doctype/employee_advance/employee_advance.json b/erpnext/hr/doctype/employee_advance/employee_advance.json
index cf6b5404ec..04f98d1441 100644
--- a/erpnext/hr/doctype/employee_advance/employee_advance.json
+++ b/erpnext/hr/doctype/employee_advance/employee_advance.json
@@ -181,7 +181,6 @@
"read_only": 1
},
{
- "default": "Company:company:default_currency",
"depends_on": "eval:(doc.docstatus==1 || doc.employee)",
"fieldname": "currency",
"fieldtype": "Link",
@@ -201,7 +200,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2020-11-25 12:01:55.980721",
+ "modified": "2021-03-31 14:42:47.321368",
"modified_by": "Administrator",
"module": "HR",
"name": "Employee Advance",
diff --git a/erpnext/hr/doctype/leave_encashment/leave_encashment.json b/erpnext/hr/doctype/leave_encashment/leave_encashment.json
index 83eeae3adb..dcb587407d 100644
--- a/erpnext/hr/doctype/leave_encashment/leave_encashment.json
+++ b/erpnext/hr/doctype/leave_encashment/leave_encashment.json
@@ -130,7 +130,6 @@
"read_only": 1
},
{
- "default": "Company:company:default_currency",
"depends_on": "eval:(doc.docstatus==1 || doc.employee)",
"fieldname": "currency",
"fieldtype": "Link",
@@ -155,7 +154,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2020-11-25 11:56:06.777241",
+ "modified": "2021-03-31 14:45:27.948207",
"modified_by": "Administrator",
"module": "HR",
"name": "Leave Encashment",
diff --git a/erpnext/payroll/doctype/additional_salary/additional_salary.json b/erpnext/payroll/doctype/additional_salary/additional_salary.json
index 2b29f667fb..61ae7e4c2f 100644
--- a/erpnext/payroll/doctype/additional_salary/additional_salary.json
+++ b/erpnext/payroll/doctype/additional_salary/additional_salary.json
@@ -163,7 +163,6 @@
"read_only": 1
},
{
- "default": "Company:company:default_currency",
"depends_on": "eval:(doc.docstatus==1 || doc.employee)",
"fieldname": "currency",
"fieldtype": "Link",
@@ -176,7 +175,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2020-10-20 17:51:13.419716",
+ "modified": "2021-03-31 14:45:48.566756",
"modified_by": "Administrator",
"module": "Payroll",
"name": "Additional Salary",
diff --git a/erpnext/payroll/doctype/employee_benefit_application/employee_benefit_application.json b/erpnext/payroll/doctype/employee_benefit_application/employee_benefit_application.json
index 4c45580bf0..c6f764ccdb 100644
--- a/erpnext/payroll/doctype/employee_benefit_application/employee_benefit_application.json
+++ b/erpnext/payroll/doctype/employee_benefit_application/employee_benefit_application.json
@@ -124,7 +124,6 @@
"read_only": 1
},
{
- "default": "Company:company:default_currency",
"depends_on": "eval:(doc.docstatus==1 || doc.employee)",
"fieldname": "currency",
"fieldtype": "Link",
@@ -148,7 +147,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2020-12-14 15:52:08.566418",
+ "modified": "2021-03-31 14:46:22.465521",
"modified_by": "Administrator",
"module": "Payroll",
"name": "Employee Benefit Application",
diff --git a/erpnext/payroll/doctype/employee_benefit_claim/employee_benefit_claim.js b/erpnext/payroll/doctype/employee_benefit_claim/employee_benefit_claim.js
index ea9ccd5205..e1f8431ec5 100644
--- a/erpnext/payroll/doctype/employee_benefit_claim/employee_benefit_claim.js
+++ b/erpnext/payroll/doctype/employee_benefit_claim/employee_benefit_claim.js
@@ -21,7 +21,6 @@ frappe.ui.form.on('Employee Benefit Claim', {
callback: function(r) {
if (r.message) {
frm.set_value('currency', r.message);
- frm.set_df_property('currency', 'hidden', 0);
}
}
});
diff --git a/erpnext/payroll/doctype/employee_benefit_claim/employee_benefit_claim.json b/erpnext/payroll/doctype/employee_benefit_claim/employee_benefit_claim.json
index da24aacda1..e331b7af93 100644
--- a/erpnext/payroll/doctype/employee_benefit_claim/employee_benefit_claim.json
+++ b/erpnext/payroll/doctype/employee_benefit_claim/employee_benefit_claim.json
@@ -125,10 +125,9 @@
"label": "Attachments"
},
{
- "default": "Company:company:default_currency",
+ "depends_on": "eval: doc.employee",
"fieldname": "currency",
"fieldtype": "Link",
- "hidden": 1,
"label": "Currency",
"options": "Currency",
"read_only": 1,
@@ -145,7 +144,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2020-11-25 11:49:56.097352",
+ "modified": "2021-03-31 15:51:51.489269",
"modified_by": "Administrator",
"module": "Payroll",
"name": "Employee Benefit Claim",
diff --git a/erpnext/payroll/doctype/employee_incentive/employee_incentive.json b/erpnext/payroll/doctype/employee_incentive/employee_incentive.json
index e5b1052b3a..51346c6c7d 100644
--- a/erpnext/payroll/doctype/employee_incentive/employee_incentive.json
+++ b/erpnext/payroll/doctype/employee_incentive/employee_incentive.json
@@ -75,7 +75,6 @@
"reqd": 1
},
{
- "default": "Company:company:default_currency",
"depends_on": "eval:(doc.docstatus==1 || doc.employee)",
"fieldname": "currency",
"fieldtype": "Link",
@@ -95,7 +94,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2020-10-20 17:22:16.468042",
+ "modified": "2021-03-31 14:48:00.919839",
"modified_by": "Administrator",
"module": "Payroll",
"name": "Employee Incentive",
diff --git a/erpnext/payroll/doctype/employee_tax_exemption_declaration/employee_tax_exemption_declaration.js b/erpnext/payroll/doctype/employee_tax_exemption_declaration/employee_tax_exemption_declaration.js
index 0e0c9b5a1a..fb11875e96 100644
--- a/erpnext/payroll/doctype/employee_tax_exemption_declaration/employee_tax_exemption_declaration.js
+++ b/erpnext/payroll/doctype/employee_tax_exemption_declaration/employee_tax_exemption_declaration.js
@@ -47,5 +47,26 @@ frappe.ui.form.on('Employee Tax Exemption Declaration', {
});
}).addClass("btn-primary");
}
+ },
+
+ employee: function(frm) {
+ if (frm.doc.employee) {
+ frm.trigger('get_employee_currency');
+ }
+ },
+
+ get_employee_currency: function(frm) {
+ frappe.call({
+ method: "erpnext.payroll.doctype.salary_structure_assignment.salary_structure_assignment.get_employee_currency",
+ args: {
+ employee: frm.doc.employee,
+ },
+ callback: function(r) {
+ if (r.message) {
+ frm.set_value('currency', r.message);
+ frm.refresh_fields();
+ }
+ }
+ });
}
});
diff --git a/erpnext/payroll/doctype/employee_tax_exemption_declaration/employee_tax_exemption_declaration.json b/erpnext/payroll/doctype/employee_tax_exemption_declaration/employee_tax_exemption_declaration.json
index 83d4ae53df..873bf887bf 100644
--- a/erpnext/payroll/doctype/employee_tax_exemption_declaration/employee_tax_exemption_declaration.json
+++ b/erpnext/payroll/doctype/employee_tax_exemption_declaration/employee_tax_exemption_declaration.json
@@ -108,7 +108,7 @@
"read_only": 1
},
{
- "default": "Company:company:default_currency",
+ "depends_on": "eval: doc.employee",
"fieldname": "currency",
"fieldtype": "Link",
"label": "Currency",
@@ -119,7 +119,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2020-10-20 16:42:24.493761",
+ "modified": "2021-03-31 20:41:57.387749",
"modified_by": "Administrator",
"module": "Payroll",
"name": "Employee Tax Exemption Declaration",
diff --git a/erpnext/payroll/doctype/employee_tax_exemption_proof_submission/employee_tax_exemption_proof_submission.js b/erpnext/payroll/doctype/employee_tax_exemption_proof_submission/employee_tax_exemption_proof_submission.js
index 497f35c41e..4fb0a3771e 100644
--- a/erpnext/payroll/doctype/employee_tax_exemption_proof_submission/employee_tax_exemption_proof_submission.js
+++ b/erpnext/payroll/doctype/employee_tax_exemption_proof_submission/employee_tax_exemption_proof_submission.js
@@ -58,5 +58,26 @@ frappe.ui.form.on('Employee Tax Exemption Proof Submission', {
currency: function(frm) {
frm.refresh_fields();
- }
+ },
+
+ employee: function(frm) {
+ if (frm.doc.employee) {
+ frm.trigger('get_employee_currency');
+ }
+ },
+
+ get_employee_currency: function(frm) {
+ frappe.call({
+ method: "erpnext.payroll.doctype.salary_structure_assignment.salary_structure_assignment.get_employee_currency",
+ args: {
+ employee: frm.doc.employee,
+ },
+ callback: function(r) {
+ if (r.message) {
+ frm.set_value('currency', r.message);
+ frm.refresh_fields();
+ }
+ }
+ });
+ },
});
diff --git a/erpnext/payroll/doctype/employee_tax_exemption_proof_submission/employee_tax_exemption_proof_submission.json b/erpnext/payroll/doctype/employee_tax_exemption_proof_submission/employee_tax_exemption_proof_submission.json
index 53f18cb1fe..f32202a3bd 100644
--- a/erpnext/payroll/doctype/employee_tax_exemption_proof_submission/employee_tax_exemption_proof_submission.json
+++ b/erpnext/payroll/doctype/employee_tax_exemption_proof_submission/employee_tax_exemption_proof_submission.json
@@ -131,7 +131,7 @@
"read_only": 1
},
{
- "default": "Company:company:default_currency",
+ "depends_on": "eval: doc.employee",
"fieldname": "currency",
"fieldtype": "Link",
"label": "Currency",
@@ -142,7 +142,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2020-10-20 16:47:03.410020",
+ "modified": "2021-03-31 20:48:32.639885",
"modified_by": "Administrator",
"module": "Payroll",
"name": "Employee Tax Exemption Proof Submission",
diff --git a/erpnext/payroll/doctype/income_tax_slab/income_tax_slab.json b/erpnext/payroll/doctype/income_tax_slab/income_tax_slab.json
index 9fa261dea2..c343a44326 100644
--- a/erpnext/payroll/doctype/income_tax_slab/income_tax_slab.json
+++ b/erpnext/payroll/doctype/income_tax_slab/income_tax_slab.json
@@ -93,7 +93,7 @@
"options": "Income Tax Slab Other Charges"
},
{
- "default": "Company:company:default_currency",
+ "fetch_from": "company.default_currency",
"fieldname": "currency",
"fieldtype": "Link",
"label": "Currency",
@@ -104,7 +104,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2020-10-19 13:54:24.728075",
+ "modified": "2021-03-31 20:53:33.323712",
"modified_by": "Administrator",
"module": "Payroll",
"name": "Income Tax Slab",
diff --git a/erpnext/payroll/doctype/retention_bonus/retention_bonus.json b/erpnext/payroll/doctype/retention_bonus/retention_bonus.json
index 6647230078..cd563bc404 100644
--- a/erpnext/payroll/doctype/retention_bonus/retention_bonus.json
+++ b/erpnext/payroll/doctype/retention_bonus/retention_bonus.json
@@ -93,7 +93,6 @@
"reqd": 1
},
{
- "default": "Company:company:default_currency",
"depends_on": "eval:(doc.docstatus==1 || doc.employee)",
"fieldname": "currency",
"fieldtype": "Link",
@@ -106,7 +105,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2020-10-20 17:27:47.003134",
+ "modified": "2021-03-31 14:50:29.401020",
"modified_by": "Administrator",
"module": "Payroll",
"name": "Retention Bonus",
diff --git a/erpnext/payroll/doctype/salary_slip/salary_slip.json b/erpnext/payroll/doctype/salary_slip/salary_slip.json
index 6688368262..ec5607602d 100644
--- a/erpnext/payroll/doctype/salary_slip/salary_slip.json
+++ b/erpnext/payroll/doctype/salary_slip/salary_slip.json
@@ -500,7 +500,6 @@
"fieldtype": "Column Break"
},
{
- "default": "Company:company:default_currency",
"depends_on": "eval:(doc.docstatus==1 || doc.salary_structure)",
"fetch_from": "salary_structure.currency",
"fieldname": "currency",
@@ -632,7 +631,7 @@
"idx": 9,
"is_submittable": 1,
"links": [],
- "modified": "2021-02-19 11:48:05.383945",
+ "modified": "2021-03-31 15:39:28.817166",
"modified_by": "Administrator",
"module": "Payroll",
"name": "Salary Slip",
diff --git a/erpnext/payroll/doctype/salary_structure/salary_structure.json b/erpnext/payroll/doctype/salary_structure/salary_structure.json
index de56fc8457..5dd1d701f0 100644
--- a/erpnext/payroll/doctype/salary_structure/salary_structure.json
+++ b/erpnext/payroll/doctype/salary_structure/salary_structure.json
@@ -232,7 +232,7 @@
"idx": 1,
"is_submittable": 1,
"links": [],
- "modified": "2020-09-30 11:30:32.190798",
+ "modified": "2021-03-31 15:41:12.342380",
"modified_by": "Administrator",
"module": "Payroll",
"name": "Salary Structure",
diff --git a/erpnext/payroll/doctype/salary_structure_assignment/salary_structure_assignment.json b/erpnext/payroll/doctype/salary_structure_assignment/salary_structure_assignment.json
index 92bb347661..50fabedb42 100644
--- a/erpnext/payroll/doctype/salary_structure_assignment/salary_structure_assignment.json
+++ b/erpnext/payroll/doctype/salary_structure_assignment/salary_structure_assignment.json
@@ -125,7 +125,6 @@
"options": "Income Tax Slab"
},
{
- "default": "Company:company:default_currency",
"depends_on": "eval:(doc.docstatus==1 || doc.salary_structure)",
"fetch_from": "salary_structure.currency",
"fieldname": "currency",
@@ -146,7 +145,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2020-11-30 18:07:48.251311",
+ "modified": "2021-03-31 15:49:36.361253",
"modified_by": "Administrator",
"module": "Payroll",
"name": "Salary Structure Assignment",
From 825850a58ff2e8150d1eca4ad0c8faffd04fdbeb Mon Sep 17 00:00:00 2001
From: Rohit Waghchaure
Date: Wed, 31 Mar 2021 23:55:06 +0530
Subject: [PATCH 118/207] fix: not able to save material request
---
erpnext/stock/doctype/material_request/material_request.js | 4 ++++
.../stock/doctype/material_request/material_request.json | 6 +++---
2 files changed, 7 insertions(+), 3 deletions(-)
diff --git a/erpnext/stock/doctype/material_request/material_request.js b/erpnext/stock/doctype/material_request/material_request.js
index 527b0d3ea9..7dfc5da50d 100644
--- a/erpnext/stock/doctype/material_request/material_request.js
+++ b/erpnext/stock/doctype/material_request/material_request.js
@@ -354,6 +354,10 @@ frappe.ui.form.on('Material Request', {
},
material_request_type: function(frm) {
frm.toggle_reqd('customer', frm.doc.material_request_type=="Customer Provided");
+
+ if (frm.doc.material_request_type !== 'Material Transfer' && frm.doc.set_from_warehouse) {
+ frm.set_value('set_from_warehouse', '');
+ }
},
});
diff --git a/erpnext/stock/doctype/material_request/material_request.json b/erpnext/stock/doctype/material_request/material_request.json
index d73349dd39..8d7b238c17 100644
--- a/erpnext/stock/doctype/material_request/material_request.json
+++ b/erpnext/stock/doctype/material_request/material_request.json
@@ -20,9 +20,9 @@
"company",
"amended_from",
"warehouse_section",
- "set_warehouse",
- "column_break5",
"set_from_warehouse",
+ "column_break5",
+ "set_warehouse",
"items_section",
"scan_barcode",
"items",
@@ -314,7 +314,7 @@
"idx": 70,
"is_submittable": 1,
"links": [],
- "modified": "2020-09-19 01:04:09.285862",
+ "modified": "2021-03-31 23:52:55.392512",
"modified_by": "Administrator",
"module": "Stock",
"name": "Material Request",
From 4198cf58e55d7ba7b4e79e0a3ff220ef9ddd5382 Mon Sep 17 00:00:00 2001
From: Ankush Menat
Date: Wed, 31 Mar 2021 21:02:16 +0530
Subject: [PATCH 119/207] test: add tests for PO->PI, PO->PR workflow
Add failing test cases for PR status and PR percent billed.
---
.../purchase_receipt/test_purchase_receipt.py | 53 ++++++++++++++++++-
1 file changed, 52 insertions(+), 1 deletion(-)
diff --git a/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
index 7741ee7f60..7f0c3fa801 100644
--- a/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
@@ -191,7 +191,7 @@ class TestPurchaseReceipt(unittest.TestCase):
rm_supp_cost = sum([d.amount for d in pr.get("supplied_items")])
self.assertEqual(pr.get("items")[0].rm_supp_cost, flt(rm_supp_cost, 2))
-
+
pr.cancel()
def test_subcontracting_gle_fg_item_rate_zero(self):
@@ -912,6 +912,57 @@ class TestPurchaseReceipt(unittest.TestCase):
ste1.cancel()
po.cancel()
+
+ def test_po_to_pi_and_po_to_pr_worflow_full(self):
+ """Test following behaviour:
+ - Create PO
+ - Create PI from PO and submit
+ - Create PR from PO and submit
+ """
+ from erpnext.buying.doctype.purchase_order import test_purchase_order
+ from erpnext.buying.doctype.purchase_order import purchase_order
+
+ po = test_purchase_order.create_purchase_order()
+
+ pi = purchase_order.make_purchase_invoice(po.name)
+ pi.submit()
+
+ pr = purchase_order.make_purchase_receipt(po.name)
+ pr.submit()
+
+ pr.load_from_db()
+
+ self.assertEqual(pr.status, "Completed")
+ self.assertEqual(pr.per_billed, 100)
+
+ def test_po_to_pi_and_po_to_pr_worflow_partial(self):
+ """Test following behaviour:
+ - Create PO
+ - Create partial PI from PO and submit
+ - Create PR from PO and submit
+ """
+ from erpnext.buying.doctype.purchase_order import test_purchase_order
+ from erpnext.buying.doctype.purchase_order import purchase_order
+
+ po = test_purchase_order.create_purchase_order()
+
+ pi = purchase_order.make_purchase_invoice(po.name)
+ pi.items[0].qty /= 2 # roughly 50%, ^ this function only creates PI with 1 item.
+ pi.submit()
+
+ pr = purchase_order.make_purchase_receipt(po.name)
+ pr.save()
+ # per_billed is only updated after submission.
+ self.assertEqual(flt(pr.per_billed), 0)
+
+ pr.submit()
+
+ pi.load_from_db()
+ pr.load_from_db()
+
+ self.assertEqual(pr.status, "To Bill")
+ self.assertAlmostEqual(pr.per_billed, 50.0, places=2)
+
def get_sl_entries(voucher_type, voucher_no):
return frappe.db.sql(""" select actual_qty, warehouse, stock_value_difference
from `tabStock Ledger Entry` where voucher_type=%s and voucher_no=%s
From 8993ccb7d20e8a6fade8f6cccf5b7977f0442a79 Mon Sep 17 00:00:00 2001
From: Ankush Menat
Date: Wed, 31 Mar 2021 17:05:00 +0530
Subject: [PATCH 120/207] fix: update PR status in database
---
erpnext/stock/doctype/purchase_receipt/purchase_receipt.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
index 70687bdac2..5d7597b2db 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -176,7 +176,7 @@ class PurchaseReceipt(BuyingController):
if flt(self.per_billed) < 100:
self.update_billing_status()
else:
- self.status = "Completed"
+ self.db_set("status", "Completed")
# Updating stock ledger should always be called after updating prevdoc status,
From 427a98d6cdb4de5c763646b248f284aeb39725e7 Mon Sep 17 00:00:00 2001
From: Ankush Menat
Date: Wed, 31 Mar 2021 18:45:18 +0530
Subject: [PATCH 121/207] fix: do not copy percent billed from PO to PR
---
erpnext/buying/doctype/purchase_order/purchase_order.py | 1 -
1 file changed, 1 deletion(-)
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.py b/erpnext/buying/doctype/purchase_order/purchase_order.py
index 90d064604e..ef9372eeb6 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.py
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.py
@@ -368,7 +368,6 @@ def make_purchase_receipt(source_name, target_doc=None):
"Purchase Order": {
"doctype": "Purchase Receipt",
"field_map": {
- "per_billed": "per_billed",
"supplier_warehouse":"supplier_warehouse"
},
"validation": {
From 1bdf9c4161fbf3c40e5ea9e229e27270700c91ce Mon Sep 17 00:00:00 2001
From: Ankush Menat
Date: Wed, 31 Mar 2021 22:06:05 +0530
Subject: [PATCH 122/207] fix: patch for purchase receipt status
---
erpnext/patches.txt | 1 +
.../patches/v12_0/purchase_receipt_status.py | 30 +++++++++++++++++++
2 files changed, 31 insertions(+)
create mode 100644 erpnext/patches/v12_0/purchase_receipt_status.py
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index aabefb85e7..16863142bc 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -763,3 +763,4 @@ erpnext.patches.v13_0.setup_gratuity_rule_for_india_and_uae
erpnext.patches.v13_0.setup_uae_vat_fields
execute:frappe.db.set_value('System Settings', None, 'app_name', 'ERPNext')
erpnext.patches.v13_0.rename_discharge_date_in_ip_record
+erpnext.patches.v12_0.purchase_receipt_status
diff --git a/erpnext/patches/v12_0/purchase_receipt_status.py b/erpnext/patches/v12_0/purchase_receipt_status.py
new file mode 100644
index 0000000000..1a99b3163b
--- /dev/null
+++ b/erpnext/patches/v12_0/purchase_receipt_status.py
@@ -0,0 +1,30 @@
+""" This patch fixes old purchase receipts (PR) where even after submitting
+ the PR, the `status` remains "Draft". `per_billed` field was copied over from previous
+ doc (PO), hence it is recalculated for setting new correct status of PR.
+"""
+
+import frappe
+
+logger = frappe.logger("patch", allow_site=True, file_count=50)
+
+def execute():
+ affected_purchase_receipts = frappe.db.sql(
+ """select name from `tabPurchase Receipt`
+ where status = 'Draft' and per_billed = 100 and docstatus = 1"""
+ )
+
+ if not affected_purchase_receipts:
+ return
+
+ logger.info("purchase_receipt_status: begin patch, PR count: {}"
+ .format(len(affected_purchase_receipts)))
+
+
+ for pr in affected_purchase_receipts:
+ pr_name = pr[0]
+ logger.info("purchase_receipt_status: patching PR - {}".format(pr_name))
+
+ pr_doc = frappe.get_doc("Purchase Receipt", pr_name)
+
+ pr_doc.update_billing_status(update_modified=False)
+ pr_doc.set_status(update=True, update_modified=False)
From 561fa6b53019b064764019aacf36b2ddd3e86c0e Mon Sep 17 00:00:00 2001
From: marination
Date: Thu, 1 Apr 2021 12:53:22 +0530
Subject: [PATCH 123/207] fix: Don't string format args as they may not be
escaped properly
- Append even conditional args to args list and send to query executer
- It will escape all values that are sent to it
- String formatting without escaping causes issues with % sign, etc.
---
.../doctype/quality_inspection/quality_inspection.py | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
diff --git a/erpnext/stock/doctype/quality_inspection/quality_inspection.py b/erpnext/stock/doctype/quality_inspection/quality_inspection.py
index 05819ab854..469511af60 100644
--- a/erpnext/stock/doctype/quality_inspection/quality_inspection.py
+++ b/erpnext/stock/doctype/quality_inspection/quality_inspection.py
@@ -64,17 +64,21 @@ class QualityInspection(Document):
(quality_inspection, self.modified, self.reference_name, self.item_code))
else:
+ args = [quality_inspection, self.modified, self.reference_name, self.item_code]
doctype = self.reference_type + ' Item'
+
if self.reference_type == 'Stock Entry':
doctype = 'Stock Entry Detail'
if self.reference_type and self.reference_name:
conditions = ""
if self.batch_no and self.docstatus == 1:
- conditions += " and t1.batch_no = '%s'"%(self.batch_no)
+ conditions += " and t1.batch_no = %s"
+ args.append(self.batch_no)
if self.docstatus == 2: # if cancel, then remove qi link wherever same name
- conditions += " and t1.quality_inspection = '%s'"%(self.name)
+ conditions += " and t1.quality_inspection = %s"
+ args.append(self.name)
frappe.db.sql("""
UPDATE
@@ -87,7 +91,7 @@ class QualityInspection(Document):
and t1.parent = t2.name
{conditions}
""".format(parent_doc=self.reference_type, child_doc=doctype, conditions=conditions),
- (quality_inspection, self.modified, self.reference_name, self.item_code))
+ args)
def inspect_and_set_status(self):
for reading in self.readings:
From 53a1aaf33decc4b83ff414c459509287639bd1de Mon Sep 17 00:00:00 2001
From: Rucha Mahabal
Date: Thu, 1 Apr 2021 14:40:15 +0530
Subject: [PATCH 124/207] fix: Salary Structure object has no attribute
set_totals (#25113)
---
erpnext/payroll/doctype/salary_slip/salary_slip.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/payroll/doctype/salary_slip/salary_slip.js b/erpnext/payroll/doctype/salary_slip/salary_slip.js
index d5278393a1..3e8a213ca9 100644
--- a/erpnext/payroll/doctype/salary_slip/salary_slip.js
+++ b/erpnext/payroll/doctype/salary_slip/salary_slip.js
@@ -216,7 +216,7 @@ frappe.ui.form.on('Salary Slip Timesheet', {
});
var set_totals = function(frm) {
- if (frm.doc.docstatus === 0) {
+ if (frm.doc.docstatus === 0 && frm.doc.doctype === "Salary Slip") {
if (frm.doc.earnings || frm.doc.deductions) {
frappe.call({
method: "set_totals",
From 4c31fbb687aa5d6cc1e199e07c4941a2b585f5e3 Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Thu, 1 Apr 2021 15:32:37 +0530
Subject: [PATCH 125/207] fix(India): create property setters for shorter
naming series (as per GST Rules) (#25128)
---
erpnext/accounts/doctype/sales_invoice/test_records.json | 8 ++++----
.../accounts/doctype/sales_invoice/test_sales_invoice.py | 1 +
erpnext/regional/india/setup.py | 9 ++++++++-
3 files changed, 13 insertions(+), 5 deletions(-)
diff --git a/erpnext/accounts/doctype/sales_invoice/test_records.json b/erpnext/accounts/doctype/sales_invoice/test_records.json
index e00a58f864..3781f8ccc9 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_records.json
+++ b/erpnext/accounts/doctype/sales_invoice/test_records.json
@@ -31,7 +31,7 @@
"base_grand_total": 561.8,
"grand_total": 561.8,
"is_pos": 0,
- "naming_series": "_T-Sales Invoice-",
+ "naming_series": "T-SINV-",
"base_net_total": 500.0,
"taxes": [
{
@@ -104,7 +104,7 @@
"base_grand_total": 630.0,
"grand_total": 630.0,
"is_pos": 0,
- "naming_series": "_T-Sales Invoice-",
+ "naming_series": "T-SINV-",
"base_net_total": 500.0,
"taxes": [
{
@@ -175,7 +175,7 @@
],
"grand_total": 0,
"is_pos": 0,
- "naming_series": "_T-Sales Invoice-",
+ "naming_series": "T-SINV-",
"taxes": [
{
"account_head": "_Test Account Shipping Charges - _TC",
@@ -301,7 +301,7 @@
],
"grand_total": 0,
"is_pos": 0,
- "naming_series": "_T-Sales Invoice-",
+ "naming_series": "T-SINV-",
"taxes": [
{
"account_head": "_Test Account Excise Duty - _TC",
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index 90e21444f5..f09cc5af96 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -2115,6 +2115,7 @@ def create_sales_invoice(**args):
si.return_against = args.return_against
si.currency=args.currency or "INR"
si.conversion_rate = args.conversion_rate or 1
+ si.naming_series = args.naming_series or "T-SINV-"
si.append("items", {
"item_code": args.item or args.item_code or "_Test Item",
diff --git a/erpnext/regional/india/setup.py b/erpnext/regional/india/setup.py
index ee49aae050..f7689cfa19 100644
--- a/erpnext/regional/india/setup.py
+++ b/erpnext/regional/india/setup.py
@@ -5,6 +5,7 @@ from __future__ import unicode_literals
import frappe, os, json
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
+from frappe.custom.doctype.property_setter.property_setter import make_property_setter
from frappe.permissions import add_permission, update_permission_property
from erpnext.regional.india import states
from erpnext.accounts.utils import get_fiscal_year, FiscalYearError
@@ -18,6 +19,7 @@ def setup(company=None, patch=True):
# TODO: for all countries
def setup_company_independent_fixtures():
make_custom_fields()
+ make_property_setters()
add_permissions()
add_custom_roles_for_reports()
frappe.enqueue('erpnext.regional.india.setup.add_hsn_sac_codes', now=frappe.flags.in_test)
@@ -110,6 +112,11 @@ def add_print_formats():
frappe.db.set_value("Print Format", "GST Tax Invoice", "disabled", 0)
frappe.db.set_value("Print Format", "GST E-Invoice", "disabled", 0)
+def make_property_setters():
+ # GST rules do not allow for an invoice no. bigger than 16 characters
+ make_property_setter('Sales Invoice', 'naming_series', 'options', 'SINV-.YY.-\nSRET-.YY.-', '')
+ make_property_setter('Purchase Invoice', 'naming_series', 'options', 'PINV-.YY.-\nPRET-.YY.-', '')
+
def make_custom_fields(update=True):
hsn_sac_field = dict(fieldname='gst_hsn_code', label='HSN/SAC',
fieldtype='Data', fetch_from='item_code.gst_hsn_code', insert_after='description',
@@ -860,4 +867,4 @@ def create_gratuity_rule():
})
rule.flags.ignore_mandatory = True
- rule.save()
\ No newline at end of file
+ rule.save()
From 45d0b9bce6c8af4bdc7f1374b09984e0ac17a451 Mon Sep 17 00:00:00 2001
From: Anuja P
Date: Thu, 1 Apr 2021 15:38:13 +0530
Subject: [PATCH 126/207] test: added tests for Pick List for item with
multiple UOM
---
.../stock/doctype/pick_list/test_pick_list.py | 58 +++++++++++++++++++
1 file changed, 58 insertions(+)
diff --git a/erpnext/stock/doctype/pick_list/test_pick_list.py b/erpnext/stock/doctype/pick_list/test_pick_list.py
index 8ea7f89dc4..49ebe118ca 100644
--- a/erpnext/stock/doctype/pick_list/test_pick_list.py
+++ b/erpnext/stock/doctype/pick_list/test_pick_list.py
@@ -9,6 +9,7 @@ test_dependencies = ['Item', 'Sales Invoice', 'Stock Entry', 'Batch']
from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import make_purchase_receipt
from erpnext.stock.doctype.item.test_item import create_item
+from erpnext.stock.doctype.pick_list.pick_list import create_delivery_note
from erpnext.stock.doctype.stock_reconciliation.stock_reconciliation \
import EmptyStockReconciliationItemsError
@@ -291,6 +292,63 @@ class TestPickList(unittest.TestCase):
self.assertEqual(pick_list.locations[1].qty, 5)
self.assertEqual(pick_list.locations[1].sales_order_item, sales_order.items[0].name)
+ def test_pick_list_for_items_with_multiple_UOM(self):
+ purchase_receipt = make_purchase_receipt(item_code="_Test Item", qty=10)
+ purchase_receipt.submit()
+
+ sales_order = frappe.get_doc({
+ 'doctype': 'Sales Order',
+ 'customer': '_Test Customer',
+ 'company': '_Test Company',
+ 'items': [{
+ 'item_code': '_Test Item',
+ 'qty': 1,
+ 'conversion_factor': 5,
+ 'delivery_date': frappe.utils.today()
+ },
+ {
+ 'item_code': '_Test Item',
+ 'qty': 1,
+ 'conversion_factor': 1,
+ 'delivery_date': frappe.utils.today()
+ }],
+ }).insert()
+ sales_order.submit()
+
+ pick_list = frappe.get_doc({
+ 'doctype': 'Pick List',
+ 'company': '_Test Company',
+ 'customer': '_Test Customer',
+ 'items_based_on': 'Sales Order',
+ 'locations': [{
+ 'item_code': '_Test Item',
+ 'qty': 1,
+ 'stock_qty': 5,
+ 'conversion_factor': 5,
+ 'sales_order': sales_order.name,
+ 'sales_order_item': sales_order.items[0].name ,
+ },
+ {
+ 'item_code': '_Test Item',
+ 'qty': 1,
+ 'stock_qty': 1,
+ 'conversion_factor': 1,
+ 'sales_order': sales_order.name,
+ 'sales_order_item': sales_order.items[1].name ,
+ }]
+ })
+ pick_list.set_item_locations()
+ pick_list.submit()
+
+ delivery_note = create_delivery_note(pick_list.name)
+
+ self.assertEqual(pick_list.locations[0].qty, delivery_note.items[0].qty)
+ self.assertEqual(pick_list.locations[1].qty, delivery_note.items[1].qty)
+ self.assertEqual(sales_order.items[0].conversion_factor, delivery_note.items[0].conversion_factor)
+
+ pick_list.cancel()
+ sales_order.cancel()
+ purchase_receipt.cancel()
# def test_pick_list_skips_items_in_expired_batch(self):
# pass
From 58625674f446d2884addb9be8d103ba52dab9455 Mon Sep 17 00:00:00 2001
From: Walstan Baptista <38958184+walstanb@users.noreply.github.com>
Date: Thu, 1 Apr 2021 15:55:37 +0530
Subject: [PATCH 127/207] test: correct naming series to avoid ValidationError
(#25132)
---
erpnext/accounts/doctype/purchase_invoice/test_records.json | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/erpnext/accounts/doctype/purchase_invoice/test_records.json b/erpnext/accounts/doctype/purchase_invoice/test_records.json
index e7166c5a12..9f9e90d8a7 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_records.json
+++ b/erpnext/accounts/doctype/purchase_invoice/test_records.json
@@ -43,7 +43,7 @@
}
],
"grand_total": 0,
- "naming_series": "_T-BILL",
+ "naming_series": "T-PINV-",
"taxes": [
{
"account_head": "_Test Account Shipping Charges - _TC",
@@ -167,7 +167,7 @@
}
],
"grand_total": 0,
- "naming_series": "_T-Purchase Invoice-",
+ "naming_series": "T-PINV-",
"taxes": [
{
"account_head": "_Test Account Shipping Charges - _TC",
From 798268850889a888fb2d4942df0febf350e8f5ca Mon Sep 17 00:00:00 2001
From: Anuja P
Date: Thu, 1 Apr 2021 16:04:28 +0530
Subject: [PATCH 128/207] fix: sider changes
---
erpnext/stock/doctype/pick_list/test_pick_list.py | 6 ++----
1 file changed, 2 insertions(+), 4 deletions(-)
diff --git a/erpnext/stock/doctype/pick_list/test_pick_list.py b/erpnext/stock/doctype/pick_list/test_pick_list.py
index 49ebe118ca..a762e9763e 100644
--- a/erpnext/stock/doctype/pick_list/test_pick_list.py
+++ b/erpnext/stock/doctype/pick_list/test_pick_list.py
@@ -305,8 +305,7 @@ class TestPickList(unittest.TestCase):
'qty': 1,
'conversion_factor': 5,
'delivery_date': frappe.utils.today()
- },
- {
+ }, {
'item_code': '_Test Item',
'qty': 1,
'conversion_factor': 1,
@@ -327,8 +326,7 @@ class TestPickList(unittest.TestCase):
'conversion_factor': 5,
'sales_order': sales_order.name,
'sales_order_item': sales_order.items[0].name ,
- },
- {
+ }, {
'item_code': '_Test Item',
'qty': 1,
'stock_qty': 1,
From 88f5c42b099fa4b6abf309e0b8eb359054756666 Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Thu, 1 Apr 2021 16:44:05 +0530
Subject: [PATCH 129/207] test: set formula in scorecard to avoid
ValidationError (#25116)
---
.../doctype/supplier_scorecard/test_supplier_scorecard.py | 7 +++----
1 file changed, 3 insertions(+), 4 deletions(-)
diff --git a/erpnext/buying/doctype/supplier_scorecard/test_supplier_scorecard.py b/erpnext/buying/doctype/supplier_scorecard/test_supplier_scorecard.py
index 6e6eaed95d..2528240549 100644
--- a/erpnext/buying/doctype/supplier_scorecard/test_supplier_scorecard.py
+++ b/erpnext/buying/doctype/supplier_scorecard/test_supplier_scorecard.py
@@ -9,9 +9,7 @@ import unittest
class TestSupplierScorecard(unittest.TestCase):
def test_create_scorecard(self):
- delete_test_scorecards()
- my_doc = make_supplier_scorecard()
- doc = my_doc.insert()
+ doc = make_supplier_scorecard().insert()
self.assertEqual(doc.name, valid_scorecard[0].get("supplier"))
def test_criteria_weight(self):
@@ -121,7 +119,8 @@ valid_scorecard = [
{
"weight":100.0,
"doctype":"Supplier Scorecard Scoring Criteria",
- "criteria_name":"Delivery"
+ "criteria_name":"Delivery",
+ "formula": "100"
}
],
"supplier":"_Test Supplier",
From 446a6df662739b7ae08823d4f5d546661f8947b3 Mon Sep 17 00:00:00 2001
From: Walstan Baptista <38958184+walstanb@users.noreply.github.com>
Date: Thu, 1 Apr 2021 16:54:26 +0530
Subject: [PATCH 130/207] test: set opening stock to fix NegativeStock errors
(#25101)
Co-authored-by: Sagar Vora
---
erpnext/stock/doctype/item/test_records.json | 1 +
1 file changed, 1 insertion(+)
diff --git a/erpnext/stock/doctype/item/test_records.json b/erpnext/stock/doctype/item/test_records.json
index 909c4eeb90..c1f20a47b7 100644
--- a/erpnext/stock/doctype/item/test_records.json
+++ b/erpnext/stock/doctype/item/test_records.json
@@ -12,6 +12,7 @@
"item_name": "_Test Item",
"apply_warehouse_wise_reorder_level": 1,
"gst_hsn_code": "999800",
+ "opening_stock": 10,
"valuation_rate": 100,
"item_defaults": [{
"company": "_Test Company",
From eea20f83ab19e0c050156fd82ebc274dcdcdd92f Mon Sep 17 00:00:00 2001
From: Deepesh Garg
Date: Thu, 1 Apr 2021 18:13:54 +0530
Subject: [PATCH 131/207] fix: Add shortfall ratio in Loan Security Shortfall
---
.../loan_security_shortfall.json | 12 +++++++++++-
.../loan_security_shortfall.py | 16 +++++++++++-----
.../loan_interest_report/loan_interest_report.py | 4 +++-
3 files changed, 25 insertions(+), 7 deletions(-)
diff --git a/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.json b/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.json
index 102bc0d71d..99b5c72b2d 100644
--- a/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.json
+++ b/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.json
@@ -1,4 +1,5 @@
{
+ "actions": [],
"autoname": "LM-LSS-.#####",
"creation": "2019-09-06 11:33:34.709540",
"doctype": "DocType",
@@ -14,6 +15,7 @@
"shortfall_amount",
"column_break_8",
"security_value",
+ "shortfall_percentage",
"section_break_8",
"process_loan_security_shortfall"
],
@@ -85,10 +87,18 @@
{
"fieldname": "column_break_8",
"fieldtype": "Column Break"
+ },
+ {
+ "fieldname": "shortfall_percentage",
+ "fieldtype": "Percent",
+ "label": "Shortfall Percentage",
+ "read_only": 1
}
],
"in_create": 1,
- "modified": "2019-10-24 06:24:26.128997",
+ "index_web_pages_for_search": 1,
+ "links": [],
+ "modified": "2021-04-01 08:13:43.263772",
"modified_by": "Administrator",
"module": "Loan Management",
"name": "Loan Security Shortfall",
diff --git a/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.py b/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.py
index b5e78981d0..c9b77167d6 100644
--- a/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.py
+++ b/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.py
@@ -22,7 +22,9 @@ def update_shortfall_status(loan, security_value):
if security_value >= loan_security_shortfall.shortfall_amount:
frappe.db.set_value("Loan Security Shortfall", loan_security_shortfall.name, {
"status": "Completed",
- "shortfall_amount": loan_security_shortfall.shortfall_amount})
+ "shortfall_amount": loan_security_shortfall.shortfall_amount,
+ "shortfall_percentage": 0
+ })
else:
frappe.db.set_value("Loan Security Shortfall", loan_security_shortfall.name,
"shortfall_amount", loan_security_shortfall.shortfall_amount - security_value)
@@ -65,7 +67,8 @@ def check_for_ltv_shortfall(process_loan_security_shortfall):
outstanding_amount = flt(loan.total_payment) - flt(loan.total_interest_payable) \
- flt(loan.total_principal_paid)
else:
- outstanding_amount = loan.disbursed_amount
+ outstanding_amount = flt(loan.disbursed_amount) - flt(loan.total_interest_payable) \
+ - flt(loan.total_principal_paid)
pledged_securities = get_pledged_security_qty(loan.name)
ltv_ratio = ''
@@ -81,14 +84,15 @@ def check_for_ltv_shortfall(process_loan_security_shortfall):
if current_ratio > ltv_ratio:
shortfall_amount = outstanding_amount - ((security_value * ltv_ratio) / 100)
create_loan_security_shortfall(loan.name, outstanding_amount, security_value, shortfall_amount,
- process_loan_security_shortfall)
+ current_ratio, process_loan_security_shortfall)
elif loan_shortfall_map.get(loan.name):
shortfall_amount = outstanding_amount - ((security_value * ltv_ratio) / 100)
if shortfall_amount <= 0:
shortfall = loan_shortfall_map.get(loan.name)
update_pending_shortfall(shortfall)
-def create_loan_security_shortfall(loan, loan_amount, security_value, shortfall_amount, process_loan_security_shortfall):
+def create_loan_security_shortfall(loan, loan_amount, security_value, shortfall_amount, shortfall_ratio,
+ process_loan_security_shortfall):
existing_shortfall = frappe.db.get_value("Loan Security Shortfall", {"loan": loan, "status": "Pending"}, "name")
if existing_shortfall:
@@ -101,6 +105,7 @@ def create_loan_security_shortfall(loan, loan_amount, security_value, shortfall_
ltv_shortfall.loan_amount = loan_amount
ltv_shortfall.security_value = security_value
ltv_shortfall.shortfall_amount = shortfall_amount
+ ltv_shortfall.shortfall_percentage = shortfall_ratio
ltv_shortfall.process_loan_security_shortfall = process_loan_security_shortfall
ltv_shortfall.save()
@@ -114,6 +119,7 @@ def update_pending_shortfall(shortfall):
frappe.db.set_value("Loan Security Shortfall", shortfall,
{
"status": "Completed",
- "shortfall_amount": 0
+ "shortfall_amount": 0,
+ "shortfall_precentage": 0
})
diff --git a/erpnext/loan_management/report/loan_interest_report/loan_interest_report.py b/erpnext/loan_management/report/loan_interest_report/loan_interest_report.py
index 0f72c3cce7..2a74a1eb85 100644
--- a/erpnext/loan_management/report/loan_interest_report/loan_interest_report.py
+++ b/erpnext/loan_management/report/loan_interest_report/loan_interest_report.py
@@ -63,9 +63,11 @@ def get_active_loan_details(filters):
currency = erpnext.get_company_currency(filters.get('company'))
for loan in loan_details:
+ total_payment = loan.total_payment if loan.status == 'Disbursed' else loan.disbursed_amount
+
loan.update({
"sanctioned_amount": flt(sanctioned_amount_map.get(loan.applicant_name)),
- "principal_outstanding": flt(loan.total_payment) - flt(loan.total_principal_paid) \
+ "principal_outstanding": flt(total_payment) - flt(loan.total_principal_paid) \
- flt(loan.total_interest_payable) - flt(loan.written_off_amount),
"total_repayment": flt(payments.get(loan.loan)),
"accrued_interest": flt(accrual_map.get(loan.loan, {}).get("accrued_interest")),
From d3ee8c7731fb970f280447f0fef75e98af312301 Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Thu, 1 Apr 2021 18:18:19 +0530
Subject: [PATCH 132/207] fix: customer creation from shopping cart (#25136)
---
erpnext/selling/doctype/customer/customer.py | 44 +++++++++++++++-----
1 file changed, 34 insertions(+), 10 deletions(-)
diff --git a/erpnext/selling/doctype/customer/customer.py b/erpnext/selling/doctype/customer/customer.py
index c452594608..96b3fa4ccd 100644
--- a/erpnext/selling/doctype/customer/customer.py
+++ b/erpnext/selling/doctype/customer/customer.py
@@ -230,13 +230,20 @@ class Customer(TransactionBase):
frappe.db.set(self, "customer_name", newdn)
def set_loyalty_program(self):
- if self.loyalty_program: return
+ if self.loyalty_program:
+ return
+
loyalty_program = get_loyalty_programs(self)
- if not loyalty_program: return
+ if not loyalty_program:
+ return
+
if len(loyalty_program) == 1:
self.loyalty_program = loyalty_program[0]
else:
- frappe.msgprint(_("Multiple Loyalty Program found for the Customer. Please select manually."))
+ frappe.msgprint(
+ _("Multiple Loyalty Programs found for Customer {}. Please select manually.")
+ .format(frappe.bold(self.customer_name))
+ )
def create_onboarding_docs(self, args):
defaults = frappe.defaults.get_defaults()
@@ -340,7 +347,6 @@ def _set_missing_values(source, target):
@frappe.whitelist()
def get_loyalty_programs(doc):
''' returns applicable loyalty programs for a customer '''
- from frappe.desk.treeview import get_children
lp_details = []
loyalty_programs = frappe.get_all("Loyalty Program",
@@ -349,15 +355,33 @@ def get_loyalty_programs(doc):
"ifnull(to_date, '2500-01-01')": [">=", today()]})
for loyalty_program in loyalty_programs:
- customer_groups = [d.value for d in get_children("Customer Group", loyalty_program.customer_group)] + [loyalty_program.customer_group]
- customer_territories = [d.value for d in get_children("Territory", loyalty_program.customer_territory)] + [loyalty_program.customer_territory]
-
- if (not loyalty_program.customer_group or doc.customer_group in customer_groups)\
- and (not loyalty_program.customer_territory or doc.territory in customer_territories):
+ if (
+ (not loyalty_program.customer_group
+ or doc.customer_group in get_nested_links(
+ "Customer Group",
+ loyalty_program.customer_group,
+ doc.flags.ignore_permissions
+ ))
+ and (not loyalty_program.customer_territory
+ or doc.territory in get_nested_links(
+ "Territory",
+ loyalty_program.customer_territory,
+ doc.flags.ignore_permissions
+ ))
+ ):
lp_details.append(loyalty_program.name)
return lp_details
+def get_nested_links(link_doctype, link_name, ignore_permissions=False):
+ from frappe.desk.treeview import _get_children
+
+ links = [link_name]
+ for d in _get_children(link_doctype, link_name, ignore_permissions):
+ links.append(d.value)
+
+ return links
+
@frappe.whitelist()
@frappe.validate_and_sanitize_search_inputs
def get_customer_list(doctype, txt, searchfield, start, page_len, filters=None):
@@ -572,4 +596,4 @@ def get_customer_primary_contact(doctype, txt, searchfield, start, page_len, fil
""", {
'customer': customer,
'txt': '%%%s%%' % txt
- })
\ No newline at end of file
+ })
From 67169ba2d3bc2f591f3a3479655c8ed15fcc5fa1 Mon Sep 17 00:00:00 2001
From: Suraj Shetty
Date: Thu, 1 Apr 2021 19:52:07 +0530
Subject: [PATCH 133/207] fix: get_route_options_for_new_doc for project
---
erpnext/projects/doctype/project/project.js | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/erpnext/projects/doctype/project/project.js b/erpnext/projects/doctype/project/project.js
index 077011ace0..c5265e23c0 100644
--- a/erpnext/projects/doctype/project/project.js
+++ b/erpnext/projects/doctype/project/project.js
@@ -18,8 +18,8 @@ frappe.ui.form.on("Project", {
};
},
onload: function (frm) {
- var so = frappe.meta.get_docfield("Project", "sales_order");
- so.get_route_options_for_new_doc = function (field) {
+ const so = frm.get_docfield("sales_order");
+ so.get_route_options_for_new_doc = () => {
if (frm.is_new()) return;
return {
"customer": frm.doc.customer,
From ace4ce64a07f9e8a5e9deb36c95abca1f6f3daf6 Mon Sep 17 00:00:00 2001
From: Afshan <33727827+AfshanKhan@users.noreply.github.com>
Date: Thu, 1 Apr 2021 20:28:12 +0530
Subject: [PATCH 134/207] fix: validation msg for TransDocNo e-invoicing
(#25121)
---
erpnext/regional/india/e_invoice/einv_validation.json | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/erpnext/regional/india/e_invoice/einv_validation.json b/erpnext/regional/india/e_invoice/einv_validation.json
index 86290cfe52..f4a3542a60 100644
--- a/erpnext/regional/india/e_invoice/einv_validation.json
+++ b/erpnext/regional/india/e_invoice/einv_validation.json
@@ -919,7 +919,8 @@
"minLength": 1,
"maxLength": 15,
"pattern": "^([0-9A-Z/-]){1,15}$",
- "description": "Tranport Document Number"
+ "description": "Tranport Document Number",
+ "validationMsg": "Transport Receipt No is invalid"
},
"TransDocDt": {
"type": "string",
From 7f10044195d040e6e0b98d2b642c305ba243be73 Mon Sep 17 00:00:00 2001
From: Deepesh Garg
Date: Fri, 2 Apr 2021 12:04:42 +0530
Subject: [PATCH 135/207] fix: Typo
---
.../doctype/loan_security_shortfall/loan_security_shortfall.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.py b/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.py
index c9b77167d6..653943629e 100644
--- a/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.py
+++ b/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.py
@@ -120,6 +120,6 @@ def update_pending_shortfall(shortfall):
{
"status": "Completed",
"shortfall_amount": 0,
- "shortfall_precentage": 0
+ "shortfall_percentage": 0
})
From 5447b250fe51af423d5f0f6f9be1ebc2886295eb Mon Sep 17 00:00:00 2001
From: Saqib
Date: Fri, 2 Apr 2021 12:16:19 +0530
Subject: [PATCH 136/207] fix: place of supply of e-invoicing (#25148)
---
erpnext/regional/india/e_invoice/utils.py | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/erpnext/regional/india/e_invoice/utils.py b/erpnext/regional/india/e_invoice/utils.py
index 96f7f1b224..433ef18e99 100644
--- a/erpnext/regional/india/e_invoice/utils.py
+++ b/erpnext/regional/india/e_invoice/utils.py
@@ -334,8 +334,11 @@ def make_einvoice(invoice):
buyer_details = get_overseas_address_details(invoice.customer_address)
else:
buyer_details = get_party_details(invoice.customer_address)
- place_of_supply = get_place_of_supply(invoice, invoice.doctype) or sanitize_for_json(invoice.billing_address_gstin)
- place_of_supply = place_of_supply[:2]
+ place_of_supply = get_place_of_supply(invoice, invoice.doctype)
+ if place_of_supply:
+ place_of_supply = place_of_supply.split('-')[0]
+ else:
+ place_of_supply = sanitize_for_json(invoice.billing_address_gstin)[:2]
buyer_details.update(dict(place_of_supply=place_of_supply))
shipping_details = payment_details = prev_doc_details = eway_bill_details = frappe._dict({})
From 7535341016bfea77b6ea9ffbfa760ba9dfed6eb3 Mon Sep 17 00:00:00 2001
From: bhavesh95863 <34086262+bhavesh95863@users.noreply.github.com>
Date: Fri, 2 Apr 2021 15:04:48 +0530
Subject: [PATCH 137/207] fix(regional): remove shipping address GSTIN
validation for e-invoice (#25153)
---
erpnext/regional/india/e_invoice/utils.py | 16 +++++++++-------
1 file changed, 9 insertions(+), 7 deletions(-)
diff --git a/erpnext/regional/india/e_invoice/utils.py b/erpnext/regional/india/e_invoice/utils.py
index 433ef18e99..8bca1a23fa 100644
--- a/erpnext/regional/india/e_invoice/utils.py
+++ b/erpnext/regional/india/e_invoice/utils.py
@@ -87,10 +87,10 @@ def get_doc_details(invoice):
invoice_date=invoice_date
))
-def get_party_details(address_name):
+def get_party_details(address_name, company_address=None, billing_address=None, shipping_address=None):
d = frappe.get_all('Address', filters={'name': address_name}, fields=['*'])[0]
- if (not d.gstin
+ if ((not d.gstin and not shipping_address)
or not d.city
or not d.pincode
or not d.address_title
@@ -108,8 +108,7 @@ def get_party_details(address_name):
# according to einvoice standard
pincode = 999999
- return frappe._dict(dict(
- gstin=d.gstin,
+ party_address_details = frappe._dict(dict(
legal_name=sanitize_for_json(d.address_title),
location=sanitize_for_json(d.city),
pincode=d.pincode,
@@ -117,6 +116,9 @@ def get_party_details(address_name):
address_line1=sanitize_for_json(d.address_line1),
address_line2=sanitize_for_json(d.address_line2)
))
+ if d.gstin:
+ party_address_details.gstin = d.gstin
+ return party_address_details
def get_gstin_details(gstin):
if not hasattr(frappe.local, 'gstin_cache'):
@@ -328,12 +330,12 @@ def make_einvoice(invoice):
item_list = get_item_list(invoice)
doc_details = get_doc_details(invoice)
invoice_value_details = get_invoice_value_details(invoice)
- seller_details = get_party_details(invoice.company_address)
+ seller_details = get_party_details(invoice.company_address, company_address=1)
if invoice.gst_category == 'Overseas':
buyer_details = get_overseas_address_details(invoice.customer_address)
else:
- buyer_details = get_party_details(invoice.customer_address)
+ buyer_details = get_party_details(invoice.customer_address, billing_address=1)
place_of_supply = get_place_of_supply(invoice, invoice.doctype)
if place_of_supply:
place_of_supply = place_of_supply.split('-')[0]
@@ -346,7 +348,7 @@ def make_einvoice(invoice):
if invoice.gst_category == 'Overseas':
shipping_details = get_overseas_address_details(invoice.shipping_address_name)
else:
- shipping_details = get_party_details(invoice.shipping_address_name)
+ shipping_details = get_party_details(invoice.shipping_address_name, shipping_address=1)
if invoice.is_pos and invoice.base_paid_amount:
payment_details = get_payment_details(invoice)
From 2453b0cf6ab9048358c9b3fd6d2b48e92fb2076c Mon Sep 17 00:00:00 2001
From: Rucha Mahabal
Date: Fri, 2 Apr 2021 17:00:28 +0530
Subject: [PATCH 138/207] fix: component amount calculation based on formula
with abbr not working (#25117)
---
erpnext/payroll/doctype/salary_slip/salary_slip.py | 5 ++++-
erpnext/payroll/doctype/salary_structure/salary_structure.py | 2 +-
2 files changed, 5 insertions(+), 2 deletions(-)
diff --git a/erpnext/payroll/doctype/salary_slip/salary_slip.py b/erpnext/payroll/doctype/salary_slip/salary_slip.py
index 9abe57cd65..aa9acd8bd0 100644
--- a/erpnext/payroll/doctype/salary_slip/salary_slip.py
+++ b/erpnext/payroll/doctype/salary_slip/salary_slip.py
@@ -618,13 +618,16 @@ class SalarySlip(TransactionBase):
component_row = self.append(component_type)
for attr in (
- 'depends_on_payment_days', 'salary_component', 'abbr'
+ 'depends_on_payment_days', 'salary_component',
'do_not_include_in_total', 'is_tax_applicable',
'is_flexible_benefit', 'variable_based_on_taxable_salary',
'exempted_from_income_tax'
):
component_row.set(attr, component_data.get(attr))
+ abbr = component_data.get('abbr') or component_data.get('salary_component_abbr')
+ component_row.set('abbr', abbr)
+
if additional_salary:
component_row.default_amount = 0
component_row.additional_amount = amount
diff --git a/erpnext/payroll/doctype/salary_structure/salary_structure.py b/erpnext/payroll/doctype/salary_structure/salary_structure.py
index 1712081550..352c1804f0 100644
--- a/erpnext/payroll/doctype/salary_structure/salary_structure.py
+++ b/erpnext/payroll/doctype/salary_structure/salary_structure.py
@@ -100,7 +100,7 @@ class SalaryStructure(Document):
from_date=from_date, base=base, variable=variable, income_tax_slab=income_tax_slab)
else:
assign_salary_structure_for_employees(employees, self,
- payroll_payable_account=payroll_payable_account,
+ payroll_payable_account=payroll_payable_account,
from_date=from_date, base=base, variable=variable, income_tax_slab=income_tax_slab)
else:
frappe.msgprint(_("No Employee Found"))
From 2cef23d4c9d9c129e6ca8ee525823a3bda10871a Mon Sep 17 00:00:00 2001
From: Kaviya Periyasamy <36359901+KaviyaPeriyasamy@users.noreply.github.com>
Date: Sat, 3 Apr 2021 11:30:49 +0530
Subject: [PATCH 139/207] fix: object referencing the same address issue
(#25159)
* fix: variable reference to same address
* fix: object referencing same address issue
* fix: value error
---
erpnext/regional/india/e_invoice/utils.py | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/erpnext/regional/india/e_invoice/utils.py b/erpnext/regional/india/e_invoice/utils.py
index 8bca1a23fa..8eccc3f565 100644
--- a/erpnext/regional/india/e_invoice/utils.py
+++ b/erpnext/regional/india/e_invoice/utils.py
@@ -396,7 +396,9 @@ def safe_json_load(json_string):
snippet = json_string[start:end]
frappe.throw(_("Error in input data. Please check for any special characters near following input: {}").format(snippet))
-def validate_einvoice(validations, einvoice, errors=[]):
+def validate_einvoice(validations, einvoice, errors=None):
+ if errors is None:
+ errors = []
for fieldname, field_validation in validations.items():
value = einvoice.get(fieldname, None)
if not value or value == "None":
From 87b2a513228f9b6a88f76adc27d7be00c855ad0d Mon Sep 17 00:00:00 2001
From: Ankush Menat
Date: Sat, 3 Apr 2021 12:28:34 +0530
Subject: [PATCH 140/207] fix: escape sql filters in credit report
closes #24965
---
.../customer_credit_balance.py | 24 +++++++++----------
1 file changed, 12 insertions(+), 12 deletions(-)
diff --git a/erpnext/selling/report/customer_credit_balance/customer_credit_balance.py b/erpnext/selling/report/customer_credit_balance/customer_credit_balance.py
index f396705460..6fb7666c2c 100644
--- a/erpnext/selling/report/customer_credit_balance/customer_credit_balance.py
+++ b/erpnext/selling/report/customer_credit_balance/customer_credit_balance.py
@@ -57,18 +57,18 @@ def get_columns(customer_naming_type):
return columns
def get_details(filters):
- conditions = ""
+ sql_query = """SELECT
+ c.name, c.customer_name,
+ ccl.bypass_credit_limit_check,
+ c.is_frozen, c.disabled
+ FROM `tabCustomer` c, `tabCustomer Credit Limit` ccl
+ WHERE
+ c.name = ccl.parent
+ AND ccl.company = %(company)s"""
+
+ # customer filter is optional.
if filters.get("customer"):
- conditions += " AND c.name = '" + filters.get("customer") + "'"
+ sql_query += " AND c.name = %(customer)s"
- return frappe.db.sql("""SELECT
- c.name, c.customer_name,
- ccl.bypass_credit_limit_check,
- c.is_frozen, c.disabled
- FROM `tabCustomer` c, `tabCustomer Credit Limit` ccl
- WHERE
- c.name = ccl.parent
- AND ccl.company = '{0}'
- {1}
- """.format( filters.get("company"),conditions), as_dict=1) #nosec
+ return frappe.db.sql(sql_query, filters, as_dict=1)
From 5d77f10baa3cb49ffb6dd812bcee67dbb0ddcfc6 Mon Sep 17 00:00:00 2001
From: Walstan Baptista <38958184+walstanb@users.noreply.github.com>
Date: Sat, 3 Apr 2021 13:38:55 +0530
Subject: [PATCH 141/207] test: docs are not deleted in tearDown (#25123)
* test: docs are not deleted in tearDown
---
.../test_inpatient_medication_order.py | 11 ++---------
1 file changed, 2 insertions(+), 9 deletions(-)
diff --git a/erpnext/healthcare/doctype/inpatient_medication_order/test_inpatient_medication_order.py b/erpnext/healthcare/doctype/inpatient_medication_order/test_inpatient_medication_order.py
index a21caca8ff..21776d2380 100644
--- a/erpnext/healthcare/doctype/inpatient_medication_order/test_inpatient_medication_order.py
+++ b/erpnext/healthcare/doctype/inpatient_medication_order/test_inpatient_medication_order.py
@@ -81,15 +81,8 @@ class TestInpatientMedicationOrder(unittest.TestCase):
self.ip_record.reload()
discharge_patient(self.ip_record)
- for entry in frappe.get_all('Inpatient Medication Entry'):
- doc = frappe.get_doc('Inpatient Medication Entry', entry.name)
- doc.cancel()
- doc.delete()
-
- for entry in frappe.get_all('Inpatient Medication Order'):
- doc = frappe.get_doc('Inpatient Medication Order', entry.name)
- doc.cancel()
- doc.delete()
+ for doctype in ["Inpatient Medication Entry", "Inpatient Medication Order"]:
+ frappe.db.sql("delete from `tab{doctype}`".format(doctype=doctype))
def create_dosage_form():
if not frappe.db.exists('Dosage Form', 'Tablet'):
From f6b1fa0a1c650a9532ed43eac3ee76e433aa6aa0 Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Sat, 3 Apr 2021 16:06:41 +0530
Subject: [PATCH 142/207] test: clear tax rules before making POS Invoices
(#25171)
---
erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py b/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py
index 054afe5bbb..6d388c4aaa 100644
--- a/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py
+++ b/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py
@@ -12,6 +12,10 @@ from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import make_pu
from erpnext.stock.doctype.item.test_item import make_item
class TestPOSInvoice(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ frappe.db.sql("delete from `tabTax Rule`")
+
def tearDown(self):
if frappe.session.user != "Administrator":
frappe.set_user("Administrator")
From f68f41d7a74761352b0ddbb254e2698772d82ef4 Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Sat, 3 Apr 2021 17:34:57 +0530
Subject: [PATCH 143/207] test: fix multiple tests in Leave Application
(#25173)
---
.../test_leave_application.py | 24 ++++++++++---------
1 file changed, 13 insertions(+), 11 deletions(-)
diff --git a/erpnext/hr/doctype/leave_application/test_leave_application.py b/erpnext/hr/doctype/leave_application/test_leave_application.py
index b335c48594..48bfa0c0aa 100644
--- a/erpnext/hr/doctype/leave_application/test_leave_application.py
+++ b/erpnext/hr/doctype/leave_application/test_leave_application.py
@@ -56,6 +56,7 @@ class TestLeaveApplication(unittest.TestCase):
@classmethod
def setUpClass(cls):
set_leave_approver()
+ frappe.db.sql("delete from tabAttendance where employee='_T-Employee-00001'")
def tearDown(self):
frappe.set_user("Administrator")
@@ -230,8 +231,9 @@ class TestLeaveApplication(unittest.TestCase):
def test_optional_leave(self):
leave_period = get_leave_period()
today = nowdate()
- from datetime import date
holiday_list = 'Test Holiday List for Optional Holiday'
+ optional_leave_date = add_days(today, 7)
+
if not frappe.db.exists('Holiday List', holiday_list):
frappe.get_doc(dict(
doctype = 'Holiday List',
@@ -239,7 +241,7 @@ class TestLeaveApplication(unittest.TestCase):
from_date = add_months(today, -6),
to_date = add_months(today, 6),
holidays = [
- dict(holiday_date = today, description = 'Test')
+ dict(holiday_date = optional_leave_date, description = 'Test')
]
)).insert()
employee = get_employee()
@@ -255,7 +257,7 @@ class TestLeaveApplication(unittest.TestCase):
allocate_leaves(employee, leave_period, leave_type, 10)
- date = add_days(today, - 1)
+ date = add_days(today, 6)
leave_application = frappe.get_doc(dict(
doctype = 'Leave Application',
@@ -270,14 +272,14 @@ class TestLeaveApplication(unittest.TestCase):
# can only apply on optional holidays
self.assertRaises(NotAnOptionalHoliday, leave_application.insert)
- leave_application.from_date = today
- leave_application.to_date = today
+ leave_application.from_date = optional_leave_date
+ leave_application.to_date = optional_leave_date
leave_application.status = "Approved"
leave_application.insert()
leave_application.submit()
# check leave balance is reduced
- self.assertEqual(get_leave_balance_on(employee.name, leave_type, today), 9)
+ self.assertEqual(get_leave_balance_on(employee.name, leave_type, optional_leave_date), 9)
def test_leaves_allowed(self):
employee = get_employee()
@@ -341,7 +343,7 @@ class TestLeaveApplication(unittest.TestCase):
to_date = add_days(date, 4),
company = "_Test Company",
docstatus = 1,
- status = "Approved"
+ status = "Approved"
))
self.assertRaises(frappe.ValidationError, leave_application.insert)
@@ -363,7 +365,7 @@ class TestLeaveApplication(unittest.TestCase):
to_date = add_days(date, 4),
company = "_Test Company",
docstatus = 1,
- status = "Approved"
+ status = "Approved"
))
self.assertTrue(leave_application.insert())
@@ -393,7 +395,7 @@ class TestLeaveApplication(unittest.TestCase):
to_date = add_days(date, 4),
company = "_Test Company",
docstatus = 1,
- status = "Approved"
+ status = "Approved"
))
self.assertRaises(frappe.ValidationError, leave_application.insert)
@@ -508,7 +510,7 @@ class TestLeaveApplication(unittest.TestCase):
description = "_Test Reason",
company = "_Test Company",
docstatus = 1,
- status = "Approved"
+ status = "Approved"
))
leave_application.submit()
leave_ledger_entry = frappe.get_all('Leave Ledger Entry', fields='*', filters=dict(transaction_name=leave_application.name))
@@ -540,7 +542,7 @@ class TestLeaveApplication(unittest.TestCase):
description = "_Test Reason",
company = "_Test Company",
docstatus = 1,
- status = "Approved"
+ status = "Approved"
))
leave_application.submit()
From b7481633b1e65888518a760d75b46a5e3f4c6cc6 Mon Sep 17 00:00:00 2001
From: Walstan Baptista <38958184+walstanb@users.noreply.github.com>
Date: Sat, 3 Apr 2021 17:37:59 +0530
Subject: [PATCH 144/207] test: adds role after setting user to Administrator
(#25177)
---
.../doctype/stock_ledger_entry/test_stock_ledger_entry.py | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
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 7ebd4e6cb2..349d8ae679 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
@@ -313,8 +313,8 @@ class TestStockLedgerEntry(unittest.TestCase):
# Set User with Stock User role but not Stock Manager
try:
- frappe.set_user("test@example.com")
user = frappe.get_doc("User", "test@example.com")
+ frappe.set_user(user.name)
user.add_roles("Stock User")
user.remove_roles("Stock Manager")
@@ -325,7 +325,9 @@ class TestStockLedgerEntry(unittest.TestCase):
# Block back-dated entry
self.assertRaises(BackDatedStockTransaction, back_dated_se_1.submit)
+ frappe.set_user("Administrator")
user.add_roles("Stock Manager")
+ frappe.set_user(user.name)
# Back dated entry allowed to Stock Manager
back_dated_se_2 = make_stock_entry(target="_Test Warehouse - _TC", qty=10, basic_rate=100,
@@ -337,6 +339,7 @@ class TestStockLedgerEntry(unittest.TestCase):
finally:
frappe.db.set_value("Stock Settings", None, "role_allowed_to_create_edit_back_dated_transactions", None)
frappe.set_user("Administrator")
+ user.remove_roles("Stock Manager")
def create_repack_entry(**args):
@@ -400,4 +403,4 @@ def create_items():
make_item(d, properties=properties)
- return items
\ No newline at end of file
+ return items
From cce3efe0c10eb89b8cce09ed9f9620cee4fd2be9 Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Sat, 3 Apr 2021 19:46:44 +0530
Subject: [PATCH 145/207] test: specify warehouse list to avoid error (#25174)
* test: specify warehouse list to avoid error
* test: get_all_warehouses of BOM company
---
erpnext/manufacturing/doctype/bom/test_bom.py | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/erpnext/manufacturing/doctype/bom/test_bom.py b/erpnext/manufacturing/doctype/bom/test_bom.py
index 3239478872..4050a7d3ed 100644
--- a/erpnext/manufacturing/doctype/bom/test_bom.py
+++ b/erpnext/manufacturing/doctype/bom/test_bom.py
@@ -134,7 +134,13 @@ class TestBOM(unittest.TestCase):
bom.items[0].conversion_factor = 6
bom.insert()
- reset_item_valuation_rate(item_code='_Test Item', qty=200, rate=200)
+ reset_item_valuation_rate(
+ item_code='_Test Item',
+ warehouse_list=frappe.get_all("Warehouse",
+ {"is_group":0, "company": bom.company}, pluck="name"),
+ qty=200,
+ rate=200
+ )
bom.update_cost()
From 37b826b98800cdde13b8d1f47e187c33742cf1e6 Mon Sep 17 00:00:00 2001
From: Walstan Baptista <38958184+walstanb@users.noreply.github.com>
Date: Sat, 3 Apr 2021 19:48:46 +0530
Subject: [PATCH 146/207] fix: correct calculation for discount amount when
margin is set (#25179)
---
erpnext/controllers/taxes_and_totals.py | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/erpnext/controllers/taxes_and_totals.py b/erpnext/controllers/taxes_and_totals.py
index e329b325b3..5f73c55836 100644
--- a/erpnext/controllers/taxes_and_totals.py
+++ b/erpnext/controllers/taxes_and_totals.py
@@ -113,10 +113,10 @@ class calculate_taxes_and_totals(object):
item.rate_with_margin, item.base_rate_with_margin = self.calculate_margin(item)
if flt(item.rate_with_margin) > 0:
item.rate = flt(item.rate_with_margin * (1.0 - (item.discount_percentage / 100.0)), item.precision("rate"))
- if not item.discount_amount:
- item.discount_amount = item.rate_with_margin - item.rate
- elif not item.discount_percentage:
+ if item.discount_amount and not item.discount_percentage:
item.rate -= item.discount_amount
+ else:
+ item.discount_amount = item.rate_with_margin - item.rate
elif flt(item.price_list_rate) > 0:
item.discount_amount = item.price_list_rate - item.rate
elif flt(item.price_list_rate) > 0 and not item.discount_amount:
@@ -808,4 +808,4 @@ class init_landed_taxes_and_totals(object):
def set_amounts_in_company_currency(self):
for d in self.doc.get(self.tax_field):
d.amount = flt(d.amount, d.precision("amount"))
- d.base_amount = flt(d.amount * flt(d.exchange_rate), d.precision("base_amount"))
\ No newline at end of file
+ d.base_amount = flt(d.amount * flt(d.exchange_rate), d.precision("base_amount"))
From 993cf8c2cd169800ce246c734fca70ea89e0b04f Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Sat, 3 Apr 2021 20:25:19 +0530
Subject: [PATCH 147/207] test: cleanup BOM in `test_routing` and prevent
overlap in `test_job_card` (#25180)
---
.../doctype/routing/test_routing.py | 13 ++++++++---
.../doctype/work_order/test_work_order.py | 22 +++++++++----------
2 files changed, 21 insertions(+), 14 deletions(-)
diff --git a/erpnext/manufacturing/doctype/routing/test_routing.py b/erpnext/manufacturing/doctype/routing/test_routing.py
index 7071bc1ab0..6a38dcfa03 100644
--- a/erpnext/manufacturing/doctype/routing/test_routing.py
+++ b/erpnext/manufacturing/doctype/routing/test_routing.py
@@ -13,8 +13,15 @@ from erpnext.manufacturing.doctype.workstation.test_workstation import make_work
from erpnext.manufacturing.doctype.work_order.test_work_order import make_wo_order_test_record
class TestRouting(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.item_code = "Test Routing Item - A"
+
+ @classmethod
+ def tearDownClass(cls):
+ frappe.db.sql('delete from tabBOM where item=%s', cls.item_code)
+
def test_sequence_id(self):
- item_code = "Test Routing Item - A"
operations = [{"operation": "Test Operation A", "workstation": "Test Workstation A", "time_in_mins": 30},
{"operation": "Test Operation B", "workstation": "Test Workstation A", "time_in_mins": 20}]
@@ -22,8 +29,8 @@ class TestRouting(unittest.TestCase):
setup_operations(operations)
routing_doc = create_routing(routing_name="Testing Route", operations=operations)
- bom_doc = setup_bom(item_code=item_code, routing=routing_doc.name)
- wo_doc = make_wo_order_test_record(production_item = item_code, bom_no=bom_doc.name)
+ bom_doc = setup_bom(item_code=self.item_code, routing=routing_doc.name)
+ wo_doc = make_wo_order_test_record(production_item = self.item_code, bom_no=bom_doc.name)
for row in routing_doc.operations:
self.assertEqual(row.sequence_id, row.idx)
diff --git a/erpnext/manufacturing/doctype/work_order/test_work_order.py b/erpnext/manufacturing/doctype/work_order/test_work_order.py
index 08291d1eae..6b1fafe5f4 100644
--- a/erpnext/manufacturing/doctype/work_order/test_work_order.py
+++ b/erpnext/manufacturing/doctype/work_order/test_work_order.py
@@ -371,14 +371,14 @@ class TestWorkOrder(unittest.TestCase):
def test_job_card(self):
stock_entries = []
- data = frappe.get_cached_value('BOM',
- {'docstatus': 1, 'with_operations': 1, 'company': '_Test Company'}, ['name', 'item'])
+ bom = frappe.get_doc('BOM', {
+ 'docstatus': 1,
+ 'with_operations': 1,
+ 'company': '_Test Company'
+ })
- bom, bom_item = data
-
- bom_doc = frappe.get_doc('BOM', bom)
- work_order = make_wo_order_test_record(item=bom_item, qty=1,
- bom_no=bom, source_warehouse="_Test Warehouse - _TC")
+ work_order = make_wo_order_test_record(item=bom.item, qty=1,
+ bom_no=bom.name, source_warehouse="_Test Warehouse - _TC")
for row in work_order.required_items:
stock_entry_doc = test_stock_entry.make_stock_entry(item_code=row.item_code,
@@ -390,14 +390,14 @@ class TestWorkOrder(unittest.TestCase):
stock_entries.append(ste)
job_cards = frappe.get_all('Job Card', filters = {'work_order': work_order.name})
- self.assertEqual(len(job_cards), len(bom_doc.operations))
+ self.assertEqual(len(job_cards), len(bom.operations))
for i, job_card in enumerate(job_cards):
doc = frappe.get_doc("Job Card", job_card)
doc.append("time_logs", {
- "from_time": now(),
- "hours": i,
- "to_time": add_to_date(now(), i),
+ "from_time": add_to_date(None, i),
+ "hours": 1,
+ "to_time": add_to_date(None, i + 1),
"completed_qty": doc.for_quantity
})
doc.submit()
From 8aacd341c7f166e5da57b5e6d9fef16ff47c24fc Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Sat, 3 Apr 2021 23:01:16 +0530
Subject: [PATCH 148/207] test: disable shopping cart before running Tax Rule
tests (#25183)
---
erpnext/accounts/doctype/tax_rule/test_tax_rule.py | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
diff --git a/erpnext/accounts/doctype/tax_rule/test_tax_rule.py b/erpnext/accounts/doctype/tax_rule/test_tax_rule.py
index 632e30db45..ac1ffd9e75 100644
--- a/erpnext/accounts/doctype/tax_rule/test_tax_rule.py
+++ b/erpnext/accounts/doctype/tax_rule/test_tax_rule.py
@@ -14,10 +14,15 @@ test_records = frappe.get_test_records('Tax Rule')
from six import iteritems
class TestTaxRule(unittest.TestCase):
- def setUp(self):
+ @classmethod
+ def setUpClass(cls):
+ frappe.db.set_value("Shopping Cart Settings", None, "enabled", 0)
+
+ @classmethod
+ def tearDownClass(cls):
frappe.db.sql("delete from `tabTax Rule`")
- def tearDown(self):
+ def setUp(self):
frappe.db.sql("delete from `tabTax Rule`")
def test_conflict(self):
From ba10ef44034a05d3211a12a7cdcc9371bcd15d1f Mon Sep 17 00:00:00 2001
From: Rucha Mahabal
Date: Sun, 4 Apr 2021 17:16:48 +0530
Subject: [PATCH 149/207] feat(HR): share doc with employee approvers if they
don't have access
---
erpnext/hr/doctype/employee/employee.py | 14 ++++++++++++-
.../hr/doctype/expense_claim/expense_claim.py | 5 ++++-
.../leave_application/leave_application.py | 5 ++++-
.../leave_ledger_entry/leave_ledger_entry.py | 4 +++-
.../hr/doctype/shift_request/shift_request.py | 5 +++++
erpnext/hr/utils.py | 20 +++++++++++++++++++
6 files changed, 49 insertions(+), 4 deletions(-)
diff --git a/erpnext/hr/doctype/employee/employee.py b/erpnext/hr/doctype/employee/employee.py
index 629bc57118..ed7d588434 100755
--- a/erpnext/hr/doctype/employee/employee.py
+++ b/erpnext/hr/doctype/employee/employee.py
@@ -80,6 +80,7 @@ class Employee(NestedSet):
self.update_user()
self.update_user_permissions()
self.reset_employee_emails_cache()
+ self.update_approver_role()
def update_user_permissions(self):
if not self.create_user_permission: return
@@ -145,6 +146,17 @@ class Employee(NestedSet):
user.save()
+ def update_approver_role(self):
+ if self.leave_approver:
+ user = frappe.get_doc("User", self.leave_approver)
+ user.flags.ignore_permissions = True
+ user.add_roles("Leave Approver")
+
+ if self.expense_approver:
+ user = frappe.get_doc("User", self.expense_approver)
+ user.flags.ignore_permissions = True
+ user.add_roles("Expense Approver")
+
def validate_date(self):
if self.date_of_birth and getdate(self.date_of_birth) > getdate(today()):
throw(_("Date of Birth cannot be greater than today."))
@@ -503,7 +515,7 @@ def has_user_permission_for_employee(user_name, employee_name):
})
def has_upload_permission(doc, ptype='read', user=None):
- if not user:
+ if not user:
user = frappe.session.user
if get_doc_permissions(doc, user=user, ptype=ptype).get(ptype):
return True
diff --git a/erpnext/hr/doctype/expense_claim/expense_claim.py b/erpnext/hr/doctype/expense_claim/expense_claim.py
index bf893d5fab..ff753e0e4a 100644
--- a/erpnext/hr/doctype/expense_claim/expense_claim.py
+++ b/erpnext/hr/doctype/expense_claim/expense_claim.py
@@ -6,7 +6,7 @@ import frappe, erpnext
from frappe import _
from frappe.utils import get_fullname, flt, cstr, get_link_to_form
from frappe.model.document import Document
-from erpnext.hr.utils import set_employee_name
+from erpnext.hr.utils import set_employee_name, share_doc_with_approver
from erpnext.accounts.party import get_party_account
from erpnext.accounts.general_ledger import make_gl_entries
from erpnext.accounts.doctype.sales_invoice.sales_invoice import get_bank_cash_account
@@ -53,6 +53,9 @@ class ExpenseClaim(AccountsController):
elif self.docstatus == 1 and self.approval_status == 'Rejected':
self.status = 'Rejected'
+ def on_update(self):
+ share_doc_with_approver(self, self.expense_approver)
+
def set_payable_account(self):
if not self.payable_account and not self.is_paid:
self.payable_account = frappe.get_cached_value('Company', self.company, 'default_expense_claim_payable_account')
diff --git a/erpnext/hr/doctype/leave_application/leave_application.py b/erpnext/hr/doctype/leave_application/leave_application.py
index 350ceadccd..0bf551e178 100755
--- a/erpnext/hr/doctype/leave_application/leave_application.py
+++ b/erpnext/hr/doctype/leave_application/leave_application.py
@@ -6,7 +6,7 @@ import frappe
from frappe import _
from frappe.utils import cint, cstr, date_diff, flt, formatdate, getdate, get_link_to_form, \
comma_or, get_fullname, add_days, nowdate, get_datetime_str
-from erpnext.hr.utils import set_employee_name, get_leave_period
+from erpnext.hr.utils import set_employee_name, get_leave_period, share_doc_with_approver
from erpnext.hr.doctype.leave_block_list.leave_block_list import get_applicable_block_dates
from erpnext.hr.doctype.employee.employee import get_holiday_list_for_employee
from erpnext.buying.doctype.supplier_scorecard.supplier_scorecard import daterange
@@ -43,6 +43,8 @@ class LeaveApplication(Document):
if frappe.db.get_single_value("HR Settings", "send_leave_notification"):
self.notify_leave_approver()
+ share_doc_with_approver(self, self.leave_approver)
+
def on_submit(self):
if self.status == "Open":
frappe.throw(_("Only Leave Applications with status 'Approved' and 'Rejected' can be submitted"))
@@ -417,6 +419,7 @@ class LeaveApplication(Document):
))
create_leave_ledger_entry(self, args, submit)
+
def get_allocation_expiry(employee, leave_type, to_date, from_date):
''' Returns expiry of carry forward allocation in leave ledger entry '''
expiry = frappe.get_all("Leave Ledger Entry",
diff --git a/erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py b/erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py
index 63559c4f5a..66dced4cc6 100644
--- a/erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py
+++ b/erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py
@@ -52,7 +52,9 @@ def create_leave_ledger_entry(ref_doc, args, submit=True):
ledger.update(args)
if submit:
- frappe.get_doc(ledger).submit()
+ doc = frappe.get_doc(ledger)
+ doc.flags.ignore_permissions = 1
+ doc.submit()
else:
delete_ledger_entry(ledger)
diff --git a/erpnext/hr/doctype/shift_request/shift_request.py b/erpnext/hr/doctype/shift_request/shift_request.py
index 473193d5ac..177c45edc6 100644
--- a/erpnext/hr/doctype/shift_request/shift_request.py
+++ b/erpnext/hr/doctype/shift_request/shift_request.py
@@ -7,6 +7,7 @@ import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import formatdate, getdate
+from erpnext.hr.utils import share_doc_with_approver
class OverlapError(frappe.ValidationError): pass
@@ -17,6 +18,9 @@ class ShiftRequest(Document):
self.validate_approver()
self.validate_default_shift()
+ def on_update(self):
+ share_doc_with_approver(self, self.approver)
+
def on_submit(self):
if self.status not in ["Approved", "Rejected"]:
frappe.throw(_("Only Shift Request with status 'Approved' and 'Rejected' can be submitted"))
@@ -29,6 +33,7 @@ class ShiftRequest(Document):
if self.to_date:
assignment_doc.end_date = self.to_date
assignment_doc.shift_request = self.name
+ assignment_doc.flags.ignore_permissions = 1
assignment_doc.insert()
assignment_doc.submit()
diff --git a/erpnext/hr/utils.py b/erpnext/hr/utils.py
index 0c4c1cafb0..e23dba4533 100644
--- a/erpnext/hr/utils.py
+++ b/erpnext/hr/utils.py
@@ -504,3 +504,23 @@ def grant_leaves_automatically():
lpa = frappe.db.get_all("Leave Policy Assignment", filters={"effective_from": getdate(), "docstatus": 1, "leaves_allocated":0})
for assignment in lpa:
frappe.get_doc("Leave Policy Assignment", assignment.name).grant_leave_alloc_for_employee()
+
+def share_doc_with_approver(doc, user):
+ # if approver does not have permissions, share
+ if not frappe.has_permission(doc=doc, ptype="submit", user=user):
+ frappe.share.add(doc.doctype, doc.name, user, submit=1)
+ frappe.msgprint(_("Shared with the user {0} with {1} access").format(
+ user, frappe.bold("submit"), alert=True))
+
+ # remove shared doc if approver changes
+ doc_before_save = doc.get_doc_before_save()
+ if doc_before_save:
+ approvers = {
+ "Leave Application": "leave_approver",
+ "Expense Claim": "expense_approver",
+ "Shift Request": "approver"
+ }
+
+ approver = approvers.get(doc.doctype)
+ if doc_before_save.get(approver) != doc.get(approver):
+ frappe.share.remove(doc.doctype, doc.name, doc_before_save.get(approver))
From 13c0a350afee9321f3e97faf72daad8b6f0e196d Mon Sep 17 00:00:00 2001
From: Rucha Mahabal
Date: Sun, 4 Apr 2021 18:37:46 +0530
Subject: [PATCH 150/207] test: leave, expense, shift request approver
permissions
---
.../expense_claim/test_expense_claim.py | 27 +++++++
.../test_leave_application.py | 41 +++++++++++
.../shift_request/test_shift_request.py | 73 +++++++++++++++----
3 files changed, 128 insertions(+), 13 deletions(-)
diff --git a/erpnext/hr/doctype/expense_claim/test_expense_claim.py b/erpnext/hr/doctype/expense_claim/test_expense_claim.py
index f9e3a441bf..df3a81d977 100644
--- a/erpnext/hr/doctype/expense_claim/test_expense_claim.py
+++ b/erpnext/hr/doctype/expense_claim/test_expense_claim.py
@@ -110,6 +110,33 @@ class TestExpenseClaim(unittest.TestCase):
gl_entry = frappe.get_all('GL Entry', {'voucher_type': 'Expense Claim', 'voucher_no': expense_claim.name})
self.assertEquals(len(gl_entry), 0)
+ def test_expense_approver_perms(self):
+ user = "test_approver_perm_emp@example.com"
+ approver = make_employee(user, "_Test Company")
+
+ # check doc shared
+ payable_account = get_payable_account("_Test Company")
+ expense_claim = make_expense_claim(payable_account, 300, 200, "_Test Company", "Travel Expenses - _TC", do_not_submit=True)
+ expense_claim.expense_approver = user
+ expense_claim.save()
+ self.assertTrue(expense_claim.name in frappe.share.get_shared("Expense Claim", user))
+
+ # check shared doc revoked
+ expense_claim.reload()
+ expense_claim.expense_approver = "test@example.com"
+ expense_claim.save()
+ self.assertTrue(expense_claim.name not in frappe.share.get_shared("Expense Claim", user))
+
+ expense_claim.reload()
+ expense_claim.expense_approver = user
+ expense_claim.save()
+
+ frappe.set_user(user)
+ expense_claim.reload()
+ expense_claim.status = "Approved"
+ expense_claim.submit()
+
+
def get_payable_account(company):
return frappe.get_cached_value('Company', company, 'default_payable_account')
diff --git a/erpnext/hr/doctype/leave_application/test_leave_application.py b/erpnext/hr/doctype/leave_application/test_leave_application.py
index b335c48594..0d561951a1 100644
--- a/erpnext/hr/doctype/leave_application/test_leave_application.py
+++ b/erpnext/hr/doctype/leave_application/test_leave_application.py
@@ -11,6 +11,7 @@ from frappe.utils import add_days, nowdate, now_datetime, getdate, add_months
from erpnext.hr.doctype.leave_type.test_leave_type import create_leave_type
from erpnext.hr.doctype.leave_allocation.test_leave_allocation import create_leave_allocation
from erpnext.hr.doctype.leave_policy_assignment.leave_policy_assignment import create_assignment_for_multiple_employees
+from erpnext.hr.doctype.employee.test_employee import make_employee
test_dependencies = ["Leave Allocation", "Leave Block List", "Employee"]
@@ -565,6 +566,46 @@ class TestLeaveApplication(unittest.TestCase):
self.assertEquals(get_leave_balance_on(employee.name, leave_type.name, add_days(nowdate(), -85), add_days(nowdate(), -84)), 0)
+ def test_leave_approver_perms(self):
+ employee = get_employee()
+ user = "test_approver_perm_emp@example.com"
+ approver = make_employee(user, "_Test Company")
+
+ # set approver for employee
+ employee.reload()
+ employee.leave_approver = user
+ employee.save()
+ self.assertTrue("Leave Approver" in frappe.get_roles(user))
+
+ make_allocation_record(employee.name)
+
+ application = self.get_application(_test_records[0])
+ application.leave_approver = user
+ application.insert()
+ self.assertTrue(application.name in frappe.share.get_shared("Leave Application", user))
+
+ # check shared doc revoked
+ application.reload()
+ application.leave_approver = "test@example.com"
+ application.save()
+ self.assertTrue(application.name not in frappe.share.get_shared("Leave Application", user))
+
+ application.reload()
+ application.leave_approver = user
+ application.save()
+
+ frappe.set_user(user)
+ application.reload()
+ application.status = "Approved"
+ application.submit()
+
+ # unset leave approver
+ frappe.set_user("Administrator")
+ employee.reload()
+ employee.leave_approver = ""
+ employee.save()
+
+
def create_carry_forwarded_allocation(employee, leave_type):
# initial leave allocation
leave_allocation = create_leave_allocation(
diff --git a/erpnext/hr/doctype/shift_request/test_shift_request.py b/erpnext/hr/doctype/shift_request/test_shift_request.py
index 230bb2b0e4..fd8dbd6a2b 100644
--- a/erpnext/hr/doctype/shift_request/test_shift_request.py
+++ b/erpnext/hr/doctype/shift_request/test_shift_request.py
@@ -6,6 +6,7 @@ from __future__ import unicode_literals
import frappe
import unittest
from frappe.utils import nowdate, add_days
+from erpnext.hr.doctype.employee.test_employee import make_employee
test_dependencies = ["Shift Type"]
@@ -19,19 +20,8 @@ class TestShiftRequest(unittest.TestCase):
set_shift_approver(department)
approver = frappe.db.sql("""select approver from `tabDepartment Approver` where parent= %s and parentfield = 'shift_request_approver'""", (department))[0][0]
- shift_request = frappe.get_doc({
- "doctype": "Shift Request",
- "shift_type": "Day Shift",
- "company": "_Test Company",
- "employee": "_T-Employee-00001",
- "employee_name": "_Test Employee",
- "from_date": nowdate(),
- "to_date": add_days(nowdate(), 10),
- "approver": approver,
- "status": "Approved"
- })
- shift_request.insert()
- shift_request.submit()
+ shift_request = make_shift_request(approver)
+
shift_assignments = frappe.db.sql('''
SELECT shift_request, employee
FROM `tabShift Assignment`
@@ -44,8 +34,65 @@ class TestShiftRequest(unittest.TestCase):
shift_assignment_doc = frappe.get_doc("Shift Assignment", {"shift_request": d.get('shift_request')})
self.assertEqual(shift_assignment_doc.docstatus, 2)
+ def test_shift_request_approver_perms(self):
+ employee = frappe.get_doc("Employee", "_T-Employee-00001")
+ user = "test_approver_perm_emp@example.com"
+ approver = make_employee(user, "_Test Company")
+
+ # set approver for employee
+ employee.reload()
+ employee.shift_request_approver = user
+ employee.save()
+
+ shift_request = make_shift_request(user, do_not_submit=True)
+ self.assertTrue(shift_request.name in frappe.share.get_shared("Shift Request", user))
+
+ # check shared doc revoked
+ shift_request.reload()
+ department = frappe.get_value("Employee", "_T-Employee-00001", "department")
+ set_shift_approver(department)
+ department_approver = frappe.db.sql("""select approver from `tabDepartment Approver` where parent= %s and parentfield = 'shift_request_approver'""", (department))[0][0]
+ shift_request.approver = department_approver
+ shift_request.save()
+ self.assertTrue(shift_request.name not in frappe.share.get_shared("Shift Request", user))
+
+ shift_request.reload()
+ shift_request.approver = user
+ shift_request.save()
+
+ frappe.set_user(user)
+ shift_request.reload()
+ shift_request.status = "Approved"
+ shift_request.submit()
+
+ # unset approver
+ frappe.set_user("Administrator")
+ employee.reload()
+ employee.shift_request_approver = ""
+ employee.save()
+
+
def set_shift_approver(department):
department_doc = frappe.get_doc("Department", department)
department_doc.append('shift_request_approver',{'approver': "test1@example.com"})
department_doc.save()
department_doc.reload()
+
+def make_shift_request(approver, do_not_submit=0):
+ shift_request = frappe.get_doc({
+ "doctype": "Shift Request",
+ "shift_type": "Day Shift",
+ "company": "_Test Company",
+ "employee": "_T-Employee-00001",
+ "employee_name": "_Test Employee",
+ "from_date": nowdate(),
+ "to_date": add_days(nowdate(), 10),
+ "approver": approver,
+ "status": "Approved"
+ }).insert()
+
+ if do_not_submit:
+ return shift_request
+
+ shift_request.submit()
+ return shift_request
\ No newline at end of file
From 8c055b546971502bf802f5398bcf5d610e726f5f Mon Sep 17 00:00:00 2001
From: Rucha Mahabal
Date: Sun, 4 Apr 2021 18:45:06 +0530
Subject: [PATCH 151/207] fix: ignore share permission while sharing doc with
approver
---
erpnext/hr/utils.py | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/erpnext/hr/utils.py b/erpnext/hr/utils.py
index e23dba4533..190eb4f10a 100644
--- a/erpnext/hr/utils.py
+++ b/erpnext/hr/utils.py
@@ -508,7 +508,9 @@ def grant_leaves_automatically():
def share_doc_with_approver(doc, user):
# if approver does not have permissions, share
if not frappe.has_permission(doc=doc, ptype="submit", user=user):
- frappe.share.add(doc.doctype, doc.name, user, submit=1)
+ frappe.share.add(doc.doctype, doc.name, user, submit=1,
+ flags={"ignore_share_permission": True})
+
frappe.msgprint(_("Shared with the user {0} with {1} access").format(
user, frappe.bold("submit"), alert=True))
From 19c3286b06200769d32ba60287c2698b76aa252b Mon Sep 17 00:00:00 2001
From: Rucha Mahabal
Date: Sun, 4 Apr 2021 19:54:00 +0530
Subject: [PATCH 152/207] fix: linter and sider issues
---
.../expense_claim/test_expense_claim.py | 32 +++++++++----------
.../test_leave_application.py | 12 +++----
.../leave_ledger_entry/leave_ledger_entry.py | 4 +--
.../shift_request/test_shift_request.py | 2 +-
4 files changed, 25 insertions(+), 25 deletions(-)
diff --git a/erpnext/hr/doctype/expense_claim/test_expense_claim.py b/erpnext/hr/doctype/expense_claim/test_expense_claim.py
index df3a81d977..1c5b69b0cc 100644
--- a/erpnext/hr/doctype/expense_claim/test_expense_claim.py
+++ b/erpnext/hr/doctype/expense_claim/test_expense_claim.py
@@ -95,12 +95,12 @@ class TestExpenseClaim(unittest.TestCase):
def test_rejected_expense_claim(self):
payable_account = get_payable_account(company_name)
expense_claim = frappe.get_doc({
- "doctype": "Expense Claim",
- "employee": "_T-Employee-00001",
- "payable_account": payable_account,
- "approval_status": "Rejected",
- "expenses":
- [{ "expense_type": "Travel", "default_account": "Travel Expenses - _TC4", "amount": 300, "sanctioned_amount": 200 }]
+ "doctype": "Expense Claim",
+ "employee": "_T-Employee-00001",
+ "payable_account": payable_account,
+ "approval_status": "Rejected",
+ "expenses":
+ [{ "expense_type": "Travel", "default_account": "Travel Expenses - _TC4", "amount": 300, "sanctioned_amount": 200 }]
})
expense_claim.submit()
@@ -112,7 +112,7 @@ class TestExpenseClaim(unittest.TestCase):
def test_expense_approver_perms(self):
user = "test_approver_perm_emp@example.com"
- approver = make_employee(user, "_Test Company")
+ make_employee(user, "_Test Company")
# check doc shared
payable_account = get_payable_account("_Test Company")
@@ -160,21 +160,21 @@ def make_expense_claim(payable_account, amount, sanctioned_amount, company, acco
currency, cost_center = frappe.db.get_value('Company', company, ['default_currency', 'cost_center'])
expense_claim = {
- "doctype": "Expense Claim",
- "employee": employee,
- "payable_account": payable_account,
- "approval_status": "Approved",
- "company": company,
- 'currency': currency,
- "expenses": [{
+ "doctype": "Expense Claim",
+ "employee": employee,
+ "payable_account": payable_account,
+ "approval_status": "Approved",
+ "company": company,
+ "currency": currency,
+ "expenses": [{
"expense_type": "Travel",
"default_account": account,
"currency": currency,
"amount": amount,
"sanctioned_amount": sanctioned_amount,
"cost_center": cost_center
- }]
- }
+ }]
+ }
if taxes:
expense_claim.update(taxes)
diff --git a/erpnext/hr/doctype/leave_application/test_leave_application.py b/erpnext/hr/doctype/leave_application/test_leave_application.py
index 0d561951a1..a5f9528de1 100644
--- a/erpnext/hr/doctype/leave_application/test_leave_application.py
+++ b/erpnext/hr/doctype/leave_application/test_leave_application.py
@@ -342,7 +342,7 @@ class TestLeaveApplication(unittest.TestCase):
to_date = add_days(date, 4),
company = "_Test Company",
docstatus = 1,
- status = "Approved"
+ status = "Approved"
))
self.assertRaises(frappe.ValidationError, leave_application.insert)
@@ -364,7 +364,7 @@ class TestLeaveApplication(unittest.TestCase):
to_date = add_days(date, 4),
company = "_Test Company",
docstatus = 1,
- status = "Approved"
+ status = "Approved"
))
self.assertTrue(leave_application.insert())
@@ -394,7 +394,7 @@ class TestLeaveApplication(unittest.TestCase):
to_date = add_days(date, 4),
company = "_Test Company",
docstatus = 1,
- status = "Approved"
+ status = "Approved"
))
self.assertRaises(frappe.ValidationError, leave_application.insert)
@@ -509,7 +509,7 @@ class TestLeaveApplication(unittest.TestCase):
description = "_Test Reason",
company = "_Test Company",
docstatus = 1,
- status = "Approved"
+ status = "Approved"
))
leave_application.submit()
leave_ledger_entry = frappe.get_all('Leave Ledger Entry', fields='*', filters=dict(transaction_name=leave_application.name))
@@ -541,7 +541,7 @@ class TestLeaveApplication(unittest.TestCase):
description = "_Test Reason",
company = "_Test Company",
docstatus = 1,
- status = "Approved"
+ status = "Approved"
))
leave_application.submit()
@@ -569,7 +569,7 @@ class TestLeaveApplication(unittest.TestCase):
def test_leave_approver_perms(self):
employee = get_employee()
user = "test_approver_perm_emp@example.com"
- approver = make_employee(user, "_Test Company")
+ make_employee(user, "_Test Company")
# set approver for employee
employee.reload()
diff --git a/erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py b/erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py
index 66dced4cc6..cf13036181 100644
--- a/erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py
+++ b/erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py
@@ -34,8 +34,8 @@ def validate_leave_allocation_against_leave_application(ledger):
""", (ledger.employee, ledger.leave_type, ledger.from_date, ledger.to_date))
if leave_application_records:
- frappe.throw(_("Leave allocation %s is linked with leave application %s"
- % (ledger.transaction_name, ', '.join(leave_application_records))))
+ frappe.throw(_("Leave allocation {0} is linked with the Leave Application {1}").format(
+ ledger.transaction_name, ', '.join(leave_application_records)))
def create_leave_ledger_entry(ref_doc, args, submit=True):
ledger = frappe._dict(
diff --git a/erpnext/hr/doctype/shift_request/test_shift_request.py b/erpnext/hr/doctype/shift_request/test_shift_request.py
index fd8dbd6a2b..9c0d8e3198 100644
--- a/erpnext/hr/doctype/shift_request/test_shift_request.py
+++ b/erpnext/hr/doctype/shift_request/test_shift_request.py
@@ -37,7 +37,7 @@ class TestShiftRequest(unittest.TestCase):
def test_shift_request_approver_perms(self):
employee = frappe.get_doc("Employee", "_T-Employee-00001")
user = "test_approver_perm_emp@example.com"
- approver = make_employee(user, "_Test Company")
+ make_employee(user, "_Test Company")
# set approver for employee
employee.reload()
From b7436a04c3f7b0b38df86d8f6a4870c866c973ac Mon Sep 17 00:00:00 2001
From: Rucha Mahabal
Date: Sun, 4 Apr 2021 20:09:00 +0530
Subject: [PATCH 153/207] fix: Ignore Permission for Leave Ledger Entry
(#25172)
---
erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py b/erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py
index 63559c4f5a..66dced4cc6 100644
--- a/erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py
+++ b/erpnext/hr/doctype/leave_ledger_entry/leave_ledger_entry.py
@@ -52,7 +52,9 @@ def create_leave_ledger_entry(ref_doc, args, submit=True):
ledger.update(args)
if submit:
- frappe.get_doc(ledger).submit()
+ doc = frappe.get_doc(ledger)
+ doc.flags.ignore_permissions = 1
+ doc.submit()
else:
delete_ledger_entry(ledger)
From 36ff0748bfa019a5808de3b52f94db0c3e5fbfda Mon Sep 17 00:00:00 2001
From: Ankush Menat
Date: Sun, 4 Apr 2021 18:27:01 +0530
Subject: [PATCH 154/207] fix: broken type check in stock ageing report
---
erpnext/stock/report/stock_ageing/stock_ageing.py | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/erpnext/stock/report/stock_ageing/stock_ageing.py b/erpnext/stock/report/stock_ageing/stock_ageing.py
index ff603fcfb3..623dc2ffd9 100644
--- a/erpnext/stock/report/stock_ageing/stock_ageing.py
+++ b/erpnext/stock/report/stock_ageing/stock_ageing.py
@@ -49,7 +49,7 @@ def get_average_age(fifo_queue, to_date):
for batch in fifo_queue:
batch_age = date_diff(to_date, batch[1])
- if type(batch[0]) in ['int', 'float']:
+ if isinstance(batch[0], (int, float)):
age_qty += batch_age * batch[0]
total_qty += batch[0]
else:
@@ -302,4 +302,4 @@ def add_column(range_columns, label, fieldname, fieldtype='Float', width=140):
fieldname=fieldname,
fieldtype=fieldtype,
width=width
- ))
\ No newline at end of file
+ ))
From b27441b40c72759742b980e0c4fe18f833c39b20 Mon Sep 17 00:00:00 2001
From: Anoop
Date: Mon, 5 Apr 2021 10:41:28 +0530
Subject: [PATCH 155/207] fix: failing patch - reload_doc new doctypes added in
v13 (#25194)
---
.../setup_patient_history_settings_for_standard_doctypes.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/erpnext/patches/v13_0/setup_patient_history_settings_for_standard_doctypes.py b/erpnext/patches/v13_0/setup_patient_history_settings_for_standard_doctypes.py
index de08aa26b3..2d3b096915 100644
--- a/erpnext/patches/v13_0/setup_patient_history_settings_for_standard_doctypes.py
+++ b/erpnext/patches/v13_0/setup_patient_history_settings_for_standard_doctypes.py
@@ -6,6 +6,8 @@ def execute():
if "Healthcare" not in frappe.get_active_domains():
return
+ frappe.reload_doc("healthcare", "doctype", "Therapy Session")
+ frappe.reload_doc("healthcare", "doctype", "Inpatient Medication Order")
frappe.reload_doc("healthcare", "doctype", "Patient History Settings")
frappe.reload_doc("healthcare", "doctype", "Patient History Standard Document Type")
frappe.reload_doc("healthcare", "doctype", "Patient History Custom Document Type")
From 8789ef16a17d55de10836faa01ad0650c201a9e5 Mon Sep 17 00:00:00 2001
From: Walstan Baptista <38958184+walstanb@users.noreply.github.com>
Date: Mon, 5 Apr 2021 13:18:03 +0530
Subject: [PATCH 156/207] test: uses `_Test Item` instead of `_Test Item Home
Desktop 100` (#25198)
---
.../stock/doctype/pick_list/test_pick_list.py | 20 +++++++++----------
1 file changed, 10 insertions(+), 10 deletions(-)
diff --git a/erpnext/stock/doctype/pick_list/test_pick_list.py b/erpnext/stock/doctype/pick_list/test_pick_list.py
index 8ea7f89dc4..01f2b0b27c 100644
--- a/erpnext/stock/doctype/pick_list/test_pick_list.py
+++ b/erpnext/stock/doctype/pick_list/test_pick_list.py
@@ -22,7 +22,7 @@ class TestPickList(unittest.TestCase):
'purpose': 'Opening Stock',
'expense_account': 'Temporary Opening - _TC',
'items': [{
- 'item_code': '_Test Item Home Desktop 100',
+ 'item_code': '_Test Item',
'warehouse': '_Test Warehouse - _TC',
'valuation_rate': 100,
'qty': 5
@@ -37,7 +37,7 @@ class TestPickList(unittest.TestCase):
'customer': '_Test Customer',
'items_based_on': 'Sales Order',
'locations': [{
- 'item_code': '_Test Item Home Desktop 100',
+ 'item_code': '_Test Item',
'qty': 5,
'stock_qty': 5,
'conversion_factor': 1,
@@ -47,7 +47,7 @@ class TestPickList(unittest.TestCase):
})
pick_list.set_item_locations()
- self.assertEqual(pick_list.locations[0].item_code, '_Test Item Home Desktop 100')
+ self.assertEqual(pick_list.locations[0].item_code, '_Test Item')
self.assertEqual(pick_list.locations[0].warehouse, '_Test Warehouse - _TC')
self.assertEqual(pick_list.locations[0].qty, 5)
@@ -237,7 +237,7 @@ class TestPickList(unittest.TestCase):
'purpose': 'Opening Stock',
'expense_account': 'Temporary Opening - _TC',
'items': [{
- 'item_code': '_Test Item Home Desktop 100',
+ 'item_code': '_Test Item',
'warehouse': '_Test Warehouse - _TC',
'valuation_rate': 100,
'qty': 10
@@ -251,7 +251,7 @@ class TestPickList(unittest.TestCase):
'customer': '_Test Customer',
'company': '_Test Company',
'items': [{
- 'item_code': '_Test Item Home Desktop 100',
+ 'item_code': '_Test Item',
'qty': 10,
'delivery_date': frappe.utils.today()
}],
@@ -264,14 +264,14 @@ class TestPickList(unittest.TestCase):
'customer': '_Test Customer',
'items_based_on': 'Sales Order',
'locations': [{
- 'item_code': '_Test Item Home Desktop 100',
+ 'item_code': '_Test Item',
'qty': 5,
'stock_qty': 5,
'conversion_factor': 1,
'sales_order': '_T-Sales Order-1',
'sales_order_item': '_T-Sales Order-1_item',
}, {
- 'item_code': '_Test Item Home Desktop 100',
+ 'item_code': '_Test Item',
'qty': 5,
'stock_qty': 5,
'conversion_factor': 1,
@@ -281,12 +281,12 @@ class TestPickList(unittest.TestCase):
})
pick_list.set_item_locations()
- self.assertEqual(pick_list.locations[0].item_code, '_Test Item Home Desktop 100')
+ self.assertEqual(pick_list.locations[0].item_code, '_Test Item')
self.assertEqual(pick_list.locations[0].warehouse, '_Test Warehouse - _TC')
self.assertEqual(pick_list.locations[0].qty, 5)
self.assertEqual(pick_list.locations[0].sales_order_item, '_T-Sales Order-1_item')
- self.assertEqual(pick_list.locations[1].item_code, '_Test Item Home Desktop 100')
+ self.assertEqual(pick_list.locations[1].item_code, '_Test Item')
self.assertEqual(pick_list.locations[1].warehouse, '_Test Warehouse - _TC')
self.assertEqual(pick_list.locations[1].qty, 5)
self.assertEqual(pick_list.locations[1].sales_order_item, sales_order.items[0].name)
@@ -302,4 +302,4 @@ class TestPickList(unittest.TestCase):
# pass
# def test_pick_list_from_material_request(self):
- # pass
\ No newline at end of file
+ # pass
From 9a0907131a493828221b701923e12b8f03d278a0 Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Mon, 5 Apr 2021 14:50:09 +0530
Subject: [PATCH 157/207] test: create tax rule if it doesnt exist (#25199)
---
erpnext/shopping_cart/test_shopping_cart.py | 13 +++++++++++++
1 file changed, 13 insertions(+)
diff --git a/erpnext/shopping_cart/test_shopping_cart.py b/erpnext/shopping_cart/test_shopping_cart.py
index cf59a52b5b..470a402a4a 100644
--- a/erpnext/shopping_cart/test_shopping_cart.py
+++ b/erpnext/shopping_cart/test_shopping_cart.py
@@ -16,6 +16,11 @@ class TestShoppingCart(unittest.TestCase):
Note:
Shopping Cart == Quotation
"""
+
+ @classmethod
+ def tearDownClass(cls):
+ frappe.db.sql("delete from `tabTax Rule`")
+
def setUp(self):
frappe.set_user("Administrator")
create_test_contact_and_address()
@@ -100,6 +105,7 @@ class TestShoppingCart(unittest.TestCase):
self.assertEqual(len(quotation.get("items")), 1)
def test_tax_rule(self):
+ self.create_tax_rule()
self.login_as_customer()
quotation = self.create_quotation()
@@ -115,6 +121,13 @@ class TestShoppingCart(unittest.TestCase):
self.remove_test_quotation(quotation)
+ def create_tax_rule(self):
+ tax_rule = frappe.get_test_records("Tax Rule")[0]
+ try:
+ frappe.get_doc(tax_rule).insert()
+ except frappe.DuplicateEntryError:
+ pass
+
def create_quotation(self):
quotation = frappe.new_doc("Quotation")
From 9967a7ce021fa53eb2b8b7bc2c2b3cfa6e83b03f Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Mon, 5 Apr 2021 15:35:52 +0530
Subject: [PATCH 158/207] test: clear all existing quotations to avoid
AssertionError (#25202)
---
erpnext/shopping_cart/test_shopping_cart.py | 17 +++++++++++------
1 file changed, 11 insertions(+), 6 deletions(-)
diff --git a/erpnext/shopping_cart/test_shopping_cart.py b/erpnext/shopping_cart/test_shopping_cart.py
index 470a402a4a..d857bf5f5c 100644
--- a/erpnext/shopping_cart/test_shopping_cart.py
+++ b/erpnext/shopping_cart/test_shopping_cart.py
@@ -56,8 +56,8 @@ class TestShoppingCart(unittest.TestCase):
def test_add_to_cart(self):
self.login_as_customer()
- # remove from cart
- self.remove_all_items_from_cart()
+ # clear existing quotations
+ self.clear_existing_quotations()
# add first item
update_cart("_Test Item", 1)
@@ -208,10 +208,15 @@ class TestShoppingCart(unittest.TestCase):
"_Test Contact For _Test Customer")
frappe.set_user("test_contact_customer@example.com")
- def remove_all_items_from_cart(self):
- quotation = _get_cart_quotation()
- quotation.flags.ignore_permissions=True
- quotation.delete()
+ def clear_existing_quotations(self):
+ quotations = frappe.get_all("Quotation", filters={
+ "party_name": get_party().name,
+ "order_type": "Shopping Cart",
+ "docstatus": 0
+ }, order_by="modified desc", pluck="name")
+
+ for quotation in quotations:
+ frappe.delete_doc("Quotation", quotation, ignore_permissions=True, force=True)
def create_user_if_not_exists(self, email, first_name = None):
if frappe.db.exists("User", email):
From c9cdf74dc51edaf2059f17f36f0189b8f9bfbb32 Mon Sep 17 00:00:00 2001
From: Sagar Vora
Date: Mon, 5 Apr 2021 16:38:10 +0530
Subject: [PATCH 159/207] test: remove `print()` (#25205)
---
.../accounts/doctype/bank_transaction/test_bank_transaction.py | 1 -
1 file changed, 1 deletion(-)
diff --git a/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py b/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py
index 17e39d562a..ce149f96e6 100644
--- a/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py
+++ b/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py
@@ -61,7 +61,6 @@ class TestBankTransaction(unittest.TestCase):
def test_debit_credit_output(self):
bank_transaction = frappe.get_doc("Bank Transaction", dict(description="Auszahlung Karte MC/000002916 AUTOMAT 698769 K002 27.10. 14:07"))
linked_payments = get_linked_payments(bank_transaction.name, ['payment_entry', 'exact_match'])
- print(linked_payments)
self.assertTrue(linked_payments[0][3])
# Check error if already reconciled
From 015fd681ec32529b7b10bfebf84f6480a2739ae5 Mon Sep 17 00:00:00 2001
From: Deepesh Garg
Date: Tue, 6 Apr 2021 00:49:46 +0530
Subject: [PATCH 160/207] fix: Give first preference to loan security on
repayment
---
.../loan_repayment/loan_repayment.json | 17 ++++++-
.../doctype/loan_repayment/loan_repayment.py | 47 ++++++++++++++-----
.../loan_security_shortfall.py | 2 +-
3 files changed, 52 insertions(+), 14 deletions(-)
diff --git a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.json b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.json
index 2b5df4be24..86ea59dc24 100644
--- a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.json
+++ b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.json
@@ -21,6 +21,7 @@
"interest_payable",
"payable_amount",
"column_break_9",
+ "shortfall_amount",
"payable_principal_amount",
"penalty_amount",
"amount_paid",
@@ -31,6 +32,7 @@
"column_break_21",
"reference_date",
"principal_amount_paid",
+ "total_penalty_paid",
"total_interest_paid",
"repayment_details",
"amended_from"
@@ -226,12 +228,25 @@
"fieldtype": "Percent",
"label": "Rate Of Interest",
"read_only": 1
+ },
+ {
+ "fieldname": "shortfall_amount",
+ "fieldtype": "Currency",
+ "label": "Shortfall Amount",
+ "options": "Company:company:default_currency",
+ "read_only": 1
+ },
+ {
+ "fieldname": "total_penalty_paid",
+ "fieldtype": "Currency",
+ "label": "Total Penalty Paid",
+ "options": "Company:company:default_currency"
}
],
"index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [],
- "modified": "2020-11-05 10:06:58.792841",
+ "modified": "2021-04-05 13:45:19.137896",
"modified_by": "Administrator",
"module": "Loan Management",
"name": "Loan Repayment",
diff --git a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
index bac06c4e9e..a88e183ead 100644
--- a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
+++ b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
@@ -60,6 +60,12 @@ class LoanRepayment(AccountsController):
if not self.payable_amount:
self.payable_amount = flt(amounts['payable_amount'], precision)
+ shortfall_amount = flt(frappe.db.get_value('Loan Security Shortfall', {'loan': self.against_loan, 'status': 'Pending'},
+ 'shortfall_amount'))
+
+ if shortfall_amount:
+ self.shortfall_amount = shortfall_amount
+
if amounts.get('due_date'):
self.due_date = amounts.get('due_date')
@@ -69,7 +75,7 @@ class LoanRepayment(AccountsController):
if not self.amount_paid:
frappe.throw(_("Amount paid cannot be zero"))
- if self.amount_paid < self.penalty_amount:
+ if not self.shortfall_amount and self.amount_paid < self.penalty_amount:
msg = _("Paid amount cannot be less than {0}").format(self.penalty_amount)
frappe.throw(msg)
@@ -148,11 +154,28 @@ class LoanRepayment(AccountsController):
def allocate_amounts(self, repayment_details):
self.set('repayment_details', [])
self.principal_amount_paid = 0
- total_interest_paid = 0
- interest_paid = self.amount_paid - self.penalty_amount
+ self.total_penalty_paid = 0
+ interest_paid = self.amount_paid
- if self.amount_paid - self.penalty_amount > 0:
- interest_paid = self.amount_paid - self.penalty_amount
+ if self.shortfall_amount and self.amount_paid > self.shortfall_amount:
+ self.principal_amount_paid = self.shortfall_amount
+ elif self.shortfall_amount:
+ self.principal_amount_paid = self.amount_paid
+
+ interest_paid -= self.principal_amount_paid
+
+ if interest_paid > 0:
+ if self.penalty_amount and interest_paid > self.penalty_amount:
+ self.total_penalty_paid = self.penalty_amount
+ elif self.penalty_amount:
+ self.total_penalty_paid = interest_paid
+
+ interest_paid -= self.total_penalty_paid
+
+ total_interest_paid = 0
+ # interest_paid = self.amount_paid - self.principal_amount_paid - self.penalty_amount
+
+ if interest_paid > 0:
for lia, amounts in iteritems(repayment_details.get('pending_accrual_entries', [])):
if amounts['interest_amount'] + amounts['payable_principal_amount'] <= interest_paid:
interest_amount = amounts['interest_amount']
@@ -177,7 +200,7 @@ class LoanRepayment(AccountsController):
'paid_principal_amount': paid_principal
})
- if repayment_details['unaccrued_interest'] and interest_paid:
+ if repayment_details['unaccrued_interest'] and interest_paid > 0:
# no of days for which to accrue interest
# Interest can only be accrued for an entire day and not partial
if interest_paid > repayment_details['unaccrued_interest']:
@@ -193,20 +216,20 @@ class LoanRepayment(AccountsController):
interest_paid -= no_of_days * per_day_interest
self.total_interest_paid = total_interest_paid
- if interest_paid:
+ if interest_paid > 0:
self.principal_amount_paid += interest_paid
def make_gl_entries(self, cancel=0, adv_adj=0):
gle_map = []
loan_details = frappe.get_doc("Loan", self.against_loan)
- if self.penalty_amount:
+ if self.total_penalty_paid:
gle_map.append(
self.get_gl_dict({
"account": loan_details.loan_account,
"against": loan_details.payment_account,
- "debit": self.penalty_amount,
- "debit_in_account_currency": self.penalty_amount,
+ "debit": self.total_penalty_paid,
+ "debit_in_account_currency": self.total_penalty_paid,
"against_voucher_type": "Loan",
"against_voucher": self.against_loan,
"remarks": _("Penalty against loan:") + self.against_loan,
@@ -221,8 +244,8 @@ class LoanRepayment(AccountsController):
self.get_gl_dict({
"account": loan_details.penalty_income_account,
"against": loan_details.payment_account,
- "credit": self.penalty_amount,
- "credit_in_account_currency": self.penalty_amount,
+ "credit": self.total_penalty_paid,
+ "credit_in_account_currency": self.total_penalty_paid,
"against_voucher_type": "Loan",
"against_voucher": self.against_loan,
"remarks": _("Penalty against loan:") + self.against_loan,
diff --git a/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.py b/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.py
index b5e78981d0..ada3a679f9 100644
--- a/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.py
+++ b/erpnext/loan_management/doctype/loan_security_shortfall/loan_security_shortfall.py
@@ -12,7 +12,7 @@ from erpnext.loan_management.doctype.loan_security_unpledge.loan_security_unpled
class LoanSecurityShortfall(Document):
pass
-def update_shortfall_status(loan, security_value):
+def update_shortfall_status(loan, security_value, on_cancel=0):
loan_security_shortfall = frappe.db.get_value("Loan Security Shortfall",
{"loan": loan, "status": "Pending"}, ['name', 'shortfall_amount'], as_dict=1)
From 084e90e5d3127065ab00c980b25db2d717da4db8 Mon Sep 17 00:00:00 2001
From: Rucha Mahabal
Date: Tue, 6 Apr 2021 10:07:50 +0530
Subject: [PATCH 161/207] fix(test): set user as Administrator
---
erpnext/hr/doctype/expense_claim/test_expense_claim.py | 1 +
1 file changed, 1 insertion(+)
diff --git a/erpnext/hr/doctype/expense_claim/test_expense_claim.py b/erpnext/hr/doctype/expense_claim/test_expense_claim.py
index 1c5b69b0cc..3f22ca2141 100644
--- a/erpnext/hr/doctype/expense_claim/test_expense_claim.py
+++ b/erpnext/hr/doctype/expense_claim/test_expense_claim.py
@@ -135,6 +135,7 @@ class TestExpenseClaim(unittest.TestCase):
expense_claim.reload()
expense_claim.status = "Approved"
expense_claim.submit()
+ frappe.set_user("Administrator")
def get_payable_account(company):
From 7b6c8bb3ab286db0ec2c89a6e844274e3c6529e8 Mon Sep 17 00:00:00 2001
From: Anupam Kumar
Date: Tue, 6 Apr 2021 10:20:10 +0530
Subject: [PATCH 162/207] fix: error message compensatory leave request
(#25206)
---
.../compensatory_leave_request.py | 11 ++++++++---
1 file changed, 8 insertions(+), 3 deletions(-)
diff --git a/erpnext/hr/doctype/compensatory_leave_request/compensatory_leave_request.py b/erpnext/hr/doctype/compensatory_leave_request/compensatory_leave_request.py
index 7a9727f18c..aa5a67f40c 100644
--- a/erpnext/hr/doctype/compensatory_leave_request/compensatory_leave_request.py
+++ b/erpnext/hr/doctype/compensatory_leave_request/compensatory_leave_request.py
@@ -5,7 +5,7 @@
from __future__ import unicode_literals
import frappe
from frappe import _
-from frappe.utils import date_diff, add_days, getdate, cint
+from frappe.utils import date_diff, add_days, getdate, cint, format_date
from frappe.model.document import Document
from erpnext.hr.utils import validate_dates, validate_overlap, get_leave_period, \
get_holidays_for_employee, create_additional_leave_ledger_entry
@@ -40,7 +40,12 @@ class CompensatoryLeaveRequest(Document):
def validate_holidays(self):
holidays = get_holidays_for_employee(self.employee, self.work_from_date, self.work_end_date)
if len(holidays) < date_diff(self.work_end_date, self.work_from_date) + 1:
- frappe.throw(_("Compensatory leave request days not in valid holidays"))
+ if date_diff(self.work_end_date, self.work_from_date):
+ msg = _("The days between {0} to {1} are not valid holidays.").format(frappe.bold(format_date(self.work_from_date)), frappe.bold(format_date(self.work_end_date)))
+ else:
+ msg = _("{0} is not a holiday.").format(frappe.bold(format_date(self.work_from_date)))
+
+ frappe.throw(msg)
def on_submit(self):
company = frappe.db.get_value("Employee", self.employee, "company")
@@ -63,7 +68,7 @@ class CompensatoryLeaveRequest(Document):
leave_allocation = self.create_leave_allocation(leave_period, date_difference)
self.leave_allocation=leave_allocation.name
else:
- frappe.throw(_("There is no leave period in between {0} and {1}").format(self.work_from_date, self.work_end_date))
+ frappe.throw(_("There is no leave period in between {0} and {1}").format(format_date(self.work_from_date), format_date(self.work_end_date)))
def on_cancel(self):
if self.leave_allocation:
From 0bcd3c45edffb10f385ef65c8dd528086a700f2c Mon Sep 17 00:00:00 2001
From: Rucha Mahabal
Date: Tue, 6 Apr 2021 13:46:53 +0530
Subject: [PATCH 163/207] fix: leave approver perms test
---
erpnext/hr/doctype/leave_application/test_leave_application.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/erpnext/hr/doctype/leave_application/test_leave_application.py b/erpnext/hr/doctype/leave_application/test_leave_application.py
index 335e05dbab..b54c9712c8 100644
--- a/erpnext/hr/doctype/leave_application/test_leave_application.py
+++ b/erpnext/hr/doctype/leave_application/test_leave_application.py
@@ -582,6 +582,8 @@ class TestLeaveApplication(unittest.TestCase):
make_allocation_record(employee.name)
application = self.get_application(_test_records[0])
+ application.from_date = '2018-01-01'
+ application.to_date = '2018-01-03'
application.leave_approver = user
application.insert()
self.assertTrue(application.name in frappe.share.get_shared("Leave Application", user))
From d551940dc518a3c7a085dcc714c8dec34685bd5e Mon Sep 17 00:00:00 2001
From: Deepesh Garg
Date: Tue, 6 Apr 2021 23:55:48 +0530
Subject: [PATCH 164/207] fix: Remove comments
---
.../loan_management/doctype/loan_repayment/loan_repayment.py | 5 -----
1 file changed, 5 deletions(-)
diff --git a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
index b3dd949f12..2489f59670 100644
--- a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
+++ b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
@@ -31,7 +31,6 @@ class LoanRepayment(AccountsController):
def on_submit(self):
self.update_paid_amount()
self.make_gl_entries()
- #self.repost_future_loan_interest_accruals()
def on_cancel(self):
self.mark_as_unpaid()
@@ -297,10 +296,6 @@ class LoanRepayment(AccountsController):
if gle_map:
make_gl_entries(gle_map, cancel=cancel, adv_adj=adv_adj, merge_entries=False)
- # def repost_future_loan_interest_accruals(self):
- # future_lias = frappe.db.get_all("Loan Interest Accrual", {"docstatus": 1, "posting_date": (">", self.posting_date)})
- # if future_lias:
-
def create_repayment_entry(loan, applicant, company, posting_date, loan_type,
payment_type, interest_payable, payable_principal_amount, amount_paid, penalty_amount=None):
From 5af6aea9f9a94e8b77372002ddcd5180603ee079 Mon Sep 17 00:00:00 2001
From: Deepesh Garg
Date: Wed, 7 Apr 2021 09:46:13 +0530
Subject: [PATCH 165/207] fix: Posting Date check
---
.../doctype/loan_repayment/loan_repayment.py | 9 ++++++---
1 file changed, 6 insertions(+), 3 deletions(-)
diff --git a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
index 2489f59670..5d57cedb41 100644
--- a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
+++ b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
@@ -72,7 +72,7 @@ class LoanRepayment(AccountsController):
def check_future_entries(self):
future_repayment_date = frappe.db.get_value("Loan Repayment", {"posting_date": (">", self.posting_date),
- "docstatus": 1}, 'posting_date')
+ "docstatus": 1, "against_loan": self.against_loan}, 'posting_date')
if future_repayment_date:
frappe.throw("Repayment already made till date {0}".format(getdate(future_repayment_date)))
@@ -315,7 +315,10 @@ def create_repayment_entry(loan, applicant, company, posting_date, loan_type,
return lr
-def get_accrued_interest_entries(against_loan, posting_date):
+def get_accrued_interest_entries(against_loan, posting_date=None):
+ if not posting_date:
+ posting_date = getdate()
+
unpaid_accrued_entries = frappe.db.sql(
"""
SELECT name, posting_date, interest_amount - paid_interest_amount as interest_amount,
@@ -343,7 +346,7 @@ def get_amounts(amounts, against_loan, posting_date):
against_loan_doc = frappe.get_doc("Loan", against_loan)
loan_type_details = frappe.get_doc("Loan Type", against_loan_doc.loan_type)
- accrued_interest_entries = get_accrued_interest_entries(against_loan_doc.name)
+ accrued_interest_entries = get_accrued_interest_entries(against_loan_doc.name, posting_date)
pending_accrual_entries = {}
From 90e240c3e6a9231b3415df4385f743d164f12dcb Mon Sep 17 00:00:00 2001
From: Walstan Baptista <38958184+walstanb@users.noreply.github.com>
Date: Wed, 7 Apr 2021 11:32:51 +0530
Subject: [PATCH 166/207] fix: frappe.whitelist for doc methods (#25230)
---
erpnext/payroll/doctype/payroll_entry/payroll_entry.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/erpnext/payroll/doctype/payroll_entry/payroll_entry.py b/erpnext/payroll/doctype/payroll_entry/payroll_entry.py
index 78904710a8..e8487acc28 100644
--- a/erpnext/payroll/doctype/payroll_entry/payroll_entry.py
+++ b/erpnext/payroll/doctype/payroll_entry/payroll_entry.py
@@ -185,6 +185,7 @@ class PayrollEntry(Document):
""" % ('%s', '%s', '%s','%s', cond), (ss_status, self.start_date, self.end_date, self.salary_slip_based_on_timesheet), as_dict=as_dict)
return ss_list
+ @frappe.whitelist()
def submit_salary_slips(self):
self.check_permission('write')
ss_list = self.get_sal_slip_list(ss_status=0)
@@ -409,6 +410,7 @@ class PayrollEntry(Document):
self.update(get_start_end_dates(self.payroll_frequency,
self.start_date or self.posting_date, self.company))
+ @frappe.whitelist()
def validate_employee_attendance(self):
employees_to_mark_attendance = []
days_in_payroll, days_holiday, days_attendance_marked = 0, 0, 0
From 5541aeaa82f520881ad10eee4eed1df5042ed3d8 Mon Sep 17 00:00:00 2001
From: Saqib Ansari
Date: Wed, 7 Apr 2021 12:34:20 +0530
Subject: [PATCH 167/207] fix: keyerror while validating coa file
---
.../chart_of_accounts_importer/chart_of_accounts_importer.py | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py b/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py
index 03c3eb0ac0..a812e87218 100644
--- a/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py
+++ b/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py
@@ -293,6 +293,11 @@ def validate_accounts(file_name):
accounts_dict = {}
for account in accounts:
accounts_dict.setdefault(account["account_name"], account)
+ if not hasattr(account, "parent_account"):
+ msg = _("Please make sure the file you are using has 'Parent Account' column present in the header.")
+ msg += "
"
+ msg += _("Alternatively, you can download the template and fill your data in.")
+ frappe.throw(msg)
if account["parent_account"] and accounts_dict.get(account["parent_account"]):
accounts_dict[account["parent_account"]]["is_group"] = 1
From e2da3cbc28918224da4b0727448c1da8d3083238 Mon Sep 17 00:00:00 2001
From: Afshan <33727827+AfshanKhan@users.noreply.github.com>
Date: Wed, 7 Apr 2021 15:13:44 +0530
Subject: [PATCH 168/207] fix: payroll issues (#24540)
* fix: payroll issues
* fix: enhancements
* fix: rename variables and refactor
* fix: slider
* fix: added missing arguments
* fix: test cases
* fix: slider
* fix: slider
fix: slider
Co-authored-by: Nabin Hait
---
.../doctype/payroll_entry/payroll_entry.js | 78 ++++----
.../doctype/payroll_entry/payroll_entry.py | 183 +++++++++++-------
.../payroll_entry/test_payroll_entry.py | 11 +-
.../doctype/salary_slip/salary_slip.js | 50 ++---
.../doctype/salary_slip/salary_slip.py | 5 +-
5 files changed, 195 insertions(+), 132 deletions(-)
diff --git a/erpnext/payroll/doctype/payroll_entry/payroll_entry.js b/erpnext/payroll/doctype/payroll_entry/payroll_entry.js
index 395e56fa92..85bb651af7 100644
--- a/erpnext/payroll/doctype/payroll_entry/payroll_entry.js
+++ b/erpnext/payroll/doctype/payroll_entry/payroll_entry.js
@@ -133,45 +133,59 @@ frappe.ui.form.on('Payroll Entry', {
}
};
});
+
+ frm.set_query('employee', 'employees', () => {
+ if (!frm.doc.company) {
+ frappe.msgprint(__("Please set a Company"));
+ return [];
+ }
+ return {
+ query: "erpnext.payroll.doctype.payroll_entry.payroll_entry.employee_query",
+ filters: frm.events.get_employee_filters(frm)
+ };
+ });
+ },
+
+ get_employee_filters: function (frm) {
+ let filters = {};
+ filters['company'] = frm.doc.company;
+ filters['start_date'] = frm.doc.start_date;
+ filters['end_date'] = frm.doc.end_date;
+
+ if (frm.doc.department) {
+ filters['department'] = frm.doc.department;
+ }
+ if (frm.doc.branch) {
+ filters['branch'] = frm.doc.branch;
+ }
+ if (frm.doc.designation) {
+ filters['designation'] = frm.doc.designation;
+ }
+ if (frm.doc.employees) {
+ filters['employees'] = frm.doc.employees.filter(d => d.employee).map(d => d.employee);
+ }
+ return filters;
},
payroll_frequency: function (frm) {
frm.trigger("set_start_end_dates").then( ()=> {
frm.events.clear_employee_table(frm);
- frm.events.get_employee_with_salary_slip_and_set_query(frm);
- });
- },
-
- employee_filters: function (frm, emp_list) {
- frm.set_query('employee', 'employees', () => {
- return {
- filters: {
- name: ["not in", emp_list]
- }
- };
- });
- },
-
- get_employee_with_salary_slip_and_set_query: function (frm) {
- frappe.db.get_list('Salary Slip', {
- filters: {
- start_date: frm.doc.start_date,
- end_date: frm.doc.end_date,
- docstatus: 1,
- },
- fields: ['employee']
- }).then((emp) => {
- var emp_list = [];
- emp.forEach((employee_data) => {
- emp_list.push(Object.values(employee_data)[0]);
- });
- frm.events.employee_filters(frm, emp_list);
});
},
company: function (frm) {
frm.events.clear_employee_table(frm);
erpnext.accounts.dimensions.update_dimension(frm, frm.doctype);
+ frm.trigger("set_payable_account_and_currency");
+ },
+
+ set_payable_account_and_currency: function (frm) {
+ frappe.db.get_value("Company", {"name": frm.doc.company}, "default_currency", (r) => {
+ frm.set_value('currency', r.default_currency);
+ });
+ frappe.db.get_value("Company", {"name": frm.doc.company}, "default_payroll_payable_account", (r) => {
+ frm.set_value('payroll_payable_account', r.default_payroll_payable_account);
+ });
},
currency: function (frm) {
@@ -345,11 +359,3 @@ let render_employee_attendance = function (frm, data) {
})
);
};
-
-frappe.ui.form.on('Payroll Employee Detail', {
- employee: function(frm) {
- if (!frm.doc.payroll_frequency) {
- frappe.throw(__("Please set a Payroll Frequency"));
- }
- }
-});
diff --git a/erpnext/payroll/doctype/payroll_entry/payroll_entry.py b/erpnext/payroll/doctype/payroll_entry/payroll_entry.py
index e8487acc28..fde2e0776e 100644
--- a/erpnext/payroll/doctype/payroll_entry/payroll_entry.py
+++ b/erpnext/payroll/doctype/payroll_entry/payroll_entry.py
@@ -10,16 +10,17 @@ from frappe.utils import cint, flt, add_days, getdate, add_to_date, DATE_FORMAT,
from frappe import _
from erpnext.accounts.utils import get_fiscal_year
from erpnext.hr.doctype.employee.employee import get_holiday_list_for_employee
+from frappe.desk.reportview import get_match_cond, get_filters_cond
class PayrollEntry(Document):
def onload(self):
if not self.docstatus==1 or self.salary_slips_submitted:
- return
+ return
# check if salary slips were manually submitted
entries = frappe.db.count("Salary Slip", {'payroll_entry': self.name, 'docstatus': 1}, ['name'])
if cint(entries) == len(self.employees):
- self.set_onload("submitted_ss", True)
+ self.set_onload("submitted_ss", True)
def validate(self):
self.number_of_employees = len(self.employees)
@@ -59,16 +60,16 @@ class PayrollEntry(Document):
condition = """and payroll_frequency = '%(payroll_frequency)s'"""% {"payroll_frequency": self.payroll_frequency}
sal_struct = frappe.db.sql_list("""
- select
- name from `tabSalary Structure`
- where
- docstatus = 1 and
- is_active = 'Yes'
- and company = %(company)s
- and currency = %(currency)s and
- ifnull(salary_slip_based_on_timesheet,0) = %(salary_slip_based_on_timesheet)s
- {condition}""".format(condition=condition),
- {"company": self.company, "currency": self.currency, "salary_slip_based_on_timesheet":self.salary_slip_based_on_timesheet})
+ select
+ name from `tabSalary Structure`
+ where
+ docstatus = 1 and
+ is_active = 'Yes'
+ and company = %(company)s
+ and currency = %(currency)s and
+ ifnull(salary_slip_based_on_timesheet,0) = %(salary_slip_based_on_timesheet)s
+ {condition}""".format(condition=condition),
+ {"company": self.company, "currency": self.currency, "salary_slip_based_on_timesheet":self.salary_slip_based_on_timesheet})
if sal_struct:
cond += "and t2.salary_structure IN %(sal_struct)s "
@@ -176,13 +177,12 @@ class PayrollEntry(Document):
"""
Returns list of salary slips based on selected criteria
"""
- cond = self.get_filter_condition()
ss_list = frappe.db.sql("""
select t1.name, t1.salary_structure, t1.payroll_cost_center from `tabSalary Slip` t1
- where t1.docstatus = %s and t1.start_date >= %s and t1.end_date <= %s
- and (t1.journal_entry is null or t1.journal_entry = "") and ifnull(salary_slip_based_on_timesheet,0) = %s %s
- """ % ('%s', '%s', '%s','%s', cond), (ss_status, self.start_date, self.end_date, self.salary_slip_based_on_timesheet), as_dict=as_dict)
+ where t1.docstatus = %s and t1.start_date >= %s and t1.end_date <= %s and t1.payroll_entry = %s
+ and (t1.journal_entry is null or t1.journal_entry = "") and ifnull(salary_slip_based_on_timesheet,0) = %s
+ """, (ss_status, self.start_date, self.end_date, self.name, self.salary_slip_based_on_timesheet), as_dict=as_dict)
return ss_list
@frappe.whitelist()
@@ -271,26 +271,26 @@ class PayrollEntry(Document):
exchange_rate, amt = self.get_amount_and_exchange_rate_for_journal_entry(acc_cc[0], amount, company_currency, currencies)
payable_amount += flt(amount, precision)
accounts.append({
- "account": acc_cc[0],
- "debit_in_account_currency": flt(amt, precision),
- "exchange_rate": flt(exchange_rate),
- "party_type": '',
- "cost_center": acc_cc[1] or self.cost_center,
- "project": self.project
- })
+ "account": acc_cc[0],
+ "debit_in_account_currency": flt(amt, precision),
+ "exchange_rate": flt(exchange_rate),
+ "party_type": '',
+ "cost_center": acc_cc[1] or self.cost_center,
+ "project": self.project
+ })
# Deductions
for acc_cc, amount in deductions.items():
exchange_rate, amt = self.get_amount_and_exchange_rate_for_journal_entry(acc_cc[0], amount, company_currency, currencies)
payable_amount -= flt(amount, precision)
accounts.append({
- "account": acc_cc[0],
- "credit_in_account_currency": flt(amt, precision),
- "exchange_rate": flt(exchange_rate),
- "cost_center": acc_cc[1] or self.cost_center,
- "party_type": '',
- "project": self.project
- })
+ "account": acc_cc[0],
+ "credit_in_account_currency": flt(amt, precision),
+ "exchange_rate": flt(exchange_rate),
+ "cost_center": acc_cc[1] or self.cost_center,
+ "party_type": '',
+ "project": self.project
+ })
# Payable amount
exchange_rate, payable_amt = self.get_amount_and_exchange_rate_for_journal_entry(payroll_payable_account, payable_amount, company_currency, currencies)
@@ -336,10 +336,9 @@ class PayrollEntry(Document):
def make_payment_entry(self):
self.check_permission('write')
- cond = self.get_filter_condition()
salary_slip_name_list = frappe.db.sql(""" select t1.name from `tabSalary Slip` t1
- where t1.docstatus = 1 and start_date >= %s and end_date <= %s %s
- """ % ('%s', '%s', cond), (self.start_date, self.end_date), as_list = True)
+ where t1.docstatus = 1 and start_date >= %s and end_date <= %s and t1.payroll_entry = %s
+ """, (self.start_date, self.end_date, self.name), as_list = True)
if salary_slip_name_list and len(salary_slip_name_list) > 0:
salary_slip_total = 0
@@ -371,20 +370,20 @@ class PayrollEntry(Document):
exchange_rate, amount = self.get_amount_and_exchange_rate_for_journal_entry(self.payment_account, je_payment_amount, company_currency, currencies)
accounts.append({
- "account": self.payment_account,
- "bank_account": self.bank_account,
- "credit_in_account_currency": flt(amount, precision),
- "exchange_rate": flt(exchange_rate),
- })
+ "account": self.payment_account,
+ "bank_account": self.bank_account,
+ "credit_in_account_currency": flt(amount, precision),
+ "exchange_rate": flt(exchange_rate),
+ })
exchange_rate, amount = self.get_amount_and_exchange_rate_for_journal_entry(payroll_payable_account, je_payment_amount, company_currency, currencies)
accounts.append({
- "account": payroll_payable_account,
- "debit_in_account_currency": flt(amount, precision),
- "exchange_rate": flt(exchange_rate),
- "reference_type": self.doctype,
- "reference_name": self.name
- })
+ "account": payroll_payable_account,
+ "debit_in_account_currency": flt(amount, precision),
+ "exchange_rate": flt(exchange_rate),
+ "reference_type": self.doctype,
+ "reference_name": self.name
+ })
if len(currencies) > 1:
multi_currency = 1
@@ -426,7 +425,7 @@ class PayrollEntry(Document):
employees_to_mark_attendance.append({
"employee": employee_detail.employee,
"employee_name": employee_detail.employee_name
- })
+ })
return employees_to_mark_attendance
def get_count_holidays_of_employee(self, employee, start_date):
@@ -443,11 +442,11 @@ class PayrollEntry(Document):
def get_count_employee_attendance(self, employee, start_date):
marked_days = 0
attendances = frappe.get_all("Attendance",
- fields = ["count(*)"],
- filters = {
- "employee": employee,
- "attendance_date": ('between', [start_date, self.end_date])
- }, as_list=1)
+ fields = ["count(*)"],
+ filters = {
+ "employee": employee,
+ "attendance_date": ('between', [start_date, self.end_date])
+ }, as_list=1)
if attendances and attendances[0][0]:
marked_days = attendances[0][0]
return marked_days
@@ -555,6 +554,7 @@ def payroll_entry_has_bank_entries(name):
def create_salary_slips_for_employees(employees, args, publish_progress=True):
salary_slips_exists_for = get_existing_salary_slips(employees, args)
count=0
+ salary_slips_not_created = []
for emp in employees:
if emp not in salary_slips_exists_for:
args.update({
@@ -568,33 +568,24 @@ def create_salary_slips_for_employees(employees, args, publish_progress=True):
frappe.publish_progress(count*100/len(set(employees) - set(salary_slips_exists_for)),
title = _("Creating Salary Slips..."))
else:
- salary_slip_name = frappe.db.sql(
- '''SELECT
- name
- FROM `tabSalary Slip`
- WHERE company=%s
- AND start_date >= %s
- AND end_date <= %s
- AND employee = %s
- ''', (args.company, args.start_date, args.end_date, emp), as_dict=True)
-
- salary_slip_doc = frappe.get_doc('Salary Slip', salary_slip_name[0].name)
- salary_slip_doc.exchange_rate = args.exchange_rate
- salary_slip_doc.set_totals()
- salary_slip_doc.db_update()
+ salary_slips_not_created.append(emp)
payroll_entry = frappe.get_doc("Payroll Entry", args.payroll_entry)
payroll_entry.db_set("salary_slips_created", 1)
payroll_entry.notify_update()
+ if salary_slips_not_created:
+ frappe.msgprint(_("Salary Slips already exists for employees {}, and will not be processed by this payroll.")
+ .format(frappe.bold(", ".join([emp for emp in salary_slips_not_created]))) , title=_("Message"), indicator="orange")
+
def get_existing_salary_slips(employees, args):
return frappe.db.sql_list("""
select distinct employee from `tabSalary Slip`
- where docstatus!= 2 and company = %s
+ where docstatus!= 2 and company = %s and payroll_entry = %s
and start_date >= %s and end_date <= %s
and employee in (%s)
- """ % ('%s', '%s', '%s', ', '.join(['%s']*len(employees))),
- [args.company, args.start_date, args.end_date] + employees)
+ """ % ('%s', '%s', '%s', '%s', ', '.join(['%s']*len(employees))),
+ [args.company, args.payroll_entry, args.start_date, args.end_date] + employees)
def submit_salary_slips_for_employees(payroll_entry, salary_slips, publish_progress=True):
submitted_ss = []
@@ -646,3 +637,61 @@ def get_payroll_entries_for_jv(doctype, txt, searchfield, start, page_len, filte
'txt': "%%%s%%" % frappe.db.escape(txt),
'start': start, 'page_len': page_len
})
+
+def get_employee_with_existing_salary_slip(start_date, end_date, company):
+ return frappe.db.sql_list("""
+ select employee from `tabSalary Slip`
+ where
+ (start_date between %(start_date)s and %(end_date)s
+ or
+ end_date between %(start_date)s and %(end_date)s
+ or
+ %(start_date)s between start_date and end_date)
+ and company = %(company)s
+ and docstatus = 1
+ """, {'start_date': start_date, 'end_date': end_date, 'company': company})
+
+@frappe.whitelist()
+@frappe.validate_and_sanitize_search_inputs
+def employee_query(doctype, txt, searchfield, start, page_len, filters):
+ filters = frappe._dict(filters)
+ conditions = []
+ exclude_employees = []
+ emp_cond = ''
+ if filters.start_date and filters.end_date:
+ employee_list = get_employee_with_existing_salary_slip(filters.start_date, filters.end_date, filters.company)
+ emp = filters.get('employees')
+ filters.pop('start_date')
+ filters.pop('end_date')
+ if filters.employees is not None:
+ filters.pop('employees')
+ if employee_list:
+ exclude_employees.extend(employee_list)
+ if emp:
+ exclude_employees.extend(emp)
+ if exclude_employees:
+ emp_cond += 'and employee not in %(exclude_employees)s'
+
+ return frappe.db.sql("""select name, employee_name from `tabEmployee`
+ where status = 'Active'
+ and docstatus < 2
+ and ({key} like %(txt)s
+ or employee_name like %(txt)s)
+ {emp_cond}
+ {fcond} {mcond}
+ order by
+ if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
+ if(locate(%(_txt)s, employee_name), locate(%(_txt)s, employee_name), 99999),
+ idx desc,
+ name, employee_name
+ limit %(start)s, %(page_len)s""".format(**{
+ 'key': searchfield,
+ 'fcond': get_filters_cond(doctype, filters, conditions),
+ 'mcond': get_match_cond(doctype),
+ 'emp_cond': emp_cond
+ }), {
+ 'txt': "%%%s%%" % txt,
+ '_txt': txt.replace("%", ""),
+ 'start': start,
+ 'page_len': page_len,
+ 'exclude_employees': exclude_employees})
diff --git a/erpnext/payroll/doctype/payroll_entry/test_payroll_entry.py b/erpnext/payroll/doctype/payroll_entry/test_payroll_entry.py
index 84c381489c..7528bf7a7f 100644
--- a/erpnext/payroll/doctype/payroll_entry/test_payroll_entry.py
+++ b/erpnext/payroll/doctype/payroll_entry/test_payroll_entry.py
@@ -51,21 +51,22 @@ class TestPayrollEntry(unittest.TestCase):
company_doc = frappe.get_doc('Company', company)
salary_structure = make_salary_structure("_Test Multi Currency Salary Structure", "Monthly", company=company, currency='USD')
- create_salary_structure_assignment(employee, salary_structure.name, company=company)
+ create_salary_structure_assignment(employee, salary_structure.name, company=company, currency='USD')
frappe.db.sql("""delete from `tabSalary Slip` where employee=%s""",(frappe.db.get_value("Employee", {"user_id": "test_muti_currency_employee@payroll.com"})))
salary_slip = get_salary_slip("test_muti_currency_employee@payroll.com", "Monthly", "_Test Multi Currency Salary Structure")
dates = get_start_end_dates('Monthly', nowdate())
- payroll_entry = make_payroll_entry(start_date=dates.start_date, end_date=dates.end_date,
+ payroll_entry = make_payroll_entry(start_date=dates.start_date, end_date=dates.end_date,
payable_account=company_doc.default_payroll_payable_account, currency='USD', exchange_rate=70)
payroll_entry.make_payment_entry()
salary_slip.load_from_db()
payroll_je = salary_slip.journal_entry
- payroll_je_doc = frappe.get_doc('Journal Entry', payroll_je)
+ if payroll_je:
+ payroll_je_doc = frappe.get_doc('Journal Entry', payroll_je)
- self.assertEqual(salary_slip.base_gross_pay, payroll_je_doc.total_debit)
- self.assertEqual(salary_slip.base_gross_pay, payroll_je_doc.total_credit)
+ self.assertEqual(salary_slip.base_gross_pay, payroll_je_doc.total_debit)
+ self.assertEqual(salary_slip.base_gross_pay, payroll_je_doc.total_credit)
payment_entry = frappe.db.sql('''
Select ifnull(sum(je.total_debit),0) as total_debit, ifnull(sum(je.total_credit),0) as total_credit from `tabJournal Entry` je, `tabJournal Entry Account` jea
diff --git a/erpnext/payroll/doctype/salary_slip/salary_slip.js b/erpnext/payroll/doctype/salary_slip/salary_slip.js
index 3e8a213ca9..e3993fae3a 100644
--- a/erpnext/payroll/doctype/salary_slip/salary_slip.js
+++ b/erpnext/payroll/doctype/salary_slip/salary_slip.js
@@ -39,7 +39,8 @@ frappe.ui.form.on("Salary Slip", {
frm.set_query("employee", function() {
return {
- query: "erpnext.controllers.queries.employee_query"
+ query: "erpnext.controllers.queries.employee_query",
+ filters: frm.doc.company
};
});
},
@@ -93,28 +94,31 @@ frappe.ui.form.on("Salary Slip", {
},
set_exchange_rate: function(frm, company_currency) {
- if (frm.doc.currency) {
- var from_currency = frm.doc.currency;
- if (from_currency != company_currency) {
- frm.events.hide_loan_section(frm);
- frappe.call({
- method: "erpnext.setup.utils.get_exchange_rate",
- args: {
- from_currency: from_currency,
- to_currency: company_currency,
- },
- callback: function(r) {
- frm.set_value("exchange_rate", flt(r.message));
- frm.set_df_property("exchange_rate", "hidden", 0);
- frm.set_df_property("exchange_rate", "description", "1 " + frm.doc.currency
- + " = [?] " + company_currency);
- }
- });
- } else {
- frm.set_value("exchange_rate", 1.0);
- frm.set_df_property("exchange_rate", "hidden", 1);
- frm.set_df_property("exchange_rate", "description", "");
- }
+ if (frm.doc.docstatus === 0) {
+ if (frm.doc.currency) {
+ var from_currency = frm.doc.currency;
+ if (from_currency != company_currency) {
+ frm.events.hide_loan_section(frm);
+ frappe.call({
+ method: "erpnext.setup.utils.get_exchange_rate",
+ args: {
+ from_currency: from_currency,
+ to_currency: company_currency,
+ },
+ callback: function(r) {
+ if (r.message) {
+ frm.set_value("exchange_rate", flt(r.message));
+ frm.set_df_property('exchange_rate', 'hidden', 0);
+ frm.set_df_property("exchange_rate", "description", "1 " + frm.doc.currency
+ + " = [?] " + company_currency);
+ }
+ }
+ });
+ } else {
+ frm.set_value("exchange_rate", 1.0);
+ frm.set_df_property('exchange_rate', 'hidden', 1);
+ frm.set_df_property("exchange_rate", "description", "" );
+ }
}
},
diff --git a/erpnext/payroll/doctype/salary_slip/salary_slip.py b/erpnext/payroll/doctype/salary_slip/salary_slip.py
index b987320520..f6d4c7b855 100644
--- a/erpnext/payroll/doctype/salary_slip/salary_slip.py
+++ b/erpnext/payroll/doctype/salary_slip/salary_slip.py
@@ -124,9 +124,12 @@ class SalarySlip(TransactionBase):
def check_existing(self):
if not self.salary_slip_based_on_timesheet:
+ cond = ""
+ if self.payroll_entry:
+ cond += "and payroll_entry = '{0}'".format(self.payroll_entry)
ret_exist = frappe.db.sql("""select name from `tabSalary Slip`
where start_date = %s and end_date = %s and docstatus != 2
- and employee = %s and name != %s""",
+ and employee = %s and name != %s {0}""".format(cond),
(self.start_date, self.end_date, self.employee, self.name))
if ret_exist:
self.employee = ''
From 76c852101058e48ecb3d492e798b1ff2d37be200 Mon Sep 17 00:00:00 2001
From: Ankush Menat
Date: Wed, 7 Apr 2021 16:09:58 +0530
Subject: [PATCH 169/207] fix: remove gst name validation for purch Invoice
---
erpnext/hooks.py | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/erpnext/hooks.py b/erpnext/hooks.py
index c2798a36b6..2e26fd2a9b 100644
--- a/erpnext/hooks.py
+++ b/erpnext/hooks.py
@@ -260,7 +260,10 @@ doc_events = {
"erpnext.regional.italy.utils.sales_invoice_on_cancel",
"erpnext.erpnext_integrations.taxjar_integration.delete_transaction"
],
- "on_trash": "erpnext.regional.check_deletion_permission"
+ "on_trash": "erpnext.regional.check_deletion_permission",
+ "validate": [
+ "erpnext.regional.india.utils.validate_document_name"
+ ]
},
"Purchase Invoice": {
"validate": [
@@ -282,9 +285,6 @@ doc_events = {
('Sales Invoice', 'Sales Order', 'Delivery Note', 'Purchase Invoice', 'Purchase Order', 'Purchase Receipt'): {
'validate': ['erpnext.regional.india.utils.set_place_of_supply']
},
- ('Sales Invoice', 'Purchase Invoice'): {
- 'validate': ['erpnext.regional.india.utils.validate_document_name']
- },
"Contact": {
"on_trash": "erpnext.support.doctype.issue.issue.update_issue",
"after_insert": "erpnext.telephony.doctype.call_log.call_log.link_existing_conversations",
From cb625d868c419e9ca2e24eb970ebcba10f9e849c Mon Sep 17 00:00:00 2001
From: Ankush Menat
Date: Thu, 8 Apr 2021 11:57:28 +0530
Subject: [PATCH 170/207] fix: round total quantity in job card
---
erpnext/manufacturing/doctype/job_card/job_card.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/erpnext/manufacturing/doctype/job_card/job_card.py b/erpnext/manufacturing/doctype/job_card/job_card.py
index 8aa0ffd774..92074c6288 100644
--- a/erpnext/manufacturing/doctype/job_card/job_card.py
+++ b/erpnext/manufacturing/doctype/job_card/job_card.py
@@ -47,6 +47,8 @@ class JobCard(Document):
if d.completed_qty:
self.total_completed_qty += d.completed_qty
+ self.total_completed_qty = flt(self.total_completed_qty, self.precision("total_completed_qty"))
+
def get_overlap_for(self, args, check_next_available_slot=False):
production_capacity = 1
From fa8bb87a86d242e4886ee8ff61fdc806498b4a5c Mon Sep 17 00:00:00 2001
From: Rohit Waghchaure
Date: Thu, 8 Apr 2021 13:30:13 +0530
Subject: [PATCH 171/207] fix: bom cost test case
---
erpnext/manufacturing/doctype/bom/test_bom.py | 28 +++++++++++++------
1 file changed, 20 insertions(+), 8 deletions(-)
diff --git a/erpnext/manufacturing/doctype/bom/test_bom.py b/erpnext/manufacturing/doctype/bom/test_bom.py
index 4050a7d3ed..cd61d2a31d 100644
--- a/erpnext/manufacturing/doctype/bom/test_bom.py
+++ b/erpnext/manufacturing/doctype/bom/test_bom.py
@@ -5,7 +5,7 @@
from __future__ import unicode_literals
import unittest
import frappe
-from frappe.utils import cstr
+from frappe.utils import cstr, flt
from frappe.test_runner import make_test_records
from erpnext.stock.doctype.stock_reconciliation.test_stock_reconciliation import create_stock_reconciliation
from erpnext.manufacturing.doctype.bom_update_tool.bom_update_tool import update_cost
@@ -81,15 +81,27 @@ class TestBOM(unittest.TestCase):
bom = frappe.copy_doc(test_records[2])
bom.insert()
- # test amounts in selected currency
- self.assertEqual(bom.operating_cost, 100)
- self.assertEqual(bom.raw_material_cost, 351.68)
- self.assertEqual(bom.total_cost, 451.68)
+ raw_material_cost = 0.0
+ op_cost = 0.0
+
+ for op_row in bom.operations:
+ op_cost += op_row.operating_cost
+
+ for row in bom.items:
+ raw_material_cost += row.amount
+
+ base_raw_material_cost = raw_material_cost * flt(bom.conversion_rate, bom.precision("conversion_rate"))
+ base_op_cost = op_cost * flt(bom.conversion_rate, bom.precision("conversion_rate"))
# test amounts in selected currency
- self.assertEqual(bom.base_operating_cost, 6000)
- self.assertEqual(bom.base_raw_material_cost, 21100.80)
- self.assertEqual(bom.base_total_cost, 27100.80)
+ self.assertEqual(bom.operating_cost, op_cost)
+ self.assertEqual(bom.raw_material_cost, raw_material_cost)
+ self.assertEqual(bom.total_cost, raw_material_cost + op_cost)
+
+ # test amounts in selected currency
+ self.assertEqual(bom.base_operating_cost, base_op_cost)
+ self.assertEqual(bom.base_raw_material_cost, base_raw_material_cost)
+ self.assertEqual(bom.base_total_cost, base_raw_material_cost + base_op_cost)
def test_bom_cost_multi_uom_multi_currency_based_on_price_list(self):
frappe.db.set_value("Price List", "_Test Price List", "price_not_uom_dependent", 1)
From e286750a0f5425904185372544d8efed6b2332fc Mon Sep 17 00:00:00 2001
From: HENRY Florian
Date: Thu, 8 Apr 2021 10:26:29 +0200
Subject: [PATCH 172/207] fix: UOM length unit in global setup list is empty
(#24855)
* When ERPNext is installed in localized language the category of UOM Conversion Factor is tranlasted into installed languaes. Filter must be locallized
* fix
* fix
Co-authored-by: Marica
---
erpnext/setup/doctype/global_defaults/global_defaults.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/setup/doctype/global_defaults/global_defaults.js b/erpnext/setup/doctype/global_defaults/global_defaults.js
index 552331aac8..942dd5989e 100644
--- a/erpnext/setup/doctype/global_defaults/global_defaults.js
+++ b/erpnext/setup/doctype/global_defaults/global_defaults.js
@@ -17,7 +17,7 @@ frappe.ui.form.on('Global Defaults', {
method: "frappe.client.get_list",
args: {
doctype: "UOM Conversion Factor",
- filters: { "category": "Length" },
+ filters: { "category": __("Length") },
fields: ["to_uom"],
limit_page_length: 500
},
From d9fa79de99a616ddc372367716f32ec07618f4ad Mon Sep 17 00:00:00 2001
From: Jannat Patel <31363128+pateljannat@users.noreply.github.com>
Date: Thu, 8 Apr 2021 16:04:57 +0530
Subject: [PATCH 173/207] fix: serial no refresh issue (#25127)
* fix: serial no refresh issue
* fix: sider
---
erpnext/public/js/controllers/transaction.js | 32 ++++++++++++--------
1 file changed, 19 insertions(+), 13 deletions(-)
diff --git a/erpnext/public/js/controllers/transaction.js b/erpnext/public/js/controllers/transaction.js
index 21a20a7bce..6c2144d6cb 100644
--- a/erpnext/public/js/controllers/transaction.js
+++ b/erpnext/public/js/controllers/transaction.js
@@ -737,28 +737,34 @@ erpnext.TransactionController = erpnext.taxes_and_totals.extend({
this.frm.trigger("item_code", cdt, cdn);
}
else {
- var valid_serial_nos = [];
- var serialnos = [];
// Replacing all occurences of comma with carriage return
item.serial_no = item.serial_no.replace(/,/g, '\n');
- serialnos = item.serial_no.split("\n");
- for (var i = 0; i < serialnos.length; i++) {
- if (serialnos[i] != "") {
- valid_serial_nos.push(serialnos[i]);
- }
- }
item.conversion_factor = item.conversion_factor || 1;
-
refresh_field("serial_no", item.name, item.parentfield);
- if(!doc.is_return && cint(user_defaults.set_qty_in_transactions_based_on_serial_no_input)) {
- frappe.model.set_value(item.doctype, item.name,
- "qty", valid_serial_nos.length / item.conversion_factor);
- frappe.model.set_value(item.doctype, item.name, "stock_qty", valid_serial_nos.length);
+ if (!doc.is_return && cint(frappe.user_defaults.set_qty_in_transactions_based_on_serial_no_input)) {
+ setTimeout(() => {
+ me.update_qty(cdt, cdn);
+ }, 10000);
}
}
}
},
+ update_qty: function(cdt, cdn) {
+ var valid_serial_nos = [];
+ var serialnos = [];
+ var item = frappe.get_doc(cdt, cdn);
+ serialnos = item.serial_no.split("\n");
+ for (var i = 0; i < serialnos.length; i++) {
+ if (serialnos[i] != "") {
+ valid_serial_nos.push(serialnos[i]);
+ }
+ }
+ frappe.model.set_value(item.doctype, item.name,
+ "qty", valid_serial_nos.length / item.conversion_factor);
+ frappe.model.set_value(item.doctype, item.name, "stock_qty", valid_serial_nos.length);
+ },
+
validate: function() {
this.calculate_taxes_and_totals(false);
},
From b7aa658a5156a945dcde79e5d14caae1189614bc Mon Sep 17 00:00:00 2001
From: Rucha Mahabal
Date: Thu, 8 Apr 2021 18:13:21 +0530
Subject: [PATCH 174/207] refactor(HR): Add missing reports and doctypes to the
Workspace (#24994)
* refactor(HR): Add missing reports and doctypes to the Workspace
* refactor: remove Employee Tax and Benefits from HR Workspace
Co-authored-by: Anurag Mishra <32095923+Anurag810@users.noreply.github.com>
---
erpnext/hr/workspace/hr/hr.json | 289 ++++++++++++++++++--------------
1 file changed, 163 insertions(+), 126 deletions(-)
diff --git a/erpnext/hr/workspace/hr/hr.json b/erpnext/hr/workspace/hr/hr.json
index f650b24d86..f4b56a0e17 100644
--- a/erpnext/hr/workspace/hr/hr.json
+++ b/erpnext/hr/workspace/hr/hr.json
@@ -15,6 +15,7 @@
"hide_custom": 0,
"icon": "hr",
"idx": 0,
+ "is_default": 0,
"is_standard": 1,
"label": "HR",
"links": [
@@ -226,42 +227,12 @@
"onboard": 0,
"type": "Card Break"
},
- {
- "dependencies": "Employee",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Leave Application",
- "link_to": "Leave Application",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "dependencies": "Employee",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Leave Allocation",
- "link_to": "Leave Allocation",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "dependencies": "Leave Type",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Leave Policy",
- "link_to": "Leave Policy",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
{
"dependencies": "",
"hidden": 0,
"is_query_report": 0,
- "label": "Leave Period",
- "link_to": "Leave Period",
+ "label": "Holiday List",
+ "link_to": "Holiday List",
"link_type": "DocType",
"onboard": 0,
"type": "Link"
@@ -280,8 +251,28 @@
"dependencies": "",
"hidden": 0,
"is_query_report": 0,
- "label": "Holiday List",
- "link_to": "Holiday List",
+ "label": "Leave Period",
+ "link_to": "Leave Period",
+ "link_type": "DocType",
+ "onboard": 0,
+ "type": "Link"
+ },
+ {
+ "dependencies": "Leave Type",
+ "hidden": 0,
+ "is_query_report": 0,
+ "label": "Leave Policy",
+ "link_to": "Leave Policy",
+ "link_type": "DocType",
+ "onboard": 0,
+ "type": "Link"
+ },
+ {
+ "dependencies": "Leave Policy",
+ "hidden": 0,
+ "is_query_report": 0,
+ "label": "Leave Policy Assignment",
+ "link_to": "Leave Policy Assignment",
"link_type": "DocType",
"onboard": 0,
"type": "Link"
@@ -290,8 +281,18 @@
"dependencies": "Employee",
"hidden": 0,
"is_query_report": 0,
- "label": "Compensatory Leave Request",
- "link_to": "Compensatory Leave Request",
+ "label": "Leave Application",
+ "link_to": "Leave Application",
+ "link_type": "DocType",
+ "onboard": 0,
+ "type": "Link"
+ },
+ {
+ "dependencies": "Employee",
+ "hidden": 0,
+ "is_query_report": 0,
+ "label": "Leave Allocation",
+ "link_to": "Leave Allocation",
"link_type": "DocType",
"onboard": 0,
"type": "Link"
@@ -317,12 +318,12 @@
"type": "Link"
},
{
- "dependencies": "Leave Application",
+ "dependencies": "Employee",
"hidden": 0,
- "is_query_report": 1,
- "label": "Employee Leave Balance",
- "link_to": "Employee Leave Balance",
- "link_type": "Report",
+ "is_query_report": 0,
+ "label": "Compensatory Leave Request",
+ "link_to": "Compensatory Leave Request",
+ "link_type": "DocType",
"onboard": 0,
"type": "Link"
},
@@ -383,16 +384,6 @@
"onboard": 0,
"type": "Link"
},
- {
- "dependencies": "Attendance",
- "hidden": 0,
- "is_query_report": 1,
- "label": "Monthly Attendance Sheet",
- "link_to": "Monthly Attendance Sheet",
- "link_type": "Report",
- "onboard": 0,
- "type": "Link"
- },
{
"hidden": 0,
"is_query_report": 0,
@@ -420,6 +411,15 @@
"onboard": 0,
"type": "Link"
},
+ {
+ "hidden": 0,
+ "is_query_report": 0,
+ "label": "Travel Request",
+ "link_to": "Travel Request",
+ "link_type": "DocType",
+ "onboard": 0,
+ "type": "Link"
+ },
{
"hidden": 0,
"is_query_report": 0,
@@ -464,6 +464,15 @@
"onboard": 0,
"type": "Card Break"
},
+ {
+ "hidden": 0,
+ "is_query_report": 0,
+ "label": "Driver",
+ "link_to": "Driver",
+ "link_type": "DocType",
+ "onboard": 0,
+ "type": "Link"
+ },
{
"dependencies": "",
"hidden": 0,
@@ -541,6 +550,24 @@
"onboard": 0,
"type": "Link"
},
+ {
+ "hidden": 0,
+ "is_query_report": 0,
+ "label": "Appointment Letter",
+ "link_to": "Appointment Letter",
+ "link_type": "DocType",
+ "onboard": 0,
+ "type": "Link"
+ },
+ {
+ "hidden": 0,
+ "is_query_report": 0,
+ "label": "Appointment Letter Template",
+ "link_to": "Appointment Letter Template",
+ "link_type": "DocType",
+ "onboard": 0,
+ "type": "Link"
+ },
{
"hidden": 0,
"is_query_report": 0,
@@ -625,33 +652,6 @@
"onboard": 0,
"type": "Link"
},
- {
- "hidden": 0,
- "is_query_report": 0,
- "label": "Reports",
- "onboard": 0,
- "type": "Card Break"
- },
- {
- "dependencies": "Employee",
- "hidden": 0,
- "is_query_report": 1,
- "label": "Employee Birthday",
- "link_to": "Employee Birthday",
- "link_type": "Report",
- "onboard": 0,
- "type": "Link"
- },
- {
- "dependencies": "Employee",
- "hidden": 0,
- "is_query_report": 1,
- "label": "Employees working on a holiday",
- "link_to": "Employees working on a holiday",
- "link_type": "Report",
- "onboard": 0,
- "type": "Link"
- },
{
"hidden": 0,
"is_query_report": 0,
@@ -702,7 +702,74 @@
{
"hidden": 0,
"is_query_report": 0,
- "label": "Employee Tax and Benefits",
+ "label": "Key Reports",
+ "onboard": 0,
+ "type": "Card Break"
+ },
+ {
+ "dependencies": "Attendance",
+ "hidden": 0,
+ "is_query_report": 1,
+ "label": "Monthly Attendance Sheet",
+ "link_to": "Monthly Attendance Sheet",
+ "link_type": "Report",
+ "onboard": 0,
+ "type": "Link"
+ },
+ {
+ "dependencies": "Staffing Plan",
+ "hidden": 0,
+ "is_query_report": 1,
+ "label": "Recruitment Analytics",
+ "link_to": "Recruitment Analytics",
+ "link_type": "Report",
+ "onboard": 0,
+ "type": "Link"
+ },
+ {
+ "dependencies": "Employee",
+ "hidden": 0,
+ "is_query_report": 1,
+ "label": "Employee Analytics",
+ "link_to": "Employee Analytics",
+ "link_type": "Report",
+ "onboard": 0,
+ "type": "Link"
+ },
+ {
+ "dependencies": "Employee",
+ "hidden": 0,
+ "is_query_report": 1,
+ "label": "Employee Leave Balance",
+ "link_to": "Employee Leave Balance",
+ "link_type": "Report",
+ "onboard": 0,
+ "type": "Link"
+ },
+ {
+ "dependencies": "Employee",
+ "hidden": 0,
+ "is_query_report": 1,
+ "label": "Employee Leave Balance Summary",
+ "link_to": "Employee Leave Balance Summary",
+ "link_type": "Report",
+ "onboard": 0,
+ "type": "Link"
+ },
+ {
+ "dependencies": "Employee Advance",
+ "hidden": 0,
+ "is_query_report": 1,
+ "label": "Employee Advance Summary",
+ "link_to": "Employee Advance Summary",
+ "link_type": "Report",
+ "onboard": 0,
+ "type": "Link"
+ },
+ {
+ "hidden": 0,
+ "is_query_report": 0,
+ "label": "Other Reports",
"onboard": 0,
"type": "Card Break"
},
@@ -710,74 +777,44 @@
"dependencies": "Employee",
"hidden": 0,
"is_query_report": 0,
- "label": "Employee Tax Exemption Declaration",
- "link_to": "Employee Tax Exemption Declaration",
- "link_type": "DocType",
+ "label": "Employee Information",
+ "link_to": "Employee Information",
+ "link_type": "Report",
"onboard": 0,
"type": "Link"
},
{
"dependencies": "Employee",
"hidden": 0,
- "is_query_report": 0,
- "label": "Employee Tax Exemption Proof Submission",
- "link_to": "Employee Tax Exemption Proof Submission",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "dependencies": "Employee, Payroll Period",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Employee Other Income",
- "link_to": "Employee Other Income",
- "link_type": "DocType",
+ "is_query_report": 1,
+ "label": "Employee Birthday",
+ "link_to": "Employee Birthday",
+ "link_type": "Report",
"onboard": 0,
"type": "Link"
},
{
"dependencies": "Employee",
"hidden": 0,
- "is_query_report": 0,
- "label": "Employee Benefit Application",
- "link_to": "Employee Benefit Application",
- "link_type": "DocType",
+ "is_query_report": 1,
+ "label": "Employees Working on a Holiday",
+ "link_to": "Employees working on a holiday",
+ "link_type": "Report",
"onboard": 0,
"type": "Link"
},
{
- "dependencies": "Employee",
+ "dependencies": "Daily Work Summary",
"hidden": 0,
- "is_query_report": 0,
- "label": "Employee Benefit Claim",
- "link_to": "Employee Benefit Claim",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "dependencies": "Employee",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Employee Tax Exemption Category",
- "link_to": "Employee Tax Exemption Category",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "dependencies": "Employee",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Employee Tax Exemption Sub Category",
- "link_to": "Employee Tax Exemption Sub Category",
- "link_type": "DocType",
+ "is_query_report": 1,
+ "label": "Daily Work Summary Replies",
+ "link_to": "Daily Work Summary Replies",
+ "link_type": "Report",
"onboard": 0,
"type": "Link"
}
],
- "modified": "2021-01-21 13:38:38.941001",
+ "modified": "2021-03-24 17:35:21.483297",
"modified_by": "Administrator",
"module": "HR",
"name": "HR",
From 30720d21396358599599d631c52d80554bfd40a8 Mon Sep 17 00:00:00 2001
From: Saqib Ansari
Date: Thu, 8 Apr 2021 19:06:44 +0530
Subject: [PATCH 175/207] fix: set correct ack no. on irn generation
---
erpnext/regional/india/e_invoice/utils.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/erpnext/regional/india/e_invoice/utils.py b/erpnext/regional/india/e_invoice/utils.py
index 8eccc3f565..3dd1b36fb6 100644
--- a/erpnext/regional/india/e_invoice/utils.py
+++ b/erpnext/regional/india/e_invoice/utils.py
@@ -787,6 +787,8 @@ class GSPConnector():
self.invoice.irn = res.get('Irn')
self.invoice.ewaybill = res.get('EwbNo')
+ self.invoice.ack_no = res.get('AckNo')
+ self.invoice.ack_date = res.get('AckDt')
self.invoice.signed_einvoice = dec_signed_invoice
self.invoice.signed_qr_code = res.get('SignedQRCode')
From 4191e7999d63acaf221b55c6ea71a7389dac469e Mon Sep 17 00:00:00 2001
From: Saqib
Date: Thu, 8 Apr 2021 21:04:56 +0530
Subject: [PATCH 176/207] chore: add error title
Co-authored-by: Marica
---
.../chart_of_accounts_importer/chart_of_accounts_importer.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py b/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py
index a812e87218..f96f59169e 100644
--- a/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py
+++ b/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py
@@ -297,7 +297,7 @@ def validate_accounts(file_name):
msg = _("Please make sure the file you are using has 'Parent Account' column present in the header.")
msg += "
"
msg += _("Alternatively, you can download the template and fill your data in.")
- frappe.throw(msg)
+ frappe.throw(msg, title=_("Parent Account Missing"))
if account["parent_account"] and accounts_dict.get(account["parent_account"]):
accounts_dict[account["parent_account"]]["is_group"] = 1
From e7813b69c4633aea6d476c286106280c5b0f94a7 Mon Sep 17 00:00:00 2001
From: Saqib Ansari
Date: Fri, 9 Apr 2021 11:30:50 +0530
Subject: [PATCH 177/207] fix: condition for setting agreement status
---
erpnext/support/doctype/issue/issue.py | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/erpnext/support/doctype/issue/issue.py b/erpnext/support/doctype/issue/issue.py
index 767a8a6a29..b068363f06 100644
--- a/erpnext/support/doctype/issue/issue.py
+++ b/erpnext/support/doctype/issue/issue.py
@@ -7,7 +7,7 @@ import json
from frappe import _
from frappe import utils
from frappe.model.document import Document
-from frappe.utils import now_datetime, getdate, get_weekdays, add_to_date, get_time, get_datetime, time_diff_in_seconds
+from frappe.utils import cint, now_datetime, getdate, get_weekdays, add_to_date, get_time, get_datetime, time_diff_in_seconds
from datetime import datetime, timedelta
from frappe.model.mapper import get_mapped_doc
from frappe.utils.user import is_website_user
@@ -128,8 +128,8 @@ class Issue(Document):
def update_agreement_status(self):
if self.service_level_agreement and self.agreement_status == "Ongoing":
- if frappe.db.get_value("Issue", self.name, "response_by_variance") < 0 or \
- frappe.db.get_value("Issue", self.name, "resolution_by_variance") < 0:
+ if cint(frappe.db.get_value("Issue", self.name, "response_by_variance")) < 0 or \
+ cint(frappe.db.get_value("Issue", self.name, "resolution_by_variance")) < 0:
self.agreement_status = "Failed"
else:
From a7ac01153e71ce425f6d06912e6283666ec24dc0 Mon Sep 17 00:00:00 2001
From: Marica
Date: Fri, 9 Apr 2021 11:55:44 +0530
Subject: [PATCH 178/207] fix: Remove redundant import and import cint
---
erpnext/stock/dashboard/item_dashboard.py | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/erpnext/stock/dashboard/item_dashboard.py b/erpnext/stock/dashboard/item_dashboard.py
index 980fae2e9f..80afe31cf3 100644
--- a/erpnext/stock/dashboard/item_dashboard.py
+++ b/erpnext/stock/dashboard/item_dashboard.py
@@ -2,8 +2,7 @@ from __future__ import unicode_literals
import frappe
from frappe.model.db_query import DatabaseQuery
-from frappe.model.meta import get_field_precision
-from frappe.utils import flt
+from frappe.utils import flt, cint
@frappe.whitelist()
def get_data(item_code=None, warehouse=None, item_group=None,
From 5467d7c3e325ec8915000cb47dccbd5a2b70b5a5 Mon Sep 17 00:00:00 2001
From: Marica
Date: Fri, 9 Apr 2021 11:56:49 +0530
Subject: [PATCH 179/207] fix: Use system precision instead of SLE precision
---
erpnext/stock/dashboard/item_dashboard.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/stock/dashboard/item_dashboard.py b/erpnext/stock/dashboard/item_dashboard.py
index 80afe31cf3..45e662807a 100644
--- a/erpnext/stock/dashboard/item_dashboard.py
+++ b/erpnext/stock/dashboard/item_dashboard.py
@@ -43,7 +43,7 @@ def get_data(item_code=None, warehouse=None, item_group=None,
limit_start=start,
limit_page_length='21')
- precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"))
+ precision = cint(frappe.db.get_single_value("System Settings", "float_precision"))
for item in items:
item.update({
From 032246dc2bf772102a876cedd814b7616efd3b34 Mon Sep 17 00:00:00 2001
From: Saqib Ansari
Date: Fri, 9 Apr 2021 12:08:24 +0530
Subject: [PATCH 180/207] feat(italy): add document type field for e-invoicing
---
erpnext/patches.txt | 1 +
...document_type_field_for_italy_einvoicing.py | 18 ++++++++++++++++++
erpnext/regional/italy/setup.py | 3 +++
erpnext/regional/italy/utils.py | 11 ++++++-----
4 files changed, 28 insertions(+), 5 deletions(-)
create mode 100644 erpnext/patches/v12_0/add_document_type_field_for_italy_einvoicing.py
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 16863142bc..010963a868 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -764,3 +764,4 @@ erpnext.patches.v13_0.setup_uae_vat_fields
execute:frappe.db.set_value('System Settings', None, 'app_name', 'ERPNext')
erpnext.patches.v13_0.rename_discharge_date_in_ip_record
erpnext.patches.v12_0.purchase_receipt_status
+erpnext.patches.v12_0.add_document_type_field_for_italy_einvoicing
\ No newline at end of file
diff --git a/erpnext/patches/v12_0/add_document_type_field_for_italy_einvoicing.py b/erpnext/patches/v12_0/add_document_type_field_for_italy_einvoicing.py
new file mode 100644
index 0000000000..4d649dd0f0
--- /dev/null
+++ b/erpnext/patches/v12_0/add_document_type_field_for_italy_einvoicing.py
@@ -0,0 +1,18 @@
+from __future__ import unicode_literals
+from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
+import frappe
+
+def execute():
+ company = frappe.get_all('Company', filters = {'country': 'Italy'})
+ if not company:
+ return
+
+ custom_fields = {
+ 'Sales Invoice': [
+ dict(fieldname='type_of_document', label='Type of Document',
+ fieldtype='Select', insert_after='customer_fiscal_code',
+ options='\nTD01\nTD02\nTD03\nTD04\nTD05\nTD06\nTD16\nTD17\nTD18\nTD19\nTD20\nTD21\nTD22\nTD23\nTD24\nTD25\nTD26\nTD27'),
+ ]
+ }
+
+ create_custom_fields(custom_fields, update=True)
\ No newline at end of file
diff --git a/erpnext/regional/italy/setup.py b/erpnext/regional/italy/setup.py
index a1f5bb9836..7db2f6b0f8 100644
--- a/erpnext/regional/italy/setup.py
+++ b/erpnext/regional/italy/setup.py
@@ -139,6 +139,9 @@ def make_custom_fields(update=True):
dict(fieldname='customer_fiscal_code', label='Customer Fiscal Code',
fieldtype='Data', insert_after='cb_e_invoicing_reference', read_only=1,
fetch_from="customer.fiscal_code"),
+ dict(fieldname='type_of_document', label='Type of Document',
+ fieldtype='Select', insert_after='customer_fiscal_code',
+ options='\nTD01\nTD02\nTD03\nTD04\nTD05\nTD06\nTD16\nTD17\nTD18\nTD19\nTD20\nTD21\nTD22\nTD23\nTD24\nTD25\nTD26\nTD27'),
],
'Purchase Invoice Item': invoice_item_fields,
'Sales Order Item': invoice_item_fields,
diff --git a/erpnext/regional/italy/utils.py b/erpnext/regional/italy/utils.py
index 08573cddcd..ba1aeafc3e 100644
--- a/erpnext/regional/italy/utils.py
+++ b/erpnext/regional/italy/utils.py
@@ -57,11 +57,12 @@ def prepare_invoice(invoice, progressive_number):
invoice.company_address_data = company_address
#Set invoice type
- if invoice.is_return and invoice.return_against:
- invoice.type_of_document = "TD04" #Credit Note (Nota di Credito)
- invoice.return_against_unamended = get_unamended_name(frappe.get_doc("Sales Invoice", invoice.return_against))
- else:
- invoice.type_of_document = "TD01" #Sales Invoice (Fattura)
+ if not invoice.type_of_document:
+ if invoice.is_return and invoice.return_against:
+ invoice.type_of_document = "TD04" #Credit Note (Nota di Credito)
+ invoice.return_against_unamended = get_unamended_name(frappe.get_doc("Sales Invoice", invoice.return_against))
+ else:
+ invoice.type_of_document = "TD01" #Sales Invoice (Fattura)
#set customer information
invoice.customer_data = frappe.get_doc("Customer", invoice.customer)
From ca5e10892c4a8b9aeb2142d666635470f43705e2 Mon Sep 17 00:00:00 2001
From: Rohit Waghchaure
Date: Fri, 9 Apr 2021 14:39:04 +0530
Subject: [PATCH 181/207] fix: travis
---
erpnext/projects/doctype/project/test_project.py | 8 ++++++--
erpnext/stock/doctype/item/test_item.py | 5 +++--
erpnext/stock/doctype/stock_entry/test_stock_entry.py | 8 ++++++--
3 files changed, 15 insertions(+), 6 deletions(-)
diff --git a/erpnext/projects/doctype/project/test_project.py b/erpnext/projects/doctype/project/test_project.py
index a92bad1d5a..70139c6da8 100644
--- a/erpnext/projects/doctype/project/test_project.py
+++ b/erpnext/projects/doctype/project/test_project.py
@@ -33,12 +33,16 @@ class TestProject(unittest.TestCase):
def test_project_template_having_parent_child_tasks(self):
project_name = "Test Project with Template - Tasks with Parent-Child Relation"
+
+ if frappe.db.get_value('Project', {'project_name': project_name}, 'name'):
+ project_name = frappe.db.get_value('Project', {'project_name': project_name}, 'name')
+
frappe.db.sql(""" delete from tabTask where project = %s """, project_name)
frappe.delete_doc('Project', project_name)
task1 = task_exists("Test Template Task Parent")
if not task1:
- task1 = create_task(subject="Test Template Task Parent", is_group=1, is_template=1, begin=1, duration=4)
+ task1 = create_task(subject="Test Template Task Parent", is_group=1, is_template=1, begin=1, duration=10)
task2 = task_exists("Test Template Task Child 1")
if not task2:
@@ -53,7 +57,7 @@ class TestProject(unittest.TestCase):
tasks = frappe.get_all('Task', ['subject','exp_end_date','depends_on_tasks', 'name', 'parent_task'], dict(project=project.name), order_by='creation asc')
self.assertEqual(tasks[0].subject, 'Test Template Task Parent')
- self.assertEqual(getdate(tasks[0].exp_end_date), calculate_end_date(project, 1, 4))
+ self.assertEqual(getdate(tasks[0].exp_end_date), calculate_end_date(project, 1, 10))
self.assertEqual(tasks[1].subject, 'Test Template Task Child 1')
self.assertEqual(getdate(tasks[1].exp_end_date), calculate_end_date(project, 1, 3))
diff --git a/erpnext/stock/doctype/item/test_item.py b/erpnext/stock/doctype/item/test_item.py
index 36d0de1e5d..e0b89d8e45 100644
--- a/erpnext/stock/doctype/item/test_item.py
+++ b/erpnext/stock/doctype/item/test_item.py
@@ -494,7 +494,8 @@ def make_item_variant():
test_records = frappe.get_test_records('Item')
-def create_item(item_code, is_stock_item=None, valuation_rate=0, warehouse=None, is_customer_provided_item=None, customer=None, is_purchase_item=None, opening_stock=None):
+def create_item(item_code, is_stock_item=None, valuation_rate=0, warehouse=None, is_customer_provided_item=None,
+ customer=None, is_purchase_item=None, opening_stock=None, company=None):
if not frappe.db.exists("Item", item_code):
item = frappe.new_doc("Item")
item.item_code = item_code
@@ -509,7 +510,7 @@ def create_item(item_code, is_stock_item=None, valuation_rate=0, warehouse=None,
item.customer = customer or ''
item.append("item_defaults", {
"default_warehouse": warehouse or '_Test Warehouse - _TC',
- "company": "_Test Company"
+ "company": company or "_Test Company"
})
item.save()
else:
diff --git a/erpnext/stock/doctype/stock_entry/test_stock_entry.py b/erpnext/stock/doctype/stock_entry/test_stock_entry.py
index 123f0c8647..a0e70516d4 100644
--- a/erpnext/stock/doctype/stock_entry/test_stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/test_stock_entry.py
@@ -179,11 +179,15 @@ class TestStockEntry(unittest.TestCase):
def test_material_transfer_gl_entry(self):
company = frappe.db.get_value('Warehouse', 'Stores - TCP1', 'company')
- mtn = make_stock_entry(item_code="_Test Item", source="Stores - TCP1",
+ item_code = 'Hand Sanitizer - 001'
+ create_item(item_code =item_code, is_stock_item = 1,
+ is_purchase_item=1, opening_stock=1000, valuation_rate=10, company=company, warehouse="Stores - TCP1")
+
+ mtn = make_stock_entry(item_code=item_code, source="Stores - TCP1",
target="Finished Goods - TCP1", qty=45, company=company)
self.check_stock_ledger_entries("Stock Entry", mtn.name,
- [["_Test Item", "Stores - TCP1", -45.0], ["_Test Item", "Finished Goods - TCP1", 45.0]])
+ [[item_code, "Stores - TCP1", -45.0], [item_code, "Finished Goods - TCP1", 45.0]])
source_warehouse_account = get_inventory_account(mtn.company, mtn.get("items")[0].s_warehouse)
From 5451bbf7d2aecd5da454e8ee591abf5cb6f38d20 Mon Sep 17 00:00:00 2001
From: Ankush Menat
Date: Fri, 9 Apr 2021 17:14:37 +0530
Subject: [PATCH 182/207] fix: condition for SLA status banner
If the document is NOT in the closed state and fulfilled then there
won't be any banner. This bug was introduced while fixing a bug related
to buttons, so separated out code for showing buttons and showing
banners.
---
erpnext/support/doctype/issue/issue.js | 102 +++++++++++++------------
1 file changed, 52 insertions(+), 50 deletions(-)
diff --git a/erpnext/support/doctype/issue/issue.js b/erpnext/support/doctype/issue/issue.js
index 9fe12f9490..ecc9fcfe82 100644
--- a/erpnext/support/doctype/issue/issue.js
+++ b/erpnext/support/doctype/issue/issue.js
@@ -48,44 +48,62 @@ frappe.ui.form.on("Issue", {
}
},
- refresh: function (frm) {
- if (frm.doc.status !== "Closed") {
- if (frm.doc.service_level_agreement && frm.doc.agreement_status === "Ongoing") {
- frappe.call({
- "method": "frappe.client.get",
- args: {
- doctype: "Service Level Agreement",
- name: frm.doc.service_level_agreement
- },
- callback: function(data) {
- let statuses = data.message.pause_sla_on;
- const hold_statuses = [];
- $.each(statuses, (_i, entry) => {
- hold_statuses.push(entry.status);
- });
- if (hold_statuses.includes(frm.doc.status)) {
- frm.dashboard.clear_headline();
- let message = {"indicator": "orange", "msg": __("SLA is on hold since {0}", [moment(frm.doc.on_hold_since).fromNow(true)])};
- frm.dashboard.set_headline_alert(
- '' +
- ' ' +
- ''+ message.msg +' ' +
- ' ' +
- ' '
- );
- } else {
- set_time_to_resolve_and_response(frm);
- }
- }
- });
- }
+ refresh: function(frm) {
- frm.add_custom_button(__("Close"), function () {
+ // alert messages
+ if (frm.doc.status !== "Closed" && frm.doc.service_level_agreement
+ && frm.doc.agreement_status === "Ongoing") {
+ frappe.call({
+ "method": "frappe.client.get",
+ args: {
+ doctype: "Service Level Agreement",
+ name: frm.doc.service_level_agreement
+ },
+ callback: function(data) {
+ let statuses = data.message.pause_sla_on;
+ const hold_statuses = [];
+ $.each(statuses, (_i, entry) => {
+ hold_statuses.push(entry.status);
+ });
+ if (hold_statuses.includes(frm.doc.status)) {
+ frm.dashboard.clear_headline();
+ let message = { "indicator": "orange", "msg": __("SLA is on hold since {0}", [moment(frm.doc.on_hold_since).fromNow(true)]) };
+ frm.dashboard.set_headline_alert(
+ '' +
+ ' ' +
+ '' + message.msg + ' ' +
+ ' ' +
+ ' '
+ );
+ } else {
+ set_time_to_resolve_and_response(frm);
+ }
+ }
+ });
+ } else if (frm.doc.service_level_agreement) {
+ frm.dashboard.clear_headline();
+
+ let agreement_status = (frm.doc.agreement_status == "Fulfilled") ?
+ { "indicator": "green", "msg": "Service Level Agreement has been fulfilled" } :
+ { "indicator": "red", "msg": "Service Level Agreement Failed" };
+
+ frm.dashboard.set_headline_alert(
+ '' +
+ ' ' +
+ '' + agreement_status.msg + ' ' +
+ ' ' +
+ ' '
+ );
+ }
+
+ // buttons
+ if (frm.doc.status !== "Closed") {
+ frm.add_custom_button(__("Close"), function() {
frm.set_value("status", "Closed");
frm.save();
});
- frm.add_custom_button(__("Task"), function () {
+ frm.add_custom_button(__("Task"), function() {
frappe.model.open_mapped_doc({
method: "erpnext.support.doctype.issue.issue.make_task",
frm: frm
@@ -93,23 +111,7 @@ frappe.ui.form.on("Issue", {
}, __("Create"));
} else {
- if (frm.doc.service_level_agreement) {
- frm.dashboard.clear_headline();
-
- let agreement_status = (frm.doc.agreement_status == "Fulfilled") ?
- {"indicator": "green", "msg": "Service Level Agreement has been fulfilled"} :
- {"indicator": "red", "msg": "Service Level Agreement Failed"};
-
- frm.dashboard.set_headline_alert(
- '' +
- ' ' +
- ''+ agreement_status.msg +' ' +
- ' ' +
- ' '
- );
- }
-
- frm.add_custom_button(__("Reopen"), function () {
+ frm.add_custom_button(__("Reopen"), function() {
frm.set_value("status", "Open");
frm.save();
});
From 986452107bd26c15f2b487a2ca83ed26845a8aff Mon Sep 17 00:00:00 2001
From: Anupam Kumar
Date: Fri, 9 Apr 2021 18:15:51 +0530
Subject: [PATCH 183/207] fix: Lead Source's module (#24583)
* fix: Lead Source's module
* fix: patch fix
---
.../doctype/lead_source/__init__.py | 0
.../crm/doctype/lead_source/lead_source.js | 8 ++
.../crm/doctype/lead_source/lead_source.json | 62 +++++++++
.../doctype/lead_source/lead_source.py | 4 +-
.../doctype/lead_source/test_lead_source.py | 6 +-
erpnext/patches/v7_1/update_lead_source.py | 2 +-
.../doctype/lead_source/lead_source.js | 8 --
.../doctype/lead_source/lead_source.json | 131 ------------------
8 files changed, 75 insertions(+), 146 deletions(-)
rename erpnext/{selling => crm}/doctype/lead_source/__init__.py (100%)
create mode 100644 erpnext/crm/doctype/lead_source/lead_source.js
create mode 100644 erpnext/crm/doctype/lead_source/lead_source.json
rename erpnext/{selling => crm}/doctype/lead_source/lead_source.py (71%)
rename erpnext/{selling => crm}/doctype/lead_source/test_lead_source.py (52%)
delete mode 100644 erpnext/selling/doctype/lead_source/lead_source.js
delete mode 100644 erpnext/selling/doctype/lead_source/lead_source.json
diff --git a/erpnext/selling/doctype/lead_source/__init__.py b/erpnext/crm/doctype/lead_source/__init__.py
similarity index 100%
rename from erpnext/selling/doctype/lead_source/__init__.py
rename to erpnext/crm/doctype/lead_source/__init__.py
diff --git a/erpnext/crm/doctype/lead_source/lead_source.js b/erpnext/crm/doctype/lead_source/lead_source.js
new file mode 100644
index 0000000000..3cbe649209
--- /dev/null
+++ b/erpnext/crm/doctype/lead_source/lead_source.js
@@ -0,0 +1,8 @@
+// Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+
+frappe.ui.form.on('Lead Source', {
+ // refresh: function(frm) {
+
+ // }
+});
diff --git a/erpnext/crm/doctype/lead_source/lead_source.json b/erpnext/crm/doctype/lead_source/lead_source.json
new file mode 100644
index 0000000000..723c6d993d
--- /dev/null
+++ b/erpnext/crm/doctype/lead_source/lead_source.json
@@ -0,0 +1,62 @@
+{
+ "actions": [],
+ "allow_rename": 1,
+ "autoname": "field:source_name",
+ "creation": "2016-09-16 01:47:47.382372",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+ "source_name",
+ "details"
+ ],
+ "fields": [
+ {
+ "fieldname": "source_name",
+ "fieldtype": "Data",
+ "in_list_view": 1,
+ "label": "Source Name",
+ "reqd": 1,
+ "unique": 1
+ },
+ {
+ "fieldname": "details",
+ "fieldtype": "Text Editor",
+ "label": "Details"
+ }
+ ],
+ "links": [],
+ "modified": "2021-02-08 12:51:48.971517",
+ "modified_by": "Administrator",
+ "module": "CRM",
+ "name": "Lead Source",
+ "owner": "Administrator",
+ "permissions": [
+ {
+ "create": 1,
+ "delete": 1,
+ "email": 1,
+ "export": 1,
+ "print": 1,
+ "read": 1,
+ "report": 1,
+ "role": "Sales Manager",
+ "share": 1,
+ "write": 1
+ },
+ {
+ "create": 1,
+ "email": 1,
+ "export": 1,
+ "print": 1,
+ "read": 1,
+ "report": 1,
+ "role": "Sales User",
+ "share": 1,
+ "write": 1
+ }
+ ],
+ "quick_entry": 1,
+ "sort_field": "modified",
+ "sort_order": "DESC"
+}
\ No newline at end of file
diff --git a/erpnext/selling/doctype/lead_source/lead_source.py b/erpnext/crm/doctype/lead_source/lead_source.py
similarity index 71%
rename from erpnext/selling/doctype/lead_source/lead_source.py
rename to erpnext/crm/doctype/lead_source/lead_source.py
index d2d7558621..5c64fb8b4a 100644
--- a/erpnext/selling/doctype/lead_source/lead_source.py
+++ b/erpnext/crm/doctype/lead_source/lead_source.py
@@ -1,9 +1,9 @@
# -*- coding: utf-8 -*-
-# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
-import frappe
+# import frappe
from frappe.model.document import Document
class LeadSource(Document):
diff --git a/erpnext/selling/doctype/lead_source/test_lead_source.py b/erpnext/crm/doctype/lead_source/test_lead_source.py
similarity index 52%
rename from erpnext/selling/doctype/lead_source/test_lead_source.py
rename to erpnext/crm/doctype/lead_source/test_lead_source.py
index 42df18f181..b5bc6490cf 100644
--- a/erpnext/selling/doctype/lead_source/test_lead_source.py
+++ b/erpnext/crm/doctype/lead_source/test_lead_source.py
@@ -1,12 +1,10 @@
# -*- coding: utf-8 -*-
-# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
-import frappe
+# import frappe
import unittest
-# test_records = frappe.get_test_records('Lead Source')
-
class TestLeadSource(unittest.TestCase):
pass
diff --git a/erpnext/patches/v7_1/update_lead_source.py b/erpnext/patches/v7_1/update_lead_source.py
index 517e66c4bc..a2a48a62e1 100644
--- a/erpnext/patches/v7_1/update_lead_source.py
+++ b/erpnext/patches/v7_1/update_lead_source.py
@@ -5,7 +5,7 @@ from frappe import _
def execute():
from erpnext.setup.setup_wizard.operations.install_fixtures import default_lead_sources
- frappe.reload_doc('selling', 'doctype', 'lead_source')
+ frappe.reload_doc('crm', 'doctype', 'lead_source')
frappe.local.lang = frappe.db.get_default("lang") or 'en'
diff --git a/erpnext/selling/doctype/lead_source/lead_source.js b/erpnext/selling/doctype/lead_source/lead_source.js
deleted file mode 100644
index 6af6a4f648..0000000000
--- a/erpnext/selling/doctype/lead_source/lead_source.js
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Lead Source', {
- refresh: function(frm) {
-
- }
-});
diff --git a/erpnext/selling/doctype/lead_source/lead_source.json b/erpnext/selling/doctype/lead_source/lead_source.json
deleted file mode 100644
index 373e83af9c..0000000000
--- a/erpnext/selling/doctype/lead_source/lead_source.json
+++ /dev/null
@@ -1,131 +0,0 @@
-{
- "allow_copy": 0,
- "allow_import": 0,
- "allow_rename": 1,
- "autoname": "field:source_name",
- "beta": 0,
- "creation": "2016-09-16 01:47:47.382372",
- "custom": 0,
- "docstatus": 0,
- "doctype": "DocType",
- "document_type": "",
- "editable_grid": 1,
- "fields": [
- {
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "source_name",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_list_view": 0,
- "label": "Source Name",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "details",
- "fieldtype": "Text Editor",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_list_view": 0,
- "label": "Details",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- }
- ],
- "hide_heading": 0,
- "hide_toolbar": 0,
- "idx": 0,
- "image_view": 0,
- "in_create": 0,
-
- "is_submittable": 0,
- "issingle": 0,
- "istable": 0,
- "max_attachments": 0,
- "modified": "2020-09-16 02:03:01.441622",
- "modified_by": "Administrator",
- "module": "Selling",
- "name": "Lead Source",
- "name_case": "",
- "owner": "Administrator",
- "permissions": [
- {
- "amend": 0,
- "apply_user_permissions": 0,
- "cancel": 0,
- "create": 1,
- "delete": 1,
- "email": 1,
- "export": 1,
- "if_owner": 0,
- "import": 0,
- "permlevel": 0,
- "print": 1,
- "read": 1,
- "report": 1,
- "role": "Sales Manager",
- "set_user_permissions": 0,
- "share": 1,
- "submit": 0,
- "write": 1
- },
- {
- "amend": 0,
- "apply_user_permissions": 0,
- "cancel": 0,
- "create": 1,
- "delete": 0,
- "email": 1,
- "export": 1,
- "if_owner": 0,
- "import": 0,
- "permlevel": 0,
- "print": 1,
- "read": 1,
- "report": 1,
- "role": "Sales User",
- "set_user_permissions": 0,
- "share": 1,
- "submit": 0,
- "write": 1
- }
- ],
- "quick_entry": 1,
- "read_only": 0,
- "read_only_onload": 0,
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_seen": 0
-}
From 110f28f869c1a82be5fc4f4cd13c6c2d6bf34720 Mon Sep 17 00:00:00 2001
From: noahjacob
Date: Fri, 9 Apr 2021 20:01:47 +0530
Subject: [PATCH 184/207] Company field editable and is readonly after saving.
---
erpnext/stock/doctype/warehouse/warehouse.json | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/erpnext/stock/doctype/warehouse/warehouse.json b/erpnext/stock/doctype/warehouse/warehouse.json
index bddb114c9d..9b9093261c 100644
--- a/erpnext/stock/doctype/warehouse/warehouse.json
+++ b/erpnext/stock/doctype/warehouse/warehouse.json
@@ -70,6 +70,7 @@
"oldfieldname": "company",
"oldfieldtype": "Link",
"options": "Company",
+ "read_only_depends_on": "eval: !doc.__islocal",
"remember_last_selected_value": 1,
"reqd": 1,
"search_index": 1
@@ -244,7 +245,7 @@
"idx": 1,
"is_tree": 1,
"links": [],
- "modified": "2021-02-16 17:21:52.380098",
+ "modified": "2021-04-09 19:54:56.263965",
"modified_by": "Administrator",
"module": "Stock",
"name": "Warehouse",
From 1358443cdbaa9924069242f7d191e625bf19ecff Mon Sep 17 00:00:00 2001
From: Rohit Waghchaure
Date: Fri, 26 Mar 2021 14:11:50 +0530
Subject: [PATCH 185/207] fix: patch
---
erpnext/controllers/stock_controller.py | 3 +--
.../v13_0/item_reposting_for_incorrect_sl_and_gl.py | 13 ++++++++++---
.../repost_item_valuation/repost_item_valuation.py | 2 +-
3 files changed, 12 insertions(+), 6 deletions(-)
diff --git a/erpnext/controllers/stock_controller.py b/erpnext/controllers/stock_controller.py
index f352bae30e..20499579ca 100644
--- a/erpnext/controllers/stock_controller.py
+++ b/erpnext/controllers/stock_controller.py
@@ -406,8 +406,7 @@ class StockController(AccountsController):
def set_rate_of_stock_uom(self):
if self.doctype in ["Purchase Receipt", "Purchase Invoice", "Purchase Order", "Sales Invoice", "Sales Order", "Delivery Note", "Quotation"]:
for d in self.get("items"):
- if d.conversion_factor:
- d.stock_uom_rate = d.rate / d.conversion_factor
+ d.stock_uom_rate = d.rate / (d.conversion_factor or 1)
def validate_internal_transfer(self):
if self.doctype in ('Sales Invoice', 'Delivery Note', 'Purchase Invoice', 'Purchase Receipt') \
diff --git a/erpnext/patches/v13_0/item_reposting_for_incorrect_sl_and_gl.py b/erpnext/patches/v13_0/item_reposting_for_incorrect_sl_and_gl.py
index d968e1fb76..abde65f5cd 100644
--- a/erpnext/patches/v13_0/item_reposting_for_incorrect_sl_and_gl.py
+++ b/erpnext/patches/v13_0/item_reposting_for_incorrect_sl_and_gl.py
@@ -20,9 +20,11 @@ def execute():
frappe.clear_cache()
frappe.flags.warehouse_account_map = {}
+ company_wise_data = {}
+
data = frappe.db.sql('''
SELECT
- name, item_code, warehouse, voucher_type, voucher_no, posting_date, posting_time
+ name, item_code, warehouse, voucher_type, voucher_no, posting_date, posting_time, company
FROM
`tabStock Ledger Entry`
WHERE
@@ -36,6 +38,9 @@ def execute():
total_sle = len(data)
i = 0
for d in data:
+ if d.company not in company_wise_data:
+ company_wise_data[d.company] = True
+
update_entries_after({
"item_code": d.item_code,
"warehouse": d.warehouse,
@@ -53,8 +58,10 @@ def execute():
print("Reposting General Ledger Entries...")
- for row in frappe.get_all('Company', filters= {'enable_perpetual_inventory': 1}):
- update_gl_entries_after(posting_date, posting_time, company=row.name)
+ if data:
+ for row in frappe.get_all('Company', filters= {'enable_perpetual_inventory': 1}):
+ if company_wise_data.get(row.name):
+ update_gl_entries_after(posting_date, posting_time, company=row.name)
frappe.db.auto_commit_on_many_writes = 0
diff --git a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
index f8cfdf83e7..e68360266f 100644
--- a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
+++ b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
@@ -124,7 +124,7 @@ def repost_entries():
return
for d in frappe.get_all('Company', filters= {'enable_perpetual_inventory': 1}):
- check_if_stock_and_account_balance_synced(today(), d.company)
+ check_if_stock_and_account_balance_synced(today(), d.name)
def get_repost_item_valuation_entries():
date = add_to_date(today(), hours=-12)
From b9aa775f3ba17dd9d763510a158b758a44ba8c56 Mon Sep 17 00:00:00 2001
From: Rohit Waghchaure
Date: Sat, 27 Mar 2021 18:54:41 +0530
Subject: [PATCH 186/207] fix: pricing_rule test cases
---
.../doctype/pricing_rule/test_pricing_rule.py | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py b/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py
index f28cee7c5a..ef9aad562d 100644
--- a/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py
+++ b/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py
@@ -328,6 +328,21 @@ class TestPricingRule(unittest.TestCase):
self.assertEquals(item.discount_amount, 110)
self.assertEquals(item.rate, 990)
+ def test_pricing_rule_with_margin_and_discount_amount(self):
+ frappe.delete_doc_if_exists('Pricing Rule', '_Test Pricing Rule')
+ make_pricing_rule(selling=1, margin_type="Percentage", margin_rate_or_amount=10,
+ rate_or_discount="Discount Amount", discount_amount=110)
+ si = create_sales_invoice(do_not_save=True)
+ si.items[0].price_list_rate = 1000
+ si.payment_schedule = []
+ si.insert(ignore_permissions=True)
+
+ item = si.items[0]
+ self.assertEquals(item.margin_rate_or_amount, 10)
+ self.assertEquals(item.rate_with_margin, 1100)
+ self.assertEquals(item.discount_amount, 110)
+ self.assertEquals(item.rate, 990)
+
def test_pricing_rule_for_product_discount_on_same_item(self):
frappe.delete_doc_if_exists('Pricing Rule', '_Test Pricing Rule')
test_record = {
@@ -560,6 +575,7 @@ def make_pricing_rule(**args):
"margin_rate_or_amount": args.margin_rate_or_amount or 0.0,
"condition": args.condition or '',
"priority": 1,
+ "discount_amount": args.discount_amount or 0.0,
"apply_multiple_pricing_rules": args.apply_multiple_pricing_rules or 0
})
From 1db8c5174949a176c6894fccd29d4576eebeb2ce Mon Sep 17 00:00:00 2001
From: Rohit Waghchaure
Date: Sat, 27 Mar 2021 19:02:07 +0530
Subject: [PATCH 187/207] fix: changed logic
---
.../v13_0/item_reposting_for_incorrect_sl_and_gl.py | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/erpnext/patches/v13_0/item_reposting_for_incorrect_sl_and_gl.py b/erpnext/patches/v13_0/item_reposting_for_incorrect_sl_and_gl.py
index abde65f5cd..021bb72cae 100644
--- a/erpnext/patches/v13_0/item_reposting_for_incorrect_sl_and_gl.py
+++ b/erpnext/patches/v13_0/item_reposting_for_incorrect_sl_and_gl.py
@@ -20,7 +20,7 @@ def execute():
frappe.clear_cache()
frappe.flags.warehouse_account_map = {}
- company_wise_data = {}
+ company_list = []
data = frappe.db.sql('''
SELECT
@@ -38,8 +38,8 @@ def execute():
total_sle = len(data)
i = 0
for d in data:
- if d.company not in company_wise_data:
- company_wise_data[d.company] = True
+ if d.company not in company_list:
+ company_list.append(d.company)
update_entries_after({
"item_code": d.item_code,
@@ -60,7 +60,7 @@ def execute():
if data:
for row in frappe.get_all('Company', filters= {'enable_perpetual_inventory': 1}):
- if company_wise_data.get(row.name):
+ if row.name in company_list:
update_gl_entries_after(posting_date, posting_time, company=row.name)
frappe.db.auto_commit_on_many_writes = 0
From 37d6c19a347a833c6863bd14108815fe4497563a Mon Sep 17 00:00:00 2001
From: Deepesh Garg
Date: Sat, 10 Apr 2021 18:33:26 +0530
Subject: [PATCH 188/207] fix: Consider paid repayment entries in subsequent
loan repayments
---
.../loan_management/doctype/loan/test_loan.py | 74 ++++++++++++-------
.../doctype/loan_repayment/loan_repayment.py | 28 +++++--
2 files changed, 68 insertions(+), 34 deletions(-)
diff --git a/erpnext/loan_management/doctype/loan/test_loan.py b/erpnext/loan_management/doctype/loan/test_loan.py
index 4b9a89486a..57f98869cc 100644
--- a/erpnext/loan_management/doctype/loan/test_loan.py
+++ b/erpnext/loan_management/doctype/loan/test_loan.py
@@ -523,33 +523,7 @@ class TestLoan(unittest.TestCase):
self.assertEqual(flt(repayment_entry.total_interest_paid, 0), flt(interest_amount, 0))
def test_penalty(self):
- pledge = [{
- "loan_security": "Test Security 1",
- "qty": 4000.00
- }]
-
- loan_application = create_loan_application('_Test Company', self.applicant2, 'Demand Loan', pledge)
- create_pledge(loan_application)
-
- loan = create_demand_loan(self.applicant2, "Demand Loan", loan_application, posting_date='2019-10-01')
- loan.submit()
-
- self.assertEquals(loan.loan_amount, 1000000)
-
- first_date = '2019-10-01'
- last_date = '2019-10-30'
-
- make_loan_disbursement_entry(loan.name, loan.loan_amount, disbursement_date=first_date)
- process_loan_interest_accrual_for_demand_loans(posting_date = last_date)
-
- amounts = calculate_amounts(loan.name, add_days(last_date, 1))
- paid_amount = amounts['interest_amount']/2
-
- repayment_entry = create_repayment_entry(loan.name, self.applicant2, add_days(last_date, 5),
- paid_amount)
-
- repayment_entry.submit()
-
+ loan = create_loan_scenario_for_penalty(self)
# 30 days - grace period
penalty_days = 30 - 4
penalty_applicable_amount = flt(amounts['interest_amount']/2)
@@ -559,8 +533,28 @@ class TestLoan(unittest.TestCase):
calculated_penalty_amount = frappe.db.get_value('Loan Interest Accrual',
{'process_loan_interest_accrual': process, 'loan': loan.name}, 'penalty_amount')
+ self.assertEquals(loan.loan_amount, 1000000)
self.assertEquals(calculated_penalty_amount, penalty_amount)
+ def test_penalty_repayment(self):
+ loan = create_loan_scenario_for_penalty(self)
+ amounts = calculate_amounts(loan.name, '2019-11-30 00:00:00')
+
+ first_penalty = 10000
+ second_penalty = amounts['penalty_amount'] - 10000
+
+ repayment_entry = create_repayment_entry(loan.name, self.applicant2, '2019-11-30 00:00:00', 10000)
+ repayment_entry.submit()
+
+ amounts = calculate_amounts(loan.name, '2019-11-30 00:00:01')
+ self.assertEquals(amounts['penalty_amount'], second_penalty)
+
+ repayment_entry = create_repayment_entry(loan.name, self.applicant2, '2019-11-30 00:00:01', second_penalty)
+ repayment_entry.submit()
+
+ amounts = calculate_amounts(loan.name, '2019-11-30 00:00:02')
+ self.assertEquals(amounts['penalty_amount'], 0)
+
def test_loan_write_off_limit(self):
pledge = [{
"loan_security": "Test Security 1",
@@ -651,6 +645,32 @@ class TestLoan(unittest.TestCase):
amounts = calculate_amounts(loan.name, add_days(last_date, 5))
self.assertEquals(flt(amounts['pending_principal_amount'], 0), 0)
+def create_loan_scenario_for_penalty(doc):
+ pledge = [{
+ "loan_security": "Test Security 1",
+ "qty": 4000.00
+ }]
+
+ loan_application = create_loan_application('_Test Company', doc.applicant2, 'Demand Loan', pledge)
+ create_pledge(loan_application)
+ loan = create_demand_loan(doc.applicant2, "Demand Loan", loan_application, posting_date='2019-10-01')
+ loan.submit()
+
+ first_date = '2019-10-01'
+ last_date = '2019-10-30'
+
+ make_loan_disbursement_entry(loan.name, loan.loan_amount, disbursement_date=first_date)
+ process_loan_interest_accrual_for_demand_loans(posting_date = last_date)
+
+ amounts = calculate_amounts(loan.name, add_days(last_date, 1))
+ paid_amount = amounts['interest_amount']/2
+
+ repayment_entry = create_repayment_entry(loan.name, doc.applicant2, add_days(last_date, 5),
+ paid_amount)
+
+ repayment_entry.submit()
+
+ return loan
def create_loan_accounts():
if not frappe.db.exists("Account", "Loans and Advances (Assets) - _TC"):
diff --git a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
index a88e183ead..2a0221beb1 100644
--- a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
+++ b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
@@ -75,10 +75,6 @@ class LoanRepayment(AccountsController):
if not self.amount_paid:
frappe.throw(_("Amount paid cannot be zero"))
- if not self.shortfall_amount and self.amount_paid < self.penalty_amount:
- msg = _("Paid amount cannot be less than {0}").format(self.penalty_amount)
- frappe.throw(msg)
-
def book_unaccrued_interest(self):
precision = cint(frappe.db.get_default("currency_precision")) or 2
if self.total_interest_paid > self.interest_payable:
@@ -327,6 +323,18 @@ def get_accrued_interest_entries(against_loan):
return unpaid_accrued_entries
+def get_penalty_details(against_loan):
+ penalty_details = frappe.db.sql("""
+ SELECT posting_date, (penalty_amount - total_penalty_paid) as pending_penalty_amount
+ FROM `tabLoan Repayment` where posting_date >= (SELECT MAX(posting_date) from `tabLoan Repayment`
+ where against_loan = %s) and docstatus = 1 and against_loan = %s
+ """, (against_loan, against_loan))
+
+ if penalty_details:
+ return penalty_details[0][0], flt(penalty_details[0][1])
+ else:
+ return None, 0
+
# This function returns the amounts that are payable at the time of loan repayment based on posting date
# So it pulls all the unpaid Loan Interest Accrual Entries and calculates the penalty if applicable
@@ -337,6 +345,7 @@ def get_amounts(amounts, against_loan, posting_date):
loan_type_details = frappe.get_doc("Loan Type", against_loan_doc.loan_type)
accrued_interest_entries = get_accrued_interest_entries(against_loan_doc.name)
+ computed_penalty_date, pending_penalty_amount = get_penalty_details(against_loan)
pending_accrual_entries = {}
total_pending_interest = 0
@@ -351,8 +360,13 @@ def get_amounts(amounts, against_loan, posting_date):
# and if no_of_late days are positive then penalty is levied
due_date = add_days(entry.posting_date, 1)
- no_of_late_days = date_diff(posting_date,
- add_days(due_date, loan_type_details.grace_period_in_days)) + 1
+ due_date_after_grace_period = add_days(due_date, loan_type_details.grace_period_in_days)
+
+ # Consider one day after already calculated penalty
+ if computed_penalty_date and getdate(computed_penalty_date) >= due_date_after_grace_period:
+ due_date_after_grace_period = add_days(computed_penalty_date, 1)
+
+ no_of_late_days = date_diff(posting_date, due_date_after_grace_period) + 1
if no_of_late_days > 0 and (not against_loan_doc.repay_from_salary) and entry.accrual_type == 'Regular':
penalty_amount += (entry.interest_amount * (loan_type_details.penalty_interest_rate / 100) * no_of_late_days)
@@ -390,7 +404,7 @@ def get_amounts(amounts, against_loan, posting_date):
amounts["pending_principal_amount"] = flt(pending_principal_amount, precision)
amounts["payable_principal_amount"] = flt(payable_principal_amount, precision)
amounts["interest_amount"] = flt(total_pending_interest, precision)
- amounts["penalty_amount"] = flt(penalty_amount, precision)
+ amounts["penalty_amount"] = flt(penalty_amount + pending_penalty_amount, precision)
amounts["payable_amount"] = flt(payable_principal_amount + total_pending_interest + penalty_amount, precision)
amounts["pending_accrual_entries"] = pending_accrual_entries
amounts["unaccrued_interest"] = flt(unaccrued_interest, precision)
From f38a653a08006a97b360bf864dedd9173fbc4ca3 Mon Sep 17 00:00:00 2001
From: Deepesh Garg
Date: Sat, 10 Apr 2021 18:34:51 +0530
Subject: [PATCH 189/207] fix: Show exact error message in datetime
---
.../loan_management/doctype/loan_repayment/loan_repayment.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
index 834c98cb3e..baa45a4704 100644
--- a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
+++ b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
@@ -75,7 +75,7 @@ class LoanRepayment(AccountsController):
"docstatus": 1, "against_loan": self.against_loan}, 'posting_date')
if future_repayment_date:
- frappe.throw("Repayment already made till date {0}".format(getdate(future_repayment_date)))
+ frappe.throw("Repayment already made till date {0}".format(get_datetime(future_repayment_date)))
def validate_amount(self):
precision = cint(frappe.db.get_default("currency_precision")) or 2
From b58590251b4537c9c1a927312f3ba1e633e8e746 Mon Sep 17 00:00:00 2001
From: Deepesh Garg
Date: Sat, 10 Apr 2021 19:55:36 +0530
Subject: [PATCH 190/207] fix: minor improvements and tests
---
.../loan_management/doctype/loan/loan.json | 9 ++++++-
.../loan_management/doctype/loan/test_loan.py | 6 ++---
.../loan_disbursement/loan_disbursement.json | 25 ++++++++++++++++++-
.../loan_repayment/loan_repayment.json | 6 +++--
.../doctype/loan_repayment/loan_repayment.py | 12 +++++++--
.../loan_security_unpledge.py | 8 ++++--
6 files changed, 55 insertions(+), 11 deletions(-)
diff --git a/erpnext/loan_management/doctype/loan/loan.json b/erpnext/loan_management/doctype/loan/loan.json
index acf09f5c03..4f8ceb0de8 100644
--- a/erpnext/loan_management/doctype/loan/loan.json
+++ b/erpnext/loan_management/doctype/loan/loan.json
@@ -23,6 +23,7 @@
"rate_of_interest",
"is_secured_loan",
"disbursement_date",
+ "closure_date",
"disbursed_amount",
"column_break_11",
"maximum_loan_amount",
@@ -348,12 +349,18 @@
"no_copy": 1,
"options": "Company:company:default_currency",
"read_only": 1
+ },
+ {
+ "fieldname": "closure_date",
+ "fieldtype": "Date",
+ "label": "Closure Date",
+ "read_only": 1
}
],
"index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [],
- "modified": "2020-11-24 12:27:23.208240",
+ "modified": "2021-04-10 09:28:21.946972",
"modified_by": "Administrator",
"module": "Loan Management",
"name": "Loan",
diff --git a/erpnext/loan_management/doctype/loan/test_loan.py b/erpnext/loan_management/doctype/loan/test_loan.py
index 57f98869cc..6f8da3166f 100644
--- a/erpnext/loan_management/doctype/loan/test_loan.py
+++ b/erpnext/loan_management/doctype/loan/test_loan.py
@@ -523,7 +523,7 @@ class TestLoan(unittest.TestCase):
self.assertEqual(flt(repayment_entry.total_interest_paid, 0), flt(interest_amount, 0))
def test_penalty(self):
- loan = create_loan_scenario_for_penalty(self)
+ loan, amounts = create_loan_scenario_for_penalty(self)
# 30 days - grace period
penalty_days = 30 - 4
penalty_applicable_amount = flt(amounts['interest_amount']/2)
@@ -537,7 +537,7 @@ class TestLoan(unittest.TestCase):
self.assertEquals(calculated_penalty_amount, penalty_amount)
def test_penalty_repayment(self):
- loan = create_loan_scenario_for_penalty(self)
+ loan, dummy = create_loan_scenario_for_penalty(self)
amounts = calculate_amounts(loan.name, '2019-11-30 00:00:00')
first_penalty = 10000
@@ -670,7 +670,7 @@ def create_loan_scenario_for_penalty(doc):
repayment_entry.submit()
- return loan
+ return loan, amounts
def create_loan_accounts():
if not frappe.db.exists("Account", "Loans and Advances (Assets) - _TC"):
diff --git a/erpnext/loan_management/doctype/loan_disbursement/loan_disbursement.json b/erpnext/loan_management/doctype/loan_disbursement/loan_disbursement.json
index cd5df4d3cd..662c626b8d 100644
--- a/erpnext/loan_management/doctype/loan_disbursement/loan_disbursement.json
+++ b/erpnext/loan_management/doctype/loan_disbursement/loan_disbursement.json
@@ -20,6 +20,10 @@
"cost_center",
"customer_details_section",
"bank_account",
+ "disbursement_references_section",
+ "reference_date",
+ "column_break_17",
+ "reference_number",
"amended_from"
],
"fields": [
@@ -126,12 +130,31 @@
{
"fieldname": "column_break_8",
"fieldtype": "Column Break"
+ },
+ {
+ "fieldname": "disbursement_references_section",
+ "fieldtype": "Section Break",
+ "label": "Disbursement References"
+ },
+ {
+ "fieldname": "reference_date",
+ "fieldtype": "Date",
+ "label": "Reference Date"
+ },
+ {
+ "fieldname": "column_break_17",
+ "fieldtype": "Column Break"
+ },
+ {
+ "fieldname": "reference_number",
+ "fieldtype": "Data",
+ "label": "Reference Number"
}
],
"index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [],
- "modified": "2020-11-06 10:04:30.882322",
+ "modified": "2021-04-10 10:03:41.502210",
"modified_by": "Administrator",
"module": "Loan Management",
"name": "Loan Disbursement",
diff --git a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.json b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.json
index 86ea59dc24..8fbf233be5 100644
--- a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.json
+++ b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.json
@@ -239,14 +239,16 @@
{
"fieldname": "total_penalty_paid",
"fieldtype": "Currency",
+ "hidden": 1,
"label": "Total Penalty Paid",
- "options": "Company:company:default_currency"
+ "options": "Company:company:default_currency",
+ "read_only": 1
}
],
"index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [],
- "modified": "2021-04-05 13:45:19.137896",
+ "modified": "2021-04-10 10:00:31.859076",
"modified_by": "Administrator",
"module": "Loan Management",
"name": "Loan Repayment",
diff --git a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
index baa45a4704..728eadf22a 100644
--- a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
+++ b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
@@ -227,6 +227,14 @@ class LoanRepayment(AccountsController):
gle_map = []
loan_details = frappe.get_doc("Loan", self.against_loan)
+ if self.shortfall_amount and self.amount_paid > self.shortfall_amount:
+ remarks = _("Shortfall Repayment of {0}.\nRepayment against Loan: {1}").format(self.shortfall_amount,
+ self.against_loan)
+ elif self.shortfall_amount:
+ remarks = _("Shortfall Repayment of {0}").format(self.shortfall_amount)
+ else:
+ remarks = _("Repayment against Loan: ") + self.against_loan
+
if self.total_penalty_paid:
gle_map.append(
self.get_gl_dict({
@@ -267,7 +275,7 @@ class LoanRepayment(AccountsController):
"debit_in_account_currency": self.amount_paid,
"against_voucher_type": "Loan",
"against_voucher": self.against_loan,
- "remarks": _("Repayment against Loan: ") + self.against_loan,
+ "remarks": remarks,
"cost_center": self.cost_center,
"posting_date": getdate(self.posting_date)
})
@@ -283,7 +291,7 @@ class LoanRepayment(AccountsController):
"credit_in_account_currency": self.amount_paid,
"against_voucher_type": "Loan",
"against_voucher": self.against_loan,
- "remarks": _("Repayment against Loan: ") + self.against_loan,
+ "remarks": remarks,
"cost_center": self.cost_center,
"posting_date": getdate(self.posting_date)
})
diff --git a/erpnext/loan_management/doctype/loan_security_unpledge/loan_security_unpledge.py b/erpnext/loan_management/doctype/loan_security_unpledge/loan_security_unpledge.py
index c4c2d68378..b24dc2f7c2 100644
--- a/erpnext/loan_management/doctype/loan_security_unpledge/loan_security_unpledge.py
+++ b/erpnext/loan_management/doctype/loan_security_unpledge/loan_security_unpledge.py
@@ -6,7 +6,7 @@ from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
-from frappe.utils import get_datetime, flt
+from frappe.utils import get_datetime, flt, getdate
import json
from six import iteritems
from erpnext.loan_management.doctype.loan_security_price.loan_security_price import get_loan_security_price
@@ -113,7 +113,11 @@ class LoanSecurityUnpledge(Document):
pledged_qty += qty
if not pledged_qty:
- frappe.db.set_value('Loan', self.loan, 'status', 'Closed')
+ frappe.db.set_value('Loan', self.loan,
+ {
+ 'status': 'Closed',
+ 'closure_date': getdate()
+ })
@frappe.whitelist()
def get_pledged_security_qty(loan):
From d235fc75ad573525ee7dc022acb468e82aa22674 Mon Sep 17 00:00:00 2001
From: Ankush Menat
Date: Mon, 12 Apr 2021 10:23:06 +0530
Subject: [PATCH 191/207] fix: remove nonexistent method from pick list
(#25279)
This method is merged in calculate_rate_and_amount() during repost item
valuation refactoring.
Ref:
https://github.com/nabinhait/erpnext/commit/e10f0a5a6cd344b0e2ea2b65a992b37e9a4594d6#diff-a160e3a8907dcdf28ce7728bb7dd45914ad8ab033489ea3de4c80fb1c4ca7fe9
---
erpnext/stock/doctype/pick_list/pick_list.py | 1 -
1 file changed, 1 deletion(-)
diff --git a/erpnext/stock/doctype/pick_list/pick_list.py b/erpnext/stock/doctype/pick_list/pick_list.py
index 755fa615bb..6ab68e292a 100644
--- a/erpnext/stock/doctype/pick_list/pick_list.py
+++ b/erpnext/stock/doctype/pick_list/pick_list.py
@@ -379,7 +379,6 @@ def create_stock_entry(pick_list):
else:
stock_entry = update_stock_entry_items_with_no_reference(pick_list, stock_entry)
- stock_entry.set_incoming_rate()
stock_entry.set_actual_qty()
stock_entry.calculate_rate_and_amount()
From 207166fe8ba5f22ec07acc9c8f91e1f2493bbf05 Mon Sep 17 00:00:00 2001
From: Anoop <3326959+akurungadam@users.noreply.github.com>
Date: Mon, 12 Apr 2021 10:25:34 +0530
Subject: [PATCH 192/207] fix(patch): copy Lab Test / Template renamed field
values (#25276)
reload_doc doctypes introduced since v11
---
.../v13_0/healthcare_lab_module_rename_doctypes.py | 13 +++++++++++++
...atient_history_settings_for_standard_doctypes.py | 1 +
2 files changed, 14 insertions(+)
diff --git a/erpnext/patches/v13_0/healthcare_lab_module_rename_doctypes.py b/erpnext/patches/v13_0/healthcare_lab_module_rename_doctypes.py
index 5920bf1f70..a78f802574 100644
--- a/erpnext/patches/v13_0/healthcare_lab_module_rename_doctypes.py
+++ b/erpnext/patches/v13_0/healthcare_lab_module_rename_doctypes.py
@@ -18,6 +18,7 @@ def execute():
for old_dt, new_dt in doctypes.items():
if not frappe.db.table_exists(new_dt) and frappe.db.table_exists(old_dt):
+ frappe.reload_doc('healthcare', 'doctype', frappe.scrub(old_dt))
frappe.rename_doc('DocType', old_dt, new_dt, force=True)
frappe.reload_doc('healthcare', 'doctype', frappe.scrub(new_dt))
frappe.delete_doc_if_exists('DocType', old_dt)
@@ -36,6 +37,18 @@ def execute():
SET parentfield = %(parentfield)s
""".format(doctype), {'parentfield': parentfield})
+ # copy renamed child table fields (fields were already renamed in old doctype json, hence sql)
+ frappe.db.sql("""UPDATE `tabNormal Test Result` SET lab_test_name = test_name""")
+ frappe.db.sql("""UPDATE `tabNormal Test Result` SET lab_test_event = test_event""")
+ frappe.db.sql("""UPDATE `tabNormal Test Result` SET lab_test_uom = test_uom""")
+ frappe.db.sql("""UPDATE `tabNormal Test Result` SET lab_test_comment = test_comment""")
+ frappe.db.sql("""UPDATE `tabNormal Test Template` SET lab_test_event = test_event""")
+ frappe.db.sql("""UPDATE `tabNormal Test Template` SET lab_test_uom = test_uom""")
+ frappe.db.sql("""UPDATE `tabDescriptive Test Result` SET lab_test_particulars = test_particulars""")
+ frappe.db.sql("""UPDATE `tabLab Test Group Template` SET lab_test_template = test_template""")
+ frappe.db.sql("""UPDATE `tabLab Test Group Template` SET lab_test_description = test_description""")
+ frappe.db.sql("""UPDATE `tabLab Test Group Template` SET lab_test_rate = test_rate""")
+
# rename field
frappe.reload_doc('healthcare', 'doctype', 'lab_test')
if frappe.db.has_column('Lab Test', 'special_toggle'):
diff --git a/erpnext/patches/v13_0/setup_patient_history_settings_for_standard_doctypes.py b/erpnext/patches/v13_0/setup_patient_history_settings_for_standard_doctypes.py
index 2d3b096915..5316c01170 100644
--- a/erpnext/patches/v13_0/setup_patient_history_settings_for_standard_doctypes.py
+++ b/erpnext/patches/v13_0/setup_patient_history_settings_for_standard_doctypes.py
@@ -8,6 +8,7 @@ def execute():
frappe.reload_doc("healthcare", "doctype", "Therapy Session")
frappe.reload_doc("healthcare", "doctype", "Inpatient Medication Order")
+ frappe.reload_doc("healthcare", "doctype", "Clinical Procedure")
frappe.reload_doc("healthcare", "doctype", "Patient History Settings")
frappe.reload_doc("healthcare", "doctype", "Patient History Standard Document Type")
frappe.reload_doc("healthcare", "doctype", "Patient History Custom Document Type")
From b8a270074e402c707e31537f072f2a637ce0d441 Mon Sep 17 00:00:00 2001
From: Saqib
Date: Mon, 12 Apr 2021 10:28:05 +0530
Subject: [PATCH 193/207] fix(pos): cannot set qty to less than zero (#25258)
---
erpnext/selling/page/point_of_sale/pos_controller.js | 5 -----
1 file changed, 5 deletions(-)
diff --git a/erpnext/selling/page/point_of_sale/pos_controller.js b/erpnext/selling/page/point_of_sale/pos_controller.js
index 9e3c9a5656..8adf5bf747 100644
--- a/erpnext/selling/page/point_of_sale/pos_controller.js
+++ b/erpnext/selling/page/point_of_sale/pos_controller.js
@@ -279,11 +279,6 @@ erpnext.PointOfSale.Controller = class {
const item_row = frappe.model.get_doc(cdt, cdn);
if (item_row && item_row[fieldname] != value) {
- if (fieldname === 'qty' && flt(value) == 0) {
- this.remove_item_from_cart();
- return;
- }
-
const { item_code, batch_no, uom } = this.item_details.current_item;
const event = {
field: fieldname,
From 9f73bd80401ed7e97bbba04f4d51b15f0d7e2581 Mon Sep 17 00:00:00 2001
From: Anupam Kumar
Date: Mon, 12 Apr 2021 10:31:36 +0530
Subject: [PATCH 194/207] fix: don't delete mode of payment account details
while deleting company transactions (#25217)
---
erpnext/setup/doctype/company/delete_company_transactions.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/setup/doctype/company/delete_company_transactions.py b/erpnext/setup/doctype/company/delete_company_transactions.py
index 0df4c87f51..933ed3cf32 100644
--- a/erpnext/setup/doctype/company/delete_company_transactions.py
+++ b/erpnext/setup/doctype/company/delete_company_transactions.py
@@ -27,7 +27,7 @@ def delete_company_transactions(company_name):
if doctype not in ("Account", "Cost Center", "Warehouse", "Budget",
"Party Account", "Employee", "Sales Taxes and Charges Template",
"Purchase Taxes and Charges Template", "POS Profile", "BOM",
- "Company", "Bank Account", "Item Tax Template", "Mode Of Payment",
+ "Company", "Bank Account", "Item Tax Template", "Mode Of Payment", "Mode of Payment Account",
"Item Default", "Customer", "Supplier", "GST Account"):
delete_for_doctype(doctype, company_name)
From c36e48a869a45f27072e724a4738b6dc7f820125 Mon Sep 17 00:00:00 2001
From: Deepesh Garg <42651287+deepeshgarg007@users.noreply.github.com>
Date: Mon, 12 Apr 2021 10:55:43 +0530
Subject: [PATCH 195/207] fix: GST on freight charge in e-invoicing (#25000)
* fix: GST on freight charge in e-invocing
* fix: Add patch for taxable value field
* fix: Handle discounts on net total
* fix: Handle all types of discounts for e-invoicing
* fix: Absolute taxable values
* fix: Use correct tax amount
---
erpnext/hooks.py | 3 +-
erpnext/patches.txt | 1 +
.../v12_0/create_taxable_value_field.py | 18 +++++++
erpnext/regional/india/e_invoice/utils.py | 47 +++++++++++++++----
erpnext/regional/india/setup.py | 5 +-
erpnext/regional/india/utils.py | 47 ++++++++++++++++++-
6 files changed, 108 insertions(+), 13 deletions(-)
create mode 100644 erpnext/patches/v12_0/create_taxable_value_field.py
diff --git a/erpnext/hooks.py b/erpnext/hooks.py
index 2e26fd2a9b..98d5966264 100644
--- a/erpnext/hooks.py
+++ b/erpnext/hooks.py
@@ -262,7 +262,8 @@ doc_events = {
],
"on_trash": "erpnext.regional.check_deletion_permission",
"validate": [
- "erpnext.regional.india.utils.validate_document_name"
+ "erpnext.regional.india.utils.validate_document_name",
+ "erpnext.regional.india.utils.update_taxable_values"
]
},
"Purchase Invoice": {
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index bf25db3ea5..d6176fd6f6 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -763,5 +763,6 @@ erpnext.patches.v13_0.setup_gratuity_rule_for_india_and_uae
erpnext.patches.v13_0.setup_uae_vat_fields
execute:frappe.db.set_value('System Settings', None, 'app_name', 'ERPNext')
erpnext.patches.v13_0.rename_discharge_date_in_ip_record
+erpnext.patches.v12_0.create_taxable_value_field
erpnext.patches.v12_0.add_gst_category_in_delivery_note
erpnext.patches.v12_0.purchase_receipt_status
diff --git a/erpnext/patches/v12_0/create_taxable_value_field.py b/erpnext/patches/v12_0/create_taxable_value_field.py
new file mode 100644
index 0000000000..a0c9fcf4cb
--- /dev/null
+++ b/erpnext/patches/v12_0/create_taxable_value_field.py
@@ -0,0 +1,18 @@
+from __future__ import unicode_literals
+import frappe
+from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
+
+def execute():
+ company = frappe.get_all('Company', filters = {'country': 'India'})
+ if not company:
+ return
+
+ custom_fields = {
+ 'Sales Invoice Item': [
+ dict(fieldname='taxable_value', label='Taxable Value',
+ fieldtype='Currency', insert_after='base_net_amount', hidden=1, options="Company:company:default_currency",
+ print_hide=1)
+ ]
+ }
+
+ create_custom_fields(custom_fields, update=True)
\ No newline at end of file
diff --git a/erpnext/regional/india/e_invoice/utils.py b/erpnext/regional/india/e_invoice/utils.py
index 3dd1b36fb6..5f59d64132 100644
--- a/erpnext/regional/india/e_invoice/utils.py
+++ b/erpnext/regional/india/e_invoice/utils.py
@@ -171,10 +171,15 @@ def get_item_list(invoice):
item.description = sanitize_for_json(d.item_name)
item.qty = abs(item.qty)
- item.discount_amount = 0
- item.unit_rate = abs(item.base_net_amount / item.qty)
- item.gross_amount = abs(item.base_net_amount)
- item.taxable_value = abs(item.base_net_amount)
+
+ if invoice.apply_discount_on == 'Net Total' and invoice.discount_amount:
+ item.discount_amount = abs(item.base_amount - item.base_net_amount)
+ else:
+ item.discount_amount = 0
+
+ item.unit_rate = abs((abs(item.taxable_value) - item.discount_amount)/ item.qty)
+ item.gross_amount = abs(item.taxable_value) + item.discount_amount
+ item.taxable_value = abs(item.taxable_value)
item.batch_expiry_date = frappe.db.get_value('Batch', d.batch_no, 'expiry_date') if d.batch_no else None
item.batch_expiry_date = format_date(item.batch_expiry_date, 'dd/mm/yyyy') if item.batch_expiry_date else None
@@ -211,7 +216,7 @@ def update_item_taxes(invoice, item):
item_tax_rate = item_tax_detail[0]
# item tax amount excluding discount amount
- item_tax_amount = (item_tax_rate / 100) * item.base_net_amount
+ item_tax_amount = (item_tax_rate / 100) * item.taxable_value
if t.account_head in gst_accounts.cess_account:
item_tax_amount_after_discount = item_tax_detail[1]
@@ -232,10 +237,14 @@ def get_invoice_value_details(invoice):
invoice_value_details = frappe._dict(dict())
if invoice.apply_discount_on == 'Net Total' and invoice.discount_amount:
- invoice_value_details.base_total = abs(invoice.base_total)
- invoice_value_details.invoice_discount_amt = abs(invoice.base_discount_amount)
+ # Discount already applied on net total which means on items
+ invoice_value_details.base_total = abs(sum([i.taxable_value for i in invoice.get('items')]))
+ invoice_value_details.invoice_discount_amt = 0
+ elif invoice.apply_discount_on == 'Grand Total' and invoice.discount_amount:
+ invoice_value_details.invoice_discount_amt = invoice.base_discount_amount
+ invoice_value_details.base_total = abs(sum([i.taxable_value for i in invoice.get('items')]))
else:
- invoice_value_details.base_total = abs(invoice.base_net_total)
+ invoice_value_details.base_total = abs(sum([i.taxable_value for i in invoice.get('items')]))
# since tax already considers discount amount
invoice_value_details.invoice_discount_amt = 0
@@ -256,7 +265,11 @@ def update_invoice_taxes(invoice, invoice_value_details):
invoice_value_details.total_igst_amt = 0
invoice_value_details.total_cess_amt = 0
invoice_value_details.total_other_charges = 0
+ considered_rows = []
+
for t in invoice.taxes:
+ tax_amount = t.base_tax_amount if (invoice.apply_discount_on == 'Grand Total' and invoice.discount_amount) \
+ else t.base_tax_amount_after_discount_amount
if t.account_head in gst_accounts_list:
if t.account_head in gst_accounts.cess_account:
# using after discount amt since item also uses after discount amt for cess calc
@@ -264,12 +277,26 @@ def update_invoice_taxes(invoice, invoice_value_details):
for tax_type in ['igst', 'cgst', 'sgst']:
if t.account_head in gst_accounts[f'{tax_type}_account']:
- invoice_value_details[f'total_{tax_type}_amt'] += abs(t.base_tax_amount_after_discount_amount)
+
+ invoice_value_details[f'total_{tax_type}_amt'] += abs(tax_amount)
+ update_other_charges(t, invoice_value_details, gst_accounts_list, invoice, considered_rows)
else:
- invoice_value_details.total_other_charges += abs(t.base_tax_amount_after_discount_amount)
+ invoice_value_details.total_other_charges += abs(tax_amount)
return invoice_value_details
+def update_other_charges(tax_row, invoice_value_details, gst_accounts_list, invoice, considered_rows):
+ prev_row_id = cint(tax_row.row_id) - 1
+ if tax_row.account_head in gst_accounts_list and prev_row_id not in considered_rows:
+ if tax_row.charge_type == 'On Previous Row Amount':
+ amount = invoice.get('taxes')[prev_row_id].tax_amount_after_discount_amount
+ invoice_value_details.total_other_charges -= abs(amount)
+ considered_rows.append(prev_row_id)
+ if tax_row.charge_type == 'On Previous Row Total':
+ amount = invoice.get('taxes')[prev_row_id].base_total - invoice.base_net_total
+ invoice_value_details.total_other_charges -= abs(amount)
+ considered_rows.append(prev_row_id)
+
def get_payment_details(invoice):
payee_name = invoice.company
mode_of_payment = ', '.join([d.mode_of_payment for d in invoice.payments])
diff --git a/erpnext/regional/india/setup.py b/erpnext/regional/india/setup.py
index 7c25ce12f5..bf0712f0a5 100644
--- a/erpnext/regional/india/setup.py
+++ b/erpnext/regional/india/setup.py
@@ -127,6 +127,9 @@ def make_custom_fields(update=True):
is_non_gst = dict(fieldname='is_non_gst', label='Is Non GST',
fieldtype='Check', fetch_from='item_code.is_non_gst', insert_after='is_nil_exempt',
print_hide=1)
+ taxable_value = dict(fieldname='taxable_value', label='Taxable Value',
+ fieldtype='Currency', insert_after='base_net_amount', hidden=1, options="Company:company:default_currency",
+ print_hide=1)
purchase_invoice_gst_category = [
dict(fieldname='gst_section', label='GST Details', fieldtype='Section Break',
@@ -460,7 +463,7 @@ def make_custom_fields(update=True):
'Supplier Quotation Item': [hsn_sac_field, nil_rated_exempt, is_non_gst],
'Sales Order Item': [hsn_sac_field, nil_rated_exempt, is_non_gst],
'Delivery Note Item': [hsn_sac_field, nil_rated_exempt, is_non_gst],
- 'Sales Invoice Item': [hsn_sac_field, nil_rated_exempt, is_non_gst],
+ 'Sales Invoice Item': [hsn_sac_field, nil_rated_exempt, is_non_gst, taxable_value],
'Purchase Order Item': [hsn_sac_field, nil_rated_exempt, is_non_gst],
'Purchase Receipt Item': [hsn_sac_field, nil_rated_exempt, is_non_gst],
'Purchase Invoice Item': [hsn_sac_field, nil_rated_exempt, is_non_gst],
diff --git a/erpnext/regional/india/utils.py b/erpnext/regional/india/utils.py
index 3637de438c..082a32f3ff 100644
--- a/erpnext/regional/india/utils.py
+++ b/erpnext/regional/india/utils.py
@@ -2,7 +2,7 @@ from __future__ import unicode_literals
import frappe, re, json
from frappe import _
import erpnext
-from frappe.utils import cstr, flt, date_diff, nowdate, round_based_on_smallest_currency_fraction, money_in_words, getdate
+from frappe.utils import cstr, flt, cint, date_diff, nowdate, round_based_on_smallest_currency_fraction, money_in_words, getdate
from erpnext.regional.india import states, state_numbers
from erpnext.controllers.taxes_and_totals import get_itemised_tax, get_itemised_taxable_amount
from erpnext.controllers.accounts_controller import get_taxes_and_charges
@@ -832,3 +832,48 @@ def get_regional_round_off_accounts(company, account_list):
account_list.extend(gst_account_list)
return account_list
+
+def update_taxable_values(doc, method):
+ country = frappe.get_cached_value('Company', doc.company, 'country')
+
+ if country != 'India':
+ return
+
+ gst_accounts = get_gst_accounts(doc.company)
+
+ # Only considering sgst account to avoid inflating taxable value
+ gst_account_list = gst_accounts.get('sgst_account', []) + gst_accounts.get('sgst_account', []) \
+ + gst_accounts.get('igst_account', [])
+
+ additional_taxes = 0
+ total_charges = 0
+ item_count = 0
+ considered_rows = []
+
+ for tax in doc.get('taxes'):
+ prev_row_id = cint(tax.row_id) - 1
+ if tax.account_head in gst_account_list and prev_row_id not in considered_rows:
+ if tax.charge_type == 'On Previous Row Amount':
+ additional_taxes += doc.get('taxes')[prev_row_id].tax_amount_after_discount_amount
+ considered_rows.append(prev_row_id)
+ if tax.charge_type == 'On Previous Row Total':
+ additional_taxes += doc.get('taxes')[prev_row_id].base_total - doc.base_net_total
+ considered_rows.append(prev_row_id)
+
+ for item in doc.get('items'):
+ if doc.apply_discount_on == 'Grand Total' and doc.discount_amount:
+ proportionate_value = item.base_amount if doc.base_total else item.qty
+ total_value = doc.base_total if doc.base_total else doc.total_qty
+ else:
+ proportionate_value = item.base_net_amount if doc.base_net_total else item.qty
+ total_value = doc.base_net_total if doc.base_net_total else doc.total_qty
+
+ applicable_charges = flt(flt(proportionate_value * (flt(additional_taxes) / flt(total_value)),
+ item.precision('taxable_value')))
+ item.taxable_value = applicable_charges + proportionate_value
+ total_charges += applicable_charges
+ item_count += 1
+
+ if total_charges != additional_taxes:
+ diff = additional_taxes - total_charges
+ doc.get('items')[item_count - 1].taxable_value += diff
From 5f3d7f547c2c0cadca23d007f296c370ef37a98c Mon Sep 17 00:00:00 2001
From: Deepesh Garg <42651287+deepeshgarg007@users.noreply.github.com>
Date: Mon, 12 Apr 2021 10:56:47 +0530
Subject: [PATCH 196/207] fix: Item wise tax rate for consolidated POS invoice
(#25029)
* fix: Item wise tax rate for consolidated POS invoice
* fix: Do not alter item wise taxes for consolidated invoices
* fix: Add test case
* fix: Update
* fix: Set opening stock for test item
* fix: Add valuation rate for opening stock
---
.../pos_invoice_merge_log.py | 34 +++++++++++--
.../test_pos_invoice_merge_log.py | 48 +++++++++++++++++++
erpnext/controllers/taxes_and_totals.py | 13 +++--
erpnext/stock/doctype/item/test_records.json | 2 +
4 files changed, 88 insertions(+), 9 deletions(-)
diff --git a/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py b/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py
index 40f77b4088..2f5ee01baf 100644
--- a/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py
+++ b/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py
@@ -12,6 +12,7 @@ from frappe.utils.background_jobs import enqueue
from frappe.model.mapper import map_doc, map_child_doc
from frappe.utils.scheduler import is_scheduler_inactive
from frappe.core.page.background_jobs.background_jobs import get_info
+import json
from six import iteritems
@@ -131,12 +132,14 @@ class POSInvoiceMergeLog(Document):
if t.account_head == tax.account_head and t.cost_center == tax.cost_center:
t.tax_amount = flt(t.tax_amount) + flt(tax.tax_amount_after_discount_amount)
t.base_tax_amount = flt(t.base_tax_amount) + flt(tax.base_tax_amount_after_discount_amount)
+ update_item_wise_tax_detail(t, tax)
found = True
if not found:
tax.charge_type = 'Actual'
tax.included_in_print_rate = 0
tax.tax_amount = tax.tax_amount_after_discount_amount
tax.base_tax_amount = tax.base_tax_amount_after_discount_amount
+ tax.item_wise_tax_detail = tax.item_wise_tax_detail
taxes.append(tax)
for payment in doc.get('payments'):
@@ -172,7 +175,7 @@ class POSInvoiceMergeLog(Document):
sales_invoice.posting_date = getdate(nowdate())
return sales_invoice
-
+
def update_pos_invoices(self, invoice_docs, sales_invoice='', credit_note=''):
for doc in invoice_docs:
doc.load_from_db()
@@ -187,6 +190,26 @@ class POSInvoiceMergeLog(Document):
si.flags.ignore_validate = True
si.cancel()
+def update_item_wise_tax_detail(consolidate_tax_row, tax_row):
+ consolidated_tax_detail = json.loads(consolidate_tax_row.item_wise_tax_detail)
+ tax_row_detail = json.loads(tax_row.item_wise_tax_detail)
+
+ if not consolidated_tax_detail:
+ consolidated_tax_detail = {}
+
+ for item_code, tax_data in tax_row_detail.items():
+ if consolidated_tax_detail.get(item_code):
+ consolidated_tax_data = consolidated_tax_detail.get(item_code)
+ consolidated_tax_detail.update({
+ item_code: [consolidated_tax_data[0], consolidated_tax_data[1] + tax_data[1]]
+ })
+ else:
+ consolidated_tax_detail.update({
+ item_code: [tax_data[0], tax_data[1]]
+ })
+
+ consolidate_tax_row.item_wise_tax_detail = json.dumps(consolidated_tax_detail, separators=(',', ':'))
+
def get_all_unconsolidated_invoices():
filters = {
'consolidated_invoice': [ 'in', [ '', None ]],
@@ -214,7 +237,7 @@ def consolidate_pos_invoices(pos_invoices=[], closing_entry={}):
if len(invoices) >= 5 and closing_entry:
closing_entry.set_status(update=True, status='Queued')
- enqueue_job(create_merge_logs, invoice_by_customer, closing_entry)
+ enqueue_job(create_merge_logs, invoice_by_customer=invoice_by_customer, closing_entry=closing_entry)
else:
create_merge_logs(invoice_by_customer, closing_entry)
@@ -227,7 +250,7 @@ def unconsolidate_pos_invoices(closing_entry):
if len(merge_logs) >= 5:
closing_entry.set_status(update=True, status='Queued')
- enqueue_job(cancel_merge_logs, merge_logs, closing_entry)
+ enqueue_job(cancel_merge_logs, merge_logs=merge_logs, closing_entry=closing_entry)
else:
cancel_merge_logs(merge_logs, closing_entry)
@@ -241,7 +264,7 @@ def create_merge_logs(invoice_by_customer, closing_entry={}):
merge_log.set('pos_invoices', invoices)
merge_log.save(ignore_permissions=True)
merge_log.submit()
-
+
if closing_entry:
closing_entry.set_status(update=True, status='Submitted')
closing_entry.update_opening_entry()
@@ -256,7 +279,7 @@ def cancel_merge_logs(merge_logs, closing_entry={}):
closing_entry.set_status(update=True, status='Cancelled')
closing_entry.update_opening_entry(for_cancel=True)
-def enqueue_job(job, invoice_by_customer, closing_entry):
+def enqueue_job(job, merge_logs=None, invoice_by_customer=None, closing_entry=None):
check_scheduler_status()
job_name = closing_entry.get("name")
@@ -269,6 +292,7 @@ def enqueue_job(job, invoice_by_customer, closing_entry):
job_name=job_name,
closing_entry=closing_entry,
invoice_by_customer=invoice_by_customer,
+ merge_logs=merge_logs,
now=frappe.conf.developer_mode or frappe.flags.in_test
)
diff --git a/erpnext/accounts/doctype/pos_invoice_merge_log/test_pos_invoice_merge_log.py b/erpnext/accounts/doctype/pos_invoice_merge_log/test_pos_invoice_merge_log.py
index d880caa3c7..040a815fab 100644
--- a/erpnext/accounts/doctype/pos_invoice_merge_log/test_pos_invoice_merge_log.py
+++ b/erpnext/accounts/doctype/pos_invoice_merge_log/test_pos_invoice_merge_log.py
@@ -5,6 +5,7 @@ from __future__ import unicode_literals
import frappe
import unittest
+import json
from erpnext.accounts.doctype.pos_invoice.test_pos_invoice import create_pos_invoice
from erpnext.accounts.doctype.pos_invoice.pos_invoice import make_sales_return
from erpnext.accounts.doctype.pos_invoice_merge_log.pos_invoice_merge_log import consolidate_pos_invoices
@@ -99,4 +100,51 @@ class TestPOSInvoiceMergeLog(unittest.TestCase):
frappe.db.sql("delete from `tabPOS Profile`")
frappe.db.sql("delete from `tabPOS Invoice`")
+ def test_consolidated_invoice_item_taxes(self):
+ frappe.db.sql("delete from `tabPOS Invoice`")
+
+ try:
+ inv = create_pos_invoice(qty=1, rate=100, do_not_save=True)
+
+ inv.append("taxes", {
+ "account_head": "_Test Account VAT - _TC",
+ "charge_type": "On Net Total",
+ "cost_center": "_Test Cost Center - _TC",
+ "description": "VAT",
+ "doctype": "Sales Taxes and Charges",
+ "rate": 9
+ })
+ inv.insert()
+ inv.submit()
+
+ inv2 = create_pos_invoice(qty=1, rate=100, do_not_save=True)
+ inv2.get('items')[0].item_code = '_Test Item 2'
+ inv2.append("taxes", {
+ "account_head": "_Test Account VAT - _TC",
+ "charge_type": "On Net Total",
+ "cost_center": "_Test Cost Center - _TC",
+ "description": "VAT",
+ "doctype": "Sales Taxes and Charges",
+ "rate": 5
+ })
+ inv2.insert()
+ inv2.submit()
+
+ consolidate_pos_invoices()
+ inv.load_from_db()
+
+ consolidated_invoice = frappe.get_doc('Sales Invoice', inv.consolidated_invoice)
+ item_wise_tax_detail = json.loads(consolidated_invoice.get('taxes')[0].item_wise_tax_detail)
+
+ tax_rate, amount = item_wise_tax_detail.get('_Test Item')
+ self.assertEqual(tax_rate, 9)
+ self.assertEqual(amount, 9)
+
+ tax_rate2, amount2 = item_wise_tax_detail.get('_Test Item 2')
+ self.assertEqual(tax_rate2, 5)
+ self.assertEqual(amount2, 5)
+ finally:
+ frappe.set_user("Administrator")
+ frappe.db.sql("delete from `tabPOS Profile`")
+ frappe.db.sql("delete from `tabPOS Invoice`")
diff --git a/erpnext/controllers/taxes_and_totals.py b/erpnext/controllers/taxes_and_totals.py
index 5f73c55836..7653a5dfdc 100644
--- a/erpnext/controllers/taxes_and_totals.py
+++ b/erpnext/controllers/taxes_and_totals.py
@@ -147,7 +147,9 @@ class calculate_taxes_and_totals(object):
validate_taxes_and_charges(tax)
validate_inclusive_tax(tax, self.doc)
- tax.item_wise_tax_detail = {}
+ if not self.doc.get('is_consolidated'):
+ tax.item_wise_tax_detail = {}
+
tax_fields = ["total", "tax_amount_after_discount_amount",
"tax_amount_for_current_item", "grand_total_for_current_item",
"tax_fraction_for_current_item", "grand_total_fraction_for_current_item"]
@@ -338,7 +340,9 @@ class calculate_taxes_and_totals(object):
current_tax_amount = tax_rate * item.qty
current_tax_amount = self.get_final_current_tax_amount(tax, current_tax_amount)
- self.set_item_wise_tax(item, tax, tax_rate, current_tax_amount)
+
+ if not self.doc.get("is_consolidated"):
+ self.set_item_wise_tax(item, tax, tax_rate, current_tax_amount)
return current_tax_amount
@@ -440,8 +444,9 @@ class calculate_taxes_and_totals(object):
self._set_in_company_currency(self.doc, ["rounding_adjustment", "rounded_total"])
def _cleanup(self):
- for tax in self.doc.get("taxes"):
- tax.item_wise_tax_detail = json.dumps(tax.item_wise_tax_detail, separators=(',', ':'))
+ if not self.doc.get('is_consolidated'):
+ for tax in self.doc.get("taxes"):
+ tax.item_wise_tax_detail = json.dumps(tax.item_wise_tax_detail, separators=(',', ':'))
def set_discount_amount(self):
if self.doc.additional_discount_percentage:
diff --git a/erpnext/stock/doctype/item/test_records.json b/erpnext/stock/doctype/item/test_records.json
index c1f20a47b7..6cec85288f 100644
--- a/erpnext/stock/doctype/item/test_records.json
+++ b/erpnext/stock/doctype/item/test_records.json
@@ -59,6 +59,8 @@
"show_in_website": 1,
"website_warehouse": "_Test Warehouse - _TC",
"gst_hsn_code": "999800",
+ "opening_stock": 10,
+ "valuation_rate": 100,
"item_defaults": [{
"company": "_Test Company",
"default_warehouse": "_Test Warehouse - _TC",
From 42f4a00c885b03166a092abe5073d3441ae53a88 Mon Sep 17 00:00:00 2001
From: prssanna
Date: Mon, 12 Apr 2021 12:01:20 +0530
Subject: [PATCH 197/207] fix: declare data before assigining
---
erpnext/accounts/doctype/sales_invoice/sales_invoice.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index b361c0c345..26d60389f6 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -916,7 +916,7 @@ frappe.ui.form.on('Sales Invoice Timesheet', {
},
callback: function(r, rt) {
if(r.message){
- data = r.message;
+ let data = r.message;
frappe.model.set_value(cdt, cdn, "billing_hours", data.billing_hours);
frappe.model.set_value(cdt, cdn, "billing_amount", data.billing_amount);
frappe.model.set_value(cdt, cdn, "timesheet_detail", data.timesheet_detail);
From 49336b8065e498fc2ae260ec3414c792dfa24585 Mon Sep 17 00:00:00 2001
From: Saqib
Date: Mon, 12 Apr 2021 12:17:50 +0530
Subject: [PATCH 198/207] fix: consolidated sales invoice posting date (#25119)
---
.../pos_invoice_merge_log/pos_invoice_merge_log.py | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
diff --git a/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py b/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py
index 2f5ee01baf..6d2cffcf68 100644
--- a/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py
+++ b/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py
@@ -79,8 +79,11 @@ class POSInvoiceMergeLog(Document):
sales_invoice = self.merge_pos_invoice_into(sales_invoice, data)
sales_invoice.is_consolidated = 1
+ sales_invoice.set_posting_time = 1
+ sales_invoice.posting_date = getdate(self.posting_date)
sales_invoice.save()
sales_invoice.submit()
+
self.consolidated_invoice = sales_invoice.name
return sales_invoice.name
@@ -92,10 +95,13 @@ class POSInvoiceMergeLog(Document):
credit_note = self.merge_pos_invoice_into(credit_note, data)
credit_note.is_consolidated = 1
+ credit_note.set_posting_time = 1
+ credit_note.posting_date = getdate(self.posting_date)
# TODO: return could be against multiple sales invoice which could also have been consolidated?
# credit_note.return_against = self.consolidated_invoice
credit_note.save()
credit_note.submit()
+
self.consolidated_credit_note = credit_note.name
return credit_note.name
@@ -171,8 +177,6 @@ class POSInvoiceMergeLog(Document):
sales_invoice = frappe.new_doc('Sales Invoice')
sales_invoice.customer = self.customer
sales_invoice.is_pos = 1
- # date can be pos closing date?
- sales_invoice.posting_date = getdate(nowdate())
return sales_invoice
@@ -257,7 +261,7 @@ def unconsolidate_pos_invoices(closing_entry):
def create_merge_logs(invoice_by_customer, closing_entry={}):
for customer, invoices in iteritems(invoice_by_customer):
merge_log = frappe.new_doc('POS Invoice Merge Log')
- merge_log.posting_date = getdate(nowdate())
+ merge_log.posting_date = getdate(closing_entry.get('posting_date'))
merge_log.customer = customer
merge_log.pos_closing_entry = closing_entry.get('name', None)
From 2339de7333514f1b45ec942fe822bccbf63b7cc4 Mon Sep 17 00:00:00 2001
From: Rohit Waghchaure
Date: Mon, 12 Apr 2021 16:09:55 +0530
Subject: [PATCH 199/207] fix: update scheduler check tim
---
.../doctype/repost_item_valuation/repost_item_valuation.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
index e68360266f..3f83780569 100644
--- a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
+++ b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
@@ -127,7 +127,7 @@ def repost_entries():
check_if_stock_and_account_balance_synced(today(), d.name)
def get_repost_item_valuation_entries():
- date = add_to_date(today(), hours=-12)
+ date = add_to_date(today(), hours=-3)
return frappe.db.sql(""" SELECT name from `tabRepost Item Valuation`
WHERE status != 'Completed' and creation <= %s and docstatus = 1
From 9320316462e1fdb96843209e3e01fb8179db924e Mon Sep 17 00:00:00 2001
From: Saqib
Date: Mon, 12 Apr 2021 17:55:46 +0530
Subject: [PATCH 200/207] feat(india): bulk e-invoice generation (#24969)
---
.../sales_invoice/regional/india_list.js | 147 ++++-
erpnext/patches.txt | 5 +-
.../add_company_link_to_einvoice_settings.py | 16 +
.../v12_0/add_einvoice_status_field.py | 69 ++
...add_einvoice_summary_report_permissions.py | 18 +
.../update_vehicle_no_reqd_condition.py | 0
.../e_invoice_settings.json | 10 +-
.../e_invoice_user/e_invoice_user.json | 11 +-
erpnext/regional/india/e_invoice/einvoice.js | 53 +-
erpnext/regional/india/e_invoice/utils.py | 590 +++++++++++++-----
erpnext/regional/india/setup.py | 32 +-
erpnext/regional/india/utils.py | 13 +-
.../report/e_invoice_summary/__init__.py | 0
.../e_invoice_summary/e_invoice_summary.js | 55 ++
.../e_invoice_summary/e_invoice_summary.json | 28 +
.../e_invoice_summary/e_invoice_summary.py | 106 ++++
16 files changed, 925 insertions(+), 228 deletions(-)
create mode 100644 erpnext/patches/v12_0/add_company_link_to_einvoice_settings.py
create mode 100644 erpnext/patches/v12_0/add_einvoice_status_field.py
create mode 100644 erpnext/patches/v12_0/add_einvoice_summary_report_permissions.py
rename erpnext/patches/{v13_0 => v12_0}/update_vehicle_no_reqd_condition.py (100%)
create mode 100644 erpnext/regional/report/e_invoice_summary/__init__.py
create mode 100644 erpnext/regional/report/e_invoice_summary/e_invoice_summary.js
create mode 100644 erpnext/regional/report/e_invoice_summary/e_invoice_summary.json
create mode 100644 erpnext/regional/report/e_invoice_summary/e_invoice_summary.py
diff --git a/erpnext/accounts/doctype/sales_invoice/regional/india_list.js b/erpnext/accounts/doctype/sales_invoice/regional/india_list.js
index 3e1c5228ea..ada665a0ca 100644
--- a/erpnext/accounts/doctype/sales_invoice/regional/india_list.js
+++ b/erpnext/accounts/doctype/sales_invoice/regional/india_list.js
@@ -1,14 +1,14 @@
var globalOnload = frappe.listview_settings['Sales Invoice'].onload;
-frappe.listview_settings['Sales Invoice'].onload = function (doclist) {
+frappe.listview_settings['Sales Invoice'].onload = function (list_view) {
// Provision in case onload event is added to sales_invoice.js in future
if (globalOnload) {
- globalOnload(doclist);
+ globalOnload(list_view);
}
const action = () => {
- const selected_docs = doclist.get_checked_items();
- const docnames = doclist.get_checked_items(true);
+ const selected_docs = list_view.get_checked_items();
+ const docnames = list_view.get_checked_items(true);
for (let doc of selected_docs) {
if (doc.docstatus !== 1) {
@@ -19,7 +19,7 @@ frappe.listview_settings['Sales Invoice'].onload = function (doclist) {
frappe.call({
method: 'erpnext.regional.india.utils.generate_ewb_json',
args: {
- 'dt': doclist.doctype,
+ 'dt': list_view.doctype,
'dn': docnames
},
callback: function(r) {
@@ -35,5 +35,140 @@ frappe.listview_settings['Sales Invoice'].onload = function (doclist) {
});
};
- doclist.page.add_actions_menu_item(__('Generate E-Way Bill JSON'), action, false);
+ list_view.page.add_actions_menu_item(__('Generate E-Way Bill JSON'), action, false);
+
+ const generate_irns = () => {
+ const docnames = list_view.get_checked_items(true);
+ if (docnames && docnames.length) {
+ frappe.call({
+ method: 'erpnext.regional.india.e_invoice.utils.generate_einvoices',
+ args: { docnames },
+ freeze: true,
+ freeze_message: __('Generating E-Invoices...')
+ });
+ } else {
+ frappe.msgprint({
+ message: __('Please select at least one sales invoice to generate IRN'),
+ title: __('No Invoice Selected'),
+ indicator: 'red'
+ });
+ }
+ };
+
+ const cancel_irns = () => {
+ const docnames = list_view.get_checked_items(true);
+
+ const fields = [
+ {
+ "label": "Reason",
+ "fieldname": "reason",
+ "fieldtype": "Select",
+ "reqd": 1,
+ "default": "1-Duplicate",
+ "options": ["1-Duplicate", "2-Data Entry Error", "3-Order Cancelled", "4-Other"]
+ },
+ {
+ "label": "Remark",
+ "fieldname": "remark",
+ "fieldtype": "Data",
+ "reqd": 1
+ }
+ ];
+
+ const d = new frappe.ui.Dialog({
+ title: __("Cancel IRN"),
+ fields: fields,
+ primary_action: function() {
+ const data = d.get_values();
+ frappe.call({
+ method: 'erpnext.regional.india.e_invoice.utils.cancel_irns',
+ args: {
+ doctype: list_view.doctype,
+ docnames,
+ reason: data.reason.split('-')[0],
+ remark: data.remark
+ },
+ freeze: true,
+ freeze_message: __('Cancelling E-Invoices...'),
+ });
+ d.hide();
+ },
+ primary_action_label: __('Submit')
+ });
+ d.show();
+ };
+
+ let einvoicing_enabled = false;
+ frappe.db.get_single_value("E Invoice Settings", "enable").then(enabled => {
+ einvoicing_enabled = enabled;
+ });
+
+ list_view.$result.on("change", "input[type=checkbox]", () => {
+ if (einvoicing_enabled) {
+ const docnames = list_view.get_checked_items(true);
+ // show/hide e-invoicing actions when no sales invoices are checked
+ if (docnames && docnames.length) {
+ // prevent adding actions twice if e-invoicing action group already exists
+ if (list_view.page.get_inner_group_button(__('E-Invoicing')).length == 0) {
+ list_view.page.add_inner_button(__('Generate IRNs'), generate_irns, __('E-Invoicing'));
+ list_view.page.add_inner_button(__('Cancel IRNs'), cancel_irns, __('E-Invoicing'));
+ }
+ } else {
+ list_view.page.remove_inner_button(__('Generate IRNs'), __('E-Invoicing'));
+ list_view.page.remove_inner_button(__('Cancel IRNs'), __('E-Invoicing'));
+ }
+ }
+ });
+
+ frappe.realtime.on("bulk_einvoice_generation_complete", (data) => {
+ const { failures, user, invoices } = data;
+
+ if (invoices.length != failures.length) {
+ frappe.msgprint({
+ message: __('{0} e-invoices generated successfully', [invoices.length]),
+ title: __('Bulk E-Invoice Generation Complete'),
+ indicator: 'orange'
+ });
+ }
+
+ if (failures && failures.length && user == frappe.session.user) {
+ let message = `
+ Failed to generate IRNs for following ${failures.length} sales invoices:
+
+ ${failures.map(d => `- ${d.docname}
`).join('')}
+
+ `;
+ frappe.msgprint({
+ message: message,
+ title: __('Bulk E-Invoice Generation Complete'),
+ indicator: 'orange'
+ });
+ }
+ });
+
+ frappe.realtime.on("bulk_einvoice_cancellation_complete", (data) => {
+ const { failures, user, invoices } = data;
+
+ if (invoices.length != failures.length) {
+ frappe.msgprint({
+ message: __('{0} e-invoices cancelled successfully', [invoices.length]),
+ title: __('Bulk E-Invoice Cancellation Complete'),
+ indicator: 'orange'
+ });
+ }
+
+ if (failures && failures.length && user == frappe.session.user) {
+ let message = `
+ Failed to cancel IRNs for following ${failures.length} sales invoices:
+
+ ${failures.map(d => `- ${d.docname}
`).join('')}
+
+ `;
+ frappe.msgprint({
+ message: message,
+ title: __('Bulk E-Invoice Cancellation Complete'),
+ indicator: 'orange'
+ });
+ }
+ });
};
\ No newline at end of file
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index d6176fd6f6..7c842fcfa9 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -756,12 +756,15 @@ erpnext.patches.v13_0.update_payment_terms_outstanding
erpnext.patches.v12_0.add_state_code_for_ladakh
erpnext.patches.v13_0.item_reposting_for_incorrect_sl_and_gl
erpnext.patches.v13_0.delete_old_bank_reconciliation_doctypes
-erpnext.patches.v13_0.update_vehicle_no_reqd_condition
+erpnext.patches.v12_0.update_vehicle_no_reqd_condition
+erpnext.patches.v12_0.add_einvoice_status_field #2021-03-17
+erpnext.patches.v12_0.add_einvoice_summary_report_permissions
erpnext.patches.v13_0.setup_fields_for_80g_certificate_and_donation
erpnext.patches.v13_0.rename_membership_settings_to_non_profit_settings
erpnext.patches.v13_0.setup_gratuity_rule_for_india_and_uae
erpnext.patches.v13_0.setup_uae_vat_fields
execute:frappe.db.set_value('System Settings', None, 'app_name', 'ERPNext')
+erpnext.patches.v12_0.add_company_link_to_einvoice_settings
erpnext.patches.v13_0.rename_discharge_date_in_ip_record
erpnext.patches.v12_0.create_taxable_value_field
erpnext.patches.v12_0.add_gst_category_in_delivery_note
diff --git a/erpnext/patches/v12_0/add_company_link_to_einvoice_settings.py b/erpnext/patches/v12_0/add_company_link_to_einvoice_settings.py
new file mode 100644
index 0000000000..fe284e814c
--- /dev/null
+++ b/erpnext/patches/v12_0/add_company_link_to_einvoice_settings.py
@@ -0,0 +1,16 @@
+from __future__ import unicode_literals
+import frappe
+
+def execute():
+ company = frappe.get_all('Company', filters = {'country': 'India'})
+ if not company or not frappe.db.count('E Invoice User'):
+ return
+
+ frappe.reload_doc("regional", "doctype", "e_invoice_user")
+ for creds in frappe.db.get_all('E Invoice User', fields=['name', 'gstin']):
+ company_name = frappe.db.sql("""
+ select dl.link_name from `tabAddress` a, `tabDynamic Link` dl
+ where a.gstin = %s and dl.parent = a.name and dl.link_doctype = 'Company'
+ """, (creds.get('gstin')))
+ if company_name[0]:
+ frappe.db.set_value('E Invoice User', creds.get('name'), 'company', company_name[0][0])
\ No newline at end of file
diff --git a/erpnext/patches/v12_0/add_einvoice_status_field.py b/erpnext/patches/v12_0/add_einvoice_status_field.py
new file mode 100644
index 0000000000..387e88588d
--- /dev/null
+++ b/erpnext/patches/v12_0/add_einvoice_status_field.py
@@ -0,0 +1,69 @@
+from __future__ import unicode_literals
+import json
+import frappe
+from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
+
+def execute():
+ company = frappe.get_all('Company', filters = {'country': 'India'})
+ if not company:
+ return
+
+ # move hidden einvoice fields to a different section
+ custom_fields = {
+ 'Sales Invoice': [
+ dict(fieldname='einvoice_section', label='E-Invoice Fields', fieldtype='Section Break', insert_after='gst_vehicle_type',
+ print_hide=1, hidden=1),
+
+ dict(fieldname='ack_no', label='Ack. No.', fieldtype='Data', read_only=1, hidden=1, insert_after='einvoice_section',
+ no_copy=1, print_hide=1),
+
+ dict(fieldname='ack_date', label='Ack. Date', fieldtype='Data', read_only=1, hidden=1, insert_after='ack_no', no_copy=1, print_hide=1),
+
+ dict(fieldname='irn_cancel_date', label='Cancel Date', fieldtype='Data', read_only=1, hidden=1, insert_after='ack_date',
+ no_copy=1, print_hide=1),
+
+ dict(fieldname='signed_einvoice', label='Signed E-Invoice', fieldtype='Code', options='JSON', hidden=1, insert_after='irn_cancel_date',
+ no_copy=1, print_hide=1, read_only=1),
+
+ dict(fieldname='signed_qr_code', label='Signed QRCode', fieldtype='Code', options='JSON', hidden=1, insert_after='signed_einvoice',
+ no_copy=1, print_hide=1, read_only=1),
+
+ dict(fieldname='qrcode_image', label='QRCode', fieldtype='Attach Image', hidden=1, insert_after='signed_qr_code',
+ no_copy=1, print_hide=1, read_only=1),
+
+ dict(fieldname='einvoice_status', label='E-Invoice Status', fieldtype='Select', insert_after='qrcode_image',
+ options='\nPending\nGenerated\nCancelled\nFailed', default=None, hidden=1, no_copy=1, print_hide=1, read_only=1),
+
+ dict(fieldname='failure_description', label='E-Invoice Failure Description', fieldtype='Code', options='JSON',
+ hidden=1, insert_after='einvoice_status', no_copy=1, print_hide=1, read_only=1)
+ ]
+ }
+ create_custom_fields(custom_fields, update=True)
+
+ if frappe.db.exists('E Invoice Settings') and frappe.db.get_single_value('E Invoice Settings', 'enable'):
+ frappe.db.sql('''
+ UPDATE `tabSales Invoice` SET einvoice_status = 'Pending'
+ WHERE
+ posting_date >= '2021-04-01'
+ AND ifnull(irn, '') = ''
+ AND ifnull(`billing_address_gstin`, '') != ifnull(`company_gstin`, '')
+ AND ifnull(gst_category, '') in ('Registered Regular', 'SEZ', 'Overseas', 'Deemed Export')
+ ''')
+
+ # set appropriate statuses
+ frappe.db.sql('''UPDATE `tabSales Invoice` SET einvoice_status = 'Generated'
+ WHERE ifnull(irn, '') != '' AND ifnull(irn_cancelled, 0) = 0''')
+
+ frappe.db.sql('''UPDATE `tabSales Invoice` SET einvoice_status = 'Cancelled'
+ WHERE ifnull(irn_cancelled, 0) = 1''')
+
+ # set correct acknowledgement in e-invoices
+ einvoices = frappe.get_all('Sales Invoice', {'irn': ['is', 'set']}, ['name', 'signed_einvoice'])
+
+ if einvoices:
+ for inv in einvoices:
+ signed_einvoice = inv.get('signed_einvoice')
+ if signed_einvoice:
+ signed_einvoice = json.loads(signed_einvoice)
+ frappe.db.set_value('Sales Invoice', inv.get('name'), 'ack_no', signed_einvoice.get('AckNo'), update_modified=False)
+ frappe.db.set_value('Sales Invoice', inv.get('name'), 'ack_date', signed_einvoice.get('AckDt'), update_modified=False)
\ No newline at end of file
diff --git a/erpnext/patches/v12_0/add_einvoice_summary_report_permissions.py b/erpnext/patches/v12_0/add_einvoice_summary_report_permissions.py
new file mode 100644
index 0000000000..bf8f566d32
--- /dev/null
+++ b/erpnext/patches/v12_0/add_einvoice_summary_report_permissions.py
@@ -0,0 +1,18 @@
+from __future__ import unicode_literals
+import frappe
+
+def execute():
+ company = frappe.get_all('Company', filters = {'country': 'India'})
+ if not company:
+ return
+
+ if frappe.db.exists('Report', 'E-Invoice Summary') and \
+ not frappe.db.get_value('Custom Role', dict(report='E-Invoice Summary')):
+ frappe.get_doc(dict(
+ doctype='Custom Role',
+ report='E-Invoice Summary',
+ roles= [
+ dict(role='Accounts User'),
+ dict(role='Accounts Manager')
+ ]
+ )).insert()
\ No newline at end of file
diff --git a/erpnext/patches/v13_0/update_vehicle_no_reqd_condition.py b/erpnext/patches/v12_0/update_vehicle_no_reqd_condition.py
similarity index 100%
rename from erpnext/patches/v13_0/update_vehicle_no_reqd_condition.py
rename to erpnext/patches/v12_0/update_vehicle_no_reqd_condition.py
diff --git a/erpnext/regional/doctype/e_invoice_settings/e_invoice_settings.json b/erpnext/regional/doctype/e_invoice_settings/e_invoice_settings.json
index db8bda75bf..68ed3391d0 100644
--- a/erpnext/regional/doctype/e_invoice_settings/e_invoice_settings.json
+++ b/erpnext/regional/doctype/e_invoice_settings/e_invoice_settings.json
@@ -8,6 +8,7 @@
"enable",
"section_break_2",
"sandbox_mode",
+ "applicable_from",
"credentials",
"auth_token",
"token_expiry"
@@ -48,12 +49,19 @@
"fieldname": "sandbox_mode",
"fieldtype": "Check",
"label": "Sandbox Mode"
+ },
+ {
+ "fieldname": "applicable_from",
+ "fieldtype": "Date",
+ "in_list_view": 1,
+ "label": "Applicable From",
+ "reqd": 1
}
],
"index_web_pages_for_search": 1,
"issingle": 1,
"links": [],
- "modified": "2021-01-13 12:04:49.449199",
+ "modified": "2021-03-30 12:26:25.538294",
"modified_by": "Administrator",
"module": "Regional",
"name": "E Invoice Settings",
diff --git a/erpnext/regional/doctype/e_invoice_user/e_invoice_user.json b/erpnext/regional/doctype/e_invoice_user/e_invoice_user.json
index dd9d99773a..a65b1ca7ca 100644
--- a/erpnext/regional/doctype/e_invoice_user/e_invoice_user.json
+++ b/erpnext/regional/doctype/e_invoice_user/e_invoice_user.json
@@ -5,6 +5,7 @@
"editable_grid": 1,
"engine": "InnoDB",
"field_order": [
+ "company",
"gstin",
"username",
"password"
@@ -30,12 +31,20 @@
"in_list_view": 1,
"label": "Password",
"reqd": 1
+ },
+ {
+ "fieldname": "company",
+ "fieldtype": "Link",
+ "in_list_view": 1,
+ "label": "Company",
+ "options": "Company",
+ "reqd": 1
}
],
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
- "modified": "2020-12-22 15:10:53.466205",
+ "modified": "2021-03-22 12:16:56.365616",
"modified_by": "Administrator",
"module": "Regional",
"name": "E Invoice User",
diff --git a/erpnext/regional/india/e_invoice/einvoice.js b/erpnext/regional/india/e_invoice/einvoice.js
index 7cd64f2fc0..c1a222adb4 100644
--- a/erpnext/regional/india/e_invoice/einvoice.js
+++ b/erpnext/regional/india/e_invoice/einvoice.js
@@ -1,12 +1,13 @@
erpnext.setup_einvoice_actions = (doctype) => {
frappe.ui.form.on(doctype, {
async refresh(frm) {
- const einvoicing_enabled = await frappe.db.get_single_value("E Invoice Settings", "enable");
- const supply_type = frm.doc.gst_category;
- const valid_supply_type = ['Registered Regular', 'SEZ', 'Overseas', 'Deemed Export'].includes(supply_type);
- const company_transaction = frm.doc.billing_address_gstin == frm.doc.company_gstin;
+ const res = await frappe.call({
+ method: 'erpnext.regional.india.e_invoice.utils.validate_eligibility',
+ args: { doc: frm.doc }
+ });
+ const invoice_eligible = res.message;
- if (cint(einvoicing_enabled) == 0 || !valid_supply_type || company_transaction) return;
+ if (!invoice_eligible) return;
const { doctype, irn, irn_cancelled, ewaybill, eway_bill_cancelled, name, __unsaved } = frm.doc;
@@ -109,45 +110,25 @@ erpnext.setup_einvoice_actions = (doctype) => {
}
if (irn && ewaybill && !irn_cancelled && !eway_bill_cancelled) {
- const fields = [
- {
- "label": "Reason",
- "fieldname": "reason",
- "fieldtype": "Select",
- "reqd": 1,
- "default": "1-Duplicate",
- "options": ["1-Duplicate", "2-Data Entry Error", "3-Order Cancelled", "4-Other"]
- },
- {
- "label": "Remark",
- "fieldname": "remark",
- "fieldtype": "Data",
- "reqd": 1
- }
- ];
const action = () => {
- const d = new frappe.ui.Dialog({
- title: __('Cancel E-Way Bill'),
- fields: fields,
+ let message = __('Cancellation of e-way bill is currently not supported. ');
+ message += '
';
+ message += __('You must first use the portal to cancel the e-way bill and then update the cancelled status in the ERPNext system.');
+
+ frappe.msgprint({
+ title: __('Update E-Way Bill Cancelled Status?'),
+ message: message,
+ indicator: 'orange',
primary_action: function() {
- const data = d.get_values();
frappe.call({
method: 'erpnext.regional.india.e_invoice.utils.cancel_eway_bill',
- args: {
- doctype,
- docname: name,
- eway_bill: ewaybill,
- reason: data.reason.split('-')[0],
- remark: data.remark
- },
+ args: { doctype, docname: name },
freeze: true,
- callback: () => frm.reload_doc() || d.hide(),
- error: () => d.hide()
+ callback: () => frm.reload_doc()
});
},
- primary_action_label: __('Submit')
+ primary_action_label: __('Yes')
});
- d.show();
};
add_custom_button(__("Cancel E-Way Bill"), action);
}
diff --git a/erpnext/regional/india/e_invoice/utils.py b/erpnext/regional/india/e_invoice/utils.py
index 5f59d64132..fb1f46493f 100644
--- a/erpnext/regional/india/e_invoice/utils.py
+++ b/erpnext/regional/india/e_invoice/utils.py
@@ -15,18 +15,43 @@ import traceback
import io
from frappe import _, bold
from pyqrcode import create as qrcreate
+from frappe.utils.background_jobs import enqueue
+from frappe.utils.scheduler import is_scheduler_inactive
+from frappe.core.page.background_jobs.background_jobs import get_info
from frappe.integrations.utils import make_post_request, make_get_request
from erpnext.regional.india.utils import get_gst_accounts, get_place_of_supply
-from frappe.utils.data import cstr, cint, format_date, flt, time_diff_in_seconds, now_datetime, add_to_date, get_link_to_form
+from frappe.utils.data import cstr, cint, format_date, flt, time_diff_in_seconds, now_datetime, add_to_date, get_link_to_form, getdate, time_diff_in_hours
+
+@frappe.whitelist()
+def validate_eligibility(doc):
+ if isinstance(doc, six.string_types):
+ doc = json.loads(doc)
+
+ invalid_doctype = doc.get('doctype') != 'Sales Invoice'
+ if invalid_doctype:
+ return False
+
+ einvoicing_enabled = cint(frappe.db.get_single_value('E Invoice Settings', 'enable'))
+ if not einvoicing_enabled:
+ return False
+
+ einvoicing_eligible_from = frappe.db.get_single_value('E Invoice Settings', 'applicable_from') or '2021-04-01'
+ if getdate(doc.get('posting_date')) < getdate(einvoicing_eligible_from):
+ return False
-def validate_einvoice_fields(doc):
- einvoicing_enabled = cint(frappe.db.get_value('E Invoice Settings', 'E Invoice Settings', 'enable'))
- invalid_doctype = doc.doctype != 'Sales Invoice'
invalid_supply_type = doc.get('gst_category') not in ['Registered Regular', 'SEZ', 'Overseas', 'Deemed Export']
company_transaction = doc.get('billing_address_gstin') == doc.get('company_gstin')
no_taxes_applied = not doc.get('taxes')
- if not einvoicing_enabled or invalid_doctype or invalid_supply_type or company_transaction or no_taxes_applied:
+ if invalid_supply_type or company_transaction or no_taxes_applied:
+ return False
+
+ return True
+
+def validate_einvoice_fields(doc):
+ invoice_eligible = validate_eligibility(doc)
+
+ if not invoice_eligible:
return
if doc.docstatus == 0 and doc._action == 'save':
@@ -35,6 +60,8 @@ def validate_einvoice_fields(doc):
if len(doc.name) > 16:
raise_document_name_too_long_error()
+ doc.einvoice_status = 'Pending'
+
elif doc.docstatus == 1 and doc._action == 'submit' and not doc.irn:
frappe.throw(_('You must generate IRN before submitting the document.'), title=_('Missing IRN'))
@@ -76,6 +103,9 @@ def get_transaction_details(invoice):
))
def get_doc_details(invoice):
+ if getdate(invoice.posting_date) < getdate('2021-01-01'):
+ frappe.throw(_('IRN generation is not allowed for invoices dated before 1st Jan 2021'), title=_('Not Allowed'))
+
invoice_type = 'CRN' if invoice.is_return else 'INV'
invoice_name = invoice.name
@@ -87,56 +117,39 @@ def get_doc_details(invoice):
invoice_date=invoice_date
))
-def get_party_details(address_name, company_address=None, billing_address=None, shipping_address=None):
- d = frappe.get_all('Address', filters={'name': address_name}, fields=['*'])[0]
-
- if ((not d.gstin and not shipping_address)
- or not d.city
- or not d.pincode
- or not d.address_title
- or not d.address_line1
- or not d.gst_state_number):
+def validate_address_fields(address, is_shipping_address):
+ if ((not address.gstin and not is_shipping_address)
+ or not address.city
+ or not address.pincode
+ or not address.address_title
+ or not address.address_line1
+ or not address.gst_state_number):
frappe.throw(
- msg=_('Address lines, city, pincode, gstin is mandatory for address {}. Please set them and try again.').format(
- get_link_to_form('Address', address_name)
- ),
+ msg=_('Address Lines, City, Pincode, GSTIN are mandatory for address {}. Please set them and try again.').format(address.name),
title=_('Missing Address Fields')
)
- if d.gst_state_number == 97:
+def get_party_details(address_name, is_shipping_address=False):
+ addr = frappe.get_doc('Address', address_name)
+
+ validate_address_fields(addr, is_shipping_address)
+
+ if addr.gst_state_number == 97:
# according to einvoice standard
- pincode = 999999
+ addr.pincode = 999999
party_address_details = frappe._dict(dict(
- legal_name=sanitize_for_json(d.address_title),
- location=sanitize_for_json(d.city),
- pincode=d.pincode,
- state_code=d.gst_state_number,
- address_line1=sanitize_for_json(d.address_line1),
- address_line2=sanitize_for_json(d.address_line2)
+ legal_name=sanitize_for_json(addr.address_title),
+ location=sanitize_for_json(addr.city),
+ pincode=addr.pincode, gstin=addr.gstin,
+ state_code=addr.gst_state_number,
+ address_line1=sanitize_for_json(addr.address_line1),
+ address_line2=sanitize_for_json(addr.address_line2)
))
- if d.gstin:
- party_address_details.gstin = d.gstin
+
return party_address_details
-def get_gstin_details(gstin):
- if not hasattr(frappe.local, 'gstin_cache'):
- frappe.local.gstin_cache = {}
-
- key = gstin
- details = frappe.local.gstin_cache.get(key)
- if details:
- return details
-
- details = frappe.cache().hget('gstin_cache', key)
- if details:
- frappe.local.gstin_cache[key] = details
- return details
-
- if not details:
- return GSPConnector.get_gstin_details(gstin)
-
def get_overseas_address_details(address_name):
address_title, address_line1, address_line2, city = frappe.db.get_value(
'Address', address_name, ['address_title', 'address_line1', 'address_line2', 'city']
@@ -212,7 +225,7 @@ def update_item_taxes(invoice, item):
is_applicable = t.tax_amount and t.account_head in gst_accounts_list
if is_applicable:
# this contains item wise tax rate & tax amount (incl. discount)
- item_tax_detail = json.loads(t.item_wise_tax_detail).get(item.item_code)
+ item_tax_detail = json.loads(t.item_wise_tax_detail).get(item.item_code or item.item_name)
item_tax_rate = item_tax_detail[0]
# item tax amount excluding discount amount
@@ -230,6 +243,9 @@ def update_item_taxes(invoice, item):
if t.account_head in gst_accounts[f'{tax_type}_account']:
item.tax_rate += item_tax_rate
item[f'{tax_type}_amount'] += abs(item_tax_amount)
+ else:
+ # TODO: other charges per item
+ pass
return item
@@ -309,6 +325,10 @@ def get_payment_details(invoice):
))
def get_return_doc_reference(invoice):
+ if not invoice.return_against:
+ frappe.throw(_('For generating IRN, reference to the original invoice is mandatory for a credit note. Please set {} field to generate e-invoice.')
+ .format(frappe.bold('Return Against')), title=_('Missing Field'))
+
invoice_date = frappe.db.get_value('Sales Invoice', invoice.return_against, 'posting_date')
return frappe._dict(dict(
invoice_name=invoice.return_against, invoice_date=format_date(invoice_date, 'dd/mm/yyyy')
@@ -316,7 +336,11 @@ def get_return_doc_reference(invoice):
def get_eway_bill_details(invoice):
if invoice.is_return:
- frappe.throw(_('E-Way Bill cannot be generated for Credit Notes & Debit Notes'), title=_('E Invoice Validation Failed'))
+ frappe.throw(_('E-Way Bill cannot be generated for Credit Notes & Debit Notes. Please clear fields in the Transporter Section of the invoice.'),
+ title=_('Invalid Fields'))
+
+ if not invoice.distance:
+ frappe.throw(_('Distance is mandatory for generating e-way bill for an e-invoice.'), title=_('Missing Field'))
mode_of_transport = { '': '', 'Road': '1', 'Air': '2', 'Rail': '3', 'Ship': '4' }
vehicle_type = { 'Regular': 'R', 'Over Dimensional Cargo (ODC)': 'O' }
@@ -334,9 +358,15 @@ def get_eway_bill_details(invoice):
def validate_mandatory_fields(invoice):
if not invoice.company_address:
- frappe.throw(_('Company Address is mandatory to fetch company GSTIN details.'), title=_('Missing Fields'))
+ frappe.throw(
+ _('Company Address is mandatory to fetch company GSTIN details. Please set Company Address and try again.'),
+ title=_('Missing Fields')
+ )
if not invoice.customer_address:
- frappe.throw(_('Customer Address is mandatory to fetch customer GSTIN details.'), title=_('Missing Fields'))
+ frappe.throw(
+ _('Customer Address is mandatory to fetch customer GSTIN details. Please set Company Address and try again.'),
+ title=_('Missing Fields')
+ )
if not frappe.db.get_value('Address', invoice.company_address, 'gstin'):
frappe.throw(
_('GSTIN is mandatory to fetch company GSTIN details. Please enter GSTIN in selected company address.'),
@@ -348,6 +378,39 @@ def validate_mandatory_fields(invoice):
title=_('Missing Fields')
)
+def validate_totals(einvoice):
+ item_list = einvoice['ItemList']
+ value_details = einvoice['ValDtls']
+
+ total_item_ass_value = 0
+ total_item_cgst_value = 0
+ total_item_sgst_value = 0
+ total_item_igst_value = 0
+ total_item_value = 0
+ for item in item_list:
+ total_item_ass_value += flt(item['AssAmt'])
+ total_item_cgst_value += flt(item['CgstAmt'])
+ total_item_sgst_value += flt(item['SgstAmt'])
+ total_item_igst_value += flt(item['IgstAmt'])
+ total_item_value += flt(item['TotItemVal'])
+
+ if abs(flt(item['AssAmt']) * flt(item['GstRt']) / 100) - (flt(item['CgstAmt']) + flt(item['SgstAmt']) + flt(item['IgstAmt'])) > 1:
+ frappe.throw(_('Row #{}: GST rate is invalid. Please remove tax rows with zero tax amount from taxes table.').format(item.idx))
+
+ if abs(flt(value_details['AssVal']) - total_item_ass_value) > 1:
+ frappe.throw(_('Total Taxable Value of the items is not equal to the Invoice Net Total. Please check item taxes / discounts for any correction.'))
+
+ if abs(flt(value_details['TotInvVal']) + flt(value_details['Discount']) - total_item_value) > 1:
+ frappe.throw(_('Total Value of the items is not equal to the Invoice Grand Total. Please check item taxes / discounts for any correction.'))
+
+ calculated_invoice_value = \
+ flt(value_details['AssVal']) + flt(value_details['CgstVal']) \
+ + flt(value_details['SgstVal']) + flt(value_details['IgstVal']) \
+ + flt(value_details['OthChrg']) - flt(value_details['Discount'])
+
+ if abs(flt(value_details['TotInvVal']) - calculated_invoice_value) > 1:
+ frappe.throw(_('Total Item Value + Taxes - Discount is not equal to the Invoice Grand Total. Please check taxes / discounts for any correction.'))
+
def make_einvoice(invoice):
validate_mandatory_fields(invoice)
@@ -357,12 +420,12 @@ def make_einvoice(invoice):
item_list = get_item_list(invoice)
doc_details = get_doc_details(invoice)
invoice_value_details = get_invoice_value_details(invoice)
- seller_details = get_party_details(invoice.company_address, company_address=1)
+ seller_details = get_party_details(invoice.company_address)
if invoice.gst_category == 'Overseas':
buyer_details = get_overseas_address_details(invoice.customer_address)
else:
- buyer_details = get_party_details(invoice.customer_address, billing_address=1)
+ buyer_details = get_party_details(invoice.customer_address)
place_of_supply = get_place_of_supply(invoice, invoice.doctype)
if place_of_supply:
place_of_supply = place_of_supply.split('-')[0]
@@ -370,20 +433,23 @@ def make_einvoice(invoice):
place_of_supply = sanitize_for_json(invoice.billing_address_gstin)[:2]
buyer_details.update(dict(place_of_supply=place_of_supply))
+ seller_details.update(dict(legal_name=invoice.company))
+ buyer_details.update(dict(legal_name=invoice.customer_name or invoice.customer))
+
shipping_details = payment_details = prev_doc_details = eway_bill_details = frappe._dict({})
if invoice.shipping_address_name and invoice.customer_address != invoice.shipping_address_name:
if invoice.gst_category == 'Overseas':
shipping_details = get_overseas_address_details(invoice.shipping_address_name)
else:
- shipping_details = get_party_details(invoice.shipping_address_name, shipping_address=1)
+ shipping_details = get_party_details(invoice.shipping_address_name, is_shipping_address=True)
if invoice.is_pos and invoice.base_paid_amount:
payment_details = get_payment_details(invoice)
- if invoice.is_return and invoice.return_against:
+ if invoice.is_return:
prev_doc_details = get_return_doc_reference(invoice)
- if invoice.transporter:
+ if invoice.transporter and flt(invoice.distance) and not invoice.is_return:
eway_bill_details = get_eway_bill_details(invoice)
# not yet implemented
@@ -396,18 +462,70 @@ def make_einvoice(invoice):
period_details=period_details, prev_doc_details=prev_doc_details,
export_details=export_details, eway_bill_details=eway_bill_details
)
- einvoice = safe_json_load(einvoice)
- validations = json.loads(read_json('einv_validation'))
- errors = validate_einvoice(validations, einvoice)
- if errors:
- message = "\n".join([
- "E Invoice: ", json.dumps(einvoice, indent=4),
- "-" * 50,
- "Errors: ", json.dumps(errors, indent=4)
- ])
- frappe.log_error(title="E Invoice Validation Failed", message=message)
- frappe.throw(errors, title=_('E Invoice Validation Failed'), as_list=1)
+ try:
+ einvoice = safe_json_load(einvoice)
+ einvoice = santize_einvoice_fields(einvoice)
+ validate_totals(einvoice)
+
+ except Exception:
+ log_error(einvoice)
+ link_to_error_list = 'Error Log'
+ frappe.throw(
+ _('An error occurred while creating e-invoice for {}. Please check {} for more information.').format(
+ invoice.name, link_to_error_list),
+ title=_('E Invoice Creation Failed')
+ )
+
+ return einvoice
+
+def log_error(data=None):
+ if not isinstance(data, dict):
+ data = json.loads(data)
+
+ seperator = "--" * 50
+ err_tb = traceback.format_exc()
+ err_msg = str(sys.exc_info()[1])
+ data = json.dumps(data, indent=4)
+
+ message = "\n".join([
+ "Error", err_msg, seperator,
+ "Data:", data, seperator,
+ "Exception:", err_tb
+ ])
+ frappe.log_error(title=_('E Invoice Request Failed'), message=message)
+
+def santize_einvoice_fields(einvoice):
+ int_fields = ["Pin","Distance","CrDay"]
+ float_fields = ["Qty","FreeQty","UnitPrice","TotAmt","Discount","PreTaxVal","AssAmt","GstRt","IgstAmt","CgstAmt","SgstAmt","CesRt","CesAmt","CesNonAdvlAmt","StateCesRt","StateCesAmt","StateCesNonAdvlAmt","OthChrg","TotItemVal","AssVal","CgstVal","SgstVal","IgstVal","CesVal","StCesVal","Discount","OthChrg","RndOffAmt","TotInvVal","TotInvValFc","PaidAmt","PaymtDue","ExpDuty",]
+ copy = einvoice.copy()
+ for key, value in copy.items():
+ if isinstance(value, list):
+ for idx, d in enumerate(value):
+ santized_dict = santize_einvoice_fields(d)
+ if santized_dict:
+ einvoice[key][idx] = santized_dict
+ else:
+ einvoice[key].pop(idx)
+
+ if not einvoice[key]:
+ einvoice.pop(key, None)
+
+ elif isinstance(value, dict):
+ santized_dict = santize_einvoice_fields(value)
+ if santized_dict:
+ einvoice[key] = santized_dict
+ else:
+ einvoice.pop(key, None)
+
+ elif not value or value == "None":
+ einvoice.pop(key, None)
+
+ elif key in float_fields:
+ einvoice[key] = flt(value, 2)
+
+ elif key in int_fields:
+ einvoice[key] = cint(value)
return einvoice
@@ -423,72 +541,22 @@ def safe_json_load(json_string):
snippet = json_string[start:end]
frappe.throw(_("Error in input data. Please check for any special characters near following input: {}").format(snippet))
-def validate_einvoice(validations, einvoice, errors=None):
- if errors is None:
- errors = []
- for fieldname, field_validation in validations.items():
- value = einvoice.get(fieldname, None)
- if not value or value == "None":
- # remove keys with empty values
- einvoice.pop(fieldname, None)
- continue
-
- value_type = field_validation.get("type").lower()
- if value_type in ['object', 'array']:
- child_validations = field_validation.get('properties')
-
- if isinstance(value, list):
- for d in value:
- validate_einvoice(child_validations, d, errors)
- if not d:
- # remove empty dicts
- einvoice.pop(fieldname, None)
- else:
- validate_einvoice(child_validations, value, errors)
- if not value:
- # remove empty dicts
- einvoice.pop(fieldname, None)
- continue
-
- # convert to int or str
- if value_type == 'string':
- einvoice[fieldname] = str(value)
- elif value_type == 'number':
- is_integer = '.' not in str(field_validation.get('maximum'))
- precision = 3 if '.999' in str(field_validation.get('maximum')) else 2
- einvoice[fieldname] = flt(value, precision) if not is_integer else cint(value)
- value = einvoice[fieldname]
-
- max_length = field_validation.get('maxLength')
- minimum = flt(field_validation.get('minimum'))
- maximum = flt(field_validation.get('maximum'))
- pattern_str = field_validation.get('pattern')
- pattern = re.compile(pattern_str or '')
-
- label = field_validation.get('description') or fieldname
-
- if value_type == 'string' and len(value) > max_length:
- errors.append(_('{} should not exceed {} characters').format(label, max_length))
- if value_type == 'number' and (value > maximum or value < minimum):
- errors.append(_('{} {} should be between {} and {}').format(label, value, minimum, maximum))
- if pattern_str and not pattern.match(value):
- errors.append(field_validation.get('validationMsg'))
-
- return errors
-
-class RequestFailed(Exception): pass
+class RequestFailed(Exception):
+ pass
+class CancellationNotAllowed(Exception):
+ pass
class GSPConnector():
def __init__(self, doctype=None, docname=None):
- self.e_invoice_settings = frappe.get_cached_doc('E Invoice Settings')
- sandbox_mode = self.e_invoice_settings.sandbox_mode
+ self.doctype = doctype
+ self.docname = docname
- self.invoice = frappe.get_cached_doc(doctype, docname) if doctype and docname else None
- self.credentials = self.get_credentials()
+ self.set_invoice()
+ self.set_credentials()
# authenticate url is same for sandbox & live
self.authenticate_url = 'https://gsp.adaequare.com/gsp/authenticate?grant_type=token'
- self.base_url = 'https://gsp.adaequare.com' if not sandbox_mode else 'https://gsp.adaequare.com/test'
+ self.base_url = 'https://gsp.adaequare.com' if not self.e_invoice_settings.sandbox_mode else 'https://gsp.adaequare.com/test'
self.cancel_irn_url = self.base_url + '/enriched/ei/api/invoice/cancel'
self.irn_details_url = self.base_url + '/enriched/ei/api/invoice/irn'
@@ -497,15 +565,26 @@ class GSPConnector():
self.cancel_ewaybill_url = self.base_url + '/enriched/ewb/ewayapi?action=CANEWB'
self.generate_ewaybill_url = self.base_url + '/enriched/ei/api/ewaybill'
- def get_credentials(self):
+ def set_invoice(self):
+ self.invoice = None
+ if self.doctype and self.docname:
+ self.invoice = frappe.get_cached_doc(self.doctype, self.docname)
+
+ def set_credentials(self):
+ self.e_invoice_settings = frappe.get_cached_doc('E Invoice Settings')
+
+ if not self.e_invoice_settings.enable:
+ frappe.throw(_("E-Invoicing is disabled. Please enable it from {} to generate e-invoices.").format(get_link_to_form("E Invoice Settings", "E Invoice Settings")))
+
if self.invoice:
gstin = self.get_seller_gstin()
- if not self.e_invoice_settings.enable:
- frappe.throw(_("E-Invoicing is disabled. Please enable it from {} to generate e-invoices.").format(get_link_to_form("E Invoice Settings", "E Invoice Settings")))
- credentials = next(d for d in self.e_invoice_settings.credentials if d.gstin == gstin)
+ credentials_for_gstin = [d for d in self.e_invoice_settings.credentials if d.gstin == gstin]
+ if credentials_for_gstin:
+ self.credentials = credentials_for_gstin[0]
+ else:
+ frappe.throw(_('Cannot find e-invoicing credentials for selected Company GSTIN. Please check E-Invoice Settings'))
else:
- credentials = self.e_invoice_settings.credentials[0] if self.e_invoice_settings.credentials else None
- return credentials
+ self.credentials = self.e_invoice_settings.credentials[0] if self.e_invoice_settings.credentials else None
def get_seller_gstin(self):
gstin = self.invoice.company_gstin or frappe.db.get_value('Address', self.invoice.company_address, 'gstin')
@@ -556,7 +635,7 @@ class GSPConnector():
self.e_invoice_settings.reload()
except Exception:
- self.log_error(res)
+ log_error(res)
self.raise_error(True)
def get_headers(self):
@@ -578,14 +657,14 @@ class GSPConnector():
if res.get('success'):
return res.get('result')
else:
- self.log_error(res)
+ log_error(res)
raise RequestFailed
except RequestFailed:
self.raise_error()
except Exception:
- self.log_error()
+ log_error()
self.raise_error(True)
@staticmethod
@@ -603,12 +682,13 @@ class GSPConnector():
return details
def generate_irn(self):
- headers = self.get_headers()
- einvoice = make_einvoice(self.invoice)
- data = json.dumps(einvoice, indent=4)
-
+ data = {}
try:
+ headers = self.get_headers()
+ einvoice = make_einvoice(self.invoice)
+ data = json.dumps(einvoice, indent=4)
res = self.make_request('post', self.generate_irn_url, headers, data)
+
if res.get('success'):
self.set_einvoice_data(res.get('result'))
@@ -628,12 +708,36 @@ class GSPConnector():
except RequestFailed:
errors = self.sanitize_error_message(res.get('message'))
+ self.set_failed_status(errors=errors)
self.raise_error(errors=errors)
- except Exception:
- self.log_error(data)
+ except Exception as e:
+ self.set_failed_status(errors=str(e))
+ log_error(data)
self.raise_error(True)
+ @staticmethod
+ def bulk_generate_irn(invoices):
+ gsp_connector = GSPConnector()
+ gsp_connector.doctype = 'Sales Invoice'
+
+ failed = []
+
+ for invoice in invoices:
+ try:
+ gsp_connector.docname = invoice
+ gsp_connector.set_invoice()
+ gsp_connector.set_credentials()
+ gsp_connector.generate_irn()
+
+ except Exception as e:
+ failed.append({
+ 'docname': invoice,
+ 'message': str(e)
+ })
+
+ return failed
+
def get_irn_details(self, irn):
headers = self.get_headers()
@@ -650,21 +754,30 @@ class GSPConnector():
self.raise_error(errors=errors)
except Exception:
- self.log_error()
+ log_error()
self.raise_error(True)
def cancel_irn(self, irn, reason, remark):
- headers = self.get_headers()
- data = json.dumps({
- 'Irn': irn,
- 'Cnlrsn': reason,
- 'Cnlrem': remark
- }, indent=4)
-
+ data, res = {}, {}
try:
+ # validate cancellation
+ if time_diff_in_hours(now_datetime(), self.invoice.ack_date) > 24:
+ frappe.throw(_('E-Invoice cannot be cancelled after 24 hours of IRN generation.'), title=_('Not Allowed'), exc=CancellationNotAllowed)
+ if not irn:
+ frappe.throw(_('IRN not found. You must generate IRN before cancelling.'), title=_('Not Allowed'), exc=CancellationNotAllowed)
+
+ headers = self.get_headers()
+ data = json.dumps({
+ 'Irn': irn,
+ 'Cnlrsn': reason,
+ 'Cnlrem': remark
+ }, indent=4)
+
res = self.make_request('post', self.cancel_irn_url, headers, data)
- if res.get('success'):
+ if res.get('success') or '9999' in res.get('message'):
self.invoice.irn_cancelled = 1
+ self.invoice.irn_cancel_date = res.get('result')['CancelDate'] if res.get('result') else ""
+ self.invoice.einvoice_status = 'Cancelled'
self.invoice.flags.updater_reference = {
'doctype': self.invoice.doctype,
'docname': self.invoice.name,
@@ -677,12 +790,41 @@ class GSPConnector():
except RequestFailed:
errors = self.sanitize_error_message(res.get('message'))
+ self.set_failed_status(errors=errors)
self.raise_error(errors=errors)
- except Exception:
- self.log_error(data)
+ except CancellationNotAllowed as e:
+ self.set_failed_status(errors=str(e))
+ self.raise_error(errors=str(e))
+
+ except Exception as e:
+ self.set_failed_status(errors=str(e))
+ log_error(data)
self.raise_error(True)
+ @staticmethod
+ def bulk_cancel_irn(invoices, reason, remark):
+ gsp_connector = GSPConnector()
+ gsp_connector.doctype = 'Sales Invoice'
+
+ failed = []
+
+ for invoice in invoices:
+ try:
+ gsp_connector.docname = invoice
+ gsp_connector.set_invoice()
+ gsp_connector.set_credentials()
+ irn = gsp_connector.invoice.irn
+ gsp_connector.cancel_irn(irn, reason, remark)
+
+ except Exception as e:
+ failed.append({
+ 'docname': invoice,
+ 'message': str(e)
+ })
+
+ return failed
+
def generate_eway_bill(self, **kwargs):
args = frappe._dict(kwargs)
@@ -721,7 +863,7 @@ class GSPConnector():
self.raise_error(errors=errors)
except Exception:
- self.log_error(data)
+ log_error(data)
self.raise_error(True)
def cancel_eway_bill(self, eway_bill, reason, remark):
@@ -753,7 +895,7 @@ class GSPConnector():
self.raise_error(errors=errors)
except Exception:
- self.log_error(data)
+ log_error(data)
self.raise_error(True)
def sanitize_error_message(self, message):
@@ -768,6 +910,9 @@ class GSPConnector():
]
then we trim down the message by looping over errors
'''
+ if not message:
+ return []
+
errors = re.findall(': [^:]+', message)
for idx, e in enumerate(errors):
# remove colons
@@ -779,22 +924,6 @@ class GSPConnector():
return errors
- def log_error(self, data={}):
- if not isinstance(data, dict):
- data = json.loads(data)
-
- seperator = "--" * 50
- err_tb = traceback.format_exc()
- err_msg = str(sys.exc_info()[1])
- data = json.dumps(data, indent=4)
-
- message = "\n".join([
- "Error", err_msg, seperator,
- "Data:", data, seperator,
- "Exception:", err_tb
- ])
- frappe.log_error(title=_('E Invoice Request Failed'), message=message)
-
def raise_error(self, raise_exception=False, errors=[]):
title = _('E Invoice Request Failed')
if errors:
@@ -817,7 +946,10 @@ class GSPConnector():
self.invoice.ack_no = res.get('AckNo')
self.invoice.ack_date = res.get('AckDt')
self.invoice.signed_einvoice = dec_signed_invoice
+ self.invoice.ack_no = res.get('AckNo')
+ self.invoice.ack_date = res.get('AckDt')
self.invoice.signed_qr_code = res.get('SignedQRCode')
+ self.invoice.einvoice_status = 'Generated'
self.attach_qrcode_image()
@@ -854,6 +986,17 @@ class GSPConnector():
self.invoice.flags.ignore_validate = True
self.invoice.save()
+ def set_failed_status(self, errors=None):
+ frappe.db.rollback()
+ self.invoice.einvoice_status = 'Failed'
+ self.invoice.failure_description = self.get_failure_message(errors) if errors else ""
+ self.update_invoice()
+ frappe.db.commit()
+
+ def get_failure_message(self, errors):
+ if isinstance(errors, list):
+ errors = ', '.join(errors)
+ return errors
def sanitize_for_json(string):
"""Escape JSON specific characters from a string."""
@@ -883,5 +1026,114 @@ def generate_eway_bill(doctype, docname, **kwargs):
@frappe.whitelist()
def cancel_eway_bill(doctype, docname, eway_bill, reason, remark):
- gsp_connector = GSPConnector(doctype, docname)
- gsp_connector.cancel_eway_bill(eway_bill, reason, remark)
+ # TODO: uncomment when eway_bill api from Adequare is enabled
+ # gsp_connector = GSPConnector(doctype, docname)
+ # gsp_connector.cancel_eway_bill(eway_bill, reason, remark)
+
+ # update cancelled status only, to be able to cancel irn next
+ frappe.db.set_value(doctype, docname, 'eway_bill_cancelled', 1)
+
+@frappe.whitelist()
+def generate_einvoices(docnames):
+ docnames = json.loads(docnames) or []
+
+ if len(docnames) < 10:
+ failures = GSPConnector.bulk_generate_irn(docnames)
+ frappe.local.message_log = []
+
+ if failures:
+ show_bulk_action_failure_message(failures)
+
+ success = len(docnames) - len(failures)
+ frappe.msgprint(
+ _('{} e-invoices generated successfully').format(success),
+ title=_('Bulk E-Invoice Generation Complete')
+ )
+
+ else:
+ enqueue_bulk_action(schedule_bulk_generate_irn, docnames=docnames)
+
+def schedule_bulk_generate_irn(docnames):
+ failures = GSPConnector.bulk_generate_irn(docnames)
+ frappe.local.message_log = []
+
+ frappe.publish_realtime("bulk_einvoice_generation_complete", {
+ "user": frappe.session.user,
+ "failures": failures,
+ "invoices": docnames
+ })
+
+def show_bulk_action_failure_message(failures):
+ for doc in failures:
+ docname = '{0}'.format(doc.get('docname'))
+ message = doc.get('message').replace("'", '"')
+ if message[0] == '[':
+ errors = json.loads(message)
+ error_list = ''.join(['{}'.format(err) for err in errors])
+ message = '''{} has following errors:
+ '''.format(docname, error_list)
+ else:
+ message = '{} - {}'.format(docname, message)
+
+ frappe.msgprint(
+ message,
+ title=_('Bulk E-Invoice Generation Complete'),
+ indicator='red'
+ )
+
+@frappe.whitelist()
+def cancel_irns(docnames, reason, remark):
+ docnames = json.loads(docnames) or []
+
+ if len(docnames) < 10:
+ failures = GSPConnector.bulk_cancel_irn(docnames, reason, remark)
+ frappe.local.message_log = []
+
+ if failures:
+ show_bulk_action_failure_message(failures)
+
+ success = len(docnames) - len(failures)
+ frappe.msgprint(
+ _('{} e-invoices cancelled successfully').format(success),
+ title=_('Bulk E-Invoice Cancellation Complete')
+ )
+ else:
+ enqueue_bulk_action(schedule_bulk_cancel_irn, docnames=docnames, reason=reason, remark=remark)
+
+def schedule_bulk_cancel_irn(docnames, reason, remark):
+ failures = GSPConnector.bulk_cancel_irn(docnames, reason, remark)
+ frappe.local.message_log = []
+
+ frappe.publish_realtime("bulk_einvoice_cancellation_complete", {
+ "user": frappe.session.user,
+ "failures": failures,
+ "invoices": docnames
+ })
+
+def enqueue_bulk_action(job, **kwargs):
+ check_scheduler_status()
+
+ enqueue(
+ job,
+ **kwargs,
+ queue="long",
+ timeout=10000,
+ event="processing_bulk_einvoice_action",
+ now=frappe.conf.developer_mode or frappe.flags.in_test,
+ )
+
+ if job == schedule_bulk_generate_irn:
+ msg = _('E-Invoices will be generated in a background process.')
+ else:
+ msg = _('E-Invoices will be cancelled in a background process.')
+
+ frappe.msgprint(msg, alert=1)
+
+def check_scheduler_status():
+ if is_scheduler_inactive() and not frappe.flags.in_test:
+ frappe.throw(_("Scheduler is inactive. Cannot enqueue job."), title=_("Scheduler Inactive"))
+
+def job_already_enqueued(job_name):
+ enqueued_jobs = [d.get("job_name") for d in get_info()]
+ if job_name in enqueued_jobs:
+ return True
\ No newline at end of file
diff --git a/erpnext/regional/india/setup.py b/erpnext/regional/india/setup.py
index bf0712f0a5..ec58fd2f33 100644
--- a/erpnext/regional/india/setup.py
+++ b/erpnext/regional/india/setup.py
@@ -51,7 +51,7 @@ def create_hsn_codes(data, code_field):
def add_custom_roles_for_reports():
for report_name in ('GST Sales Register', 'GST Purchase Register',
- 'GST Itemised Sales Register', 'GST Itemised Purchase Register', 'Eway Bill'):
+ 'GST Itemised Sales Register', 'GST Itemised Purchase Register', 'Eway Bill', 'E-Invoice Summary'):
if not frappe.db.get_value('Custom Role', dict(report=report_name)):
frappe.get_doc(dict(
@@ -418,21 +418,37 @@ def make_custom_fields(update=True):
dict(fieldname='irn', label='IRN', fieldtype='Data', read_only=1, insert_after='customer', no_copy=1, print_hide=1,
depends_on='eval:in_list(["Registered Regular", "SEZ", "Overseas", "Deemed Export"], doc.gst_category) && doc.irn_cancelled === 0'),
- dict(fieldname='ack_no', label='Ack. No.', fieldtype='Data', read_only=1, hidden=1, insert_after='irn', no_copy=1, print_hide=1),
-
- dict(fieldname='ack_date', label='Ack. Date', fieldtype='Data', read_only=1, hidden=1, insert_after='ack_no', no_copy=1, print_hide=1),
-
dict(fieldname='irn_cancelled', label='IRN Cancelled', fieldtype='Check', no_copy=1, print_hide=1,
depends_on='eval:(doc.irn_cancelled === 1)', read_only=1, allow_on_submit=1, insert_after='customer'),
dict(fieldname='eway_bill_cancelled', label='E-Way Bill Cancelled', fieldtype='Check', no_copy=1, print_hide=1,
depends_on='eval:(doc.eway_bill_cancelled === 1)', read_only=1, allow_on_submit=1, insert_after='customer'),
- dict(fieldname='signed_einvoice', fieldtype='Code', options='JSON', hidden=1, no_copy=1, print_hide=1, read_only=1),
+ dict(fieldname='einvoice_section', label='E-Invoice Fields', fieldtype='Section Break', insert_after='gst_vehicle_type',
+ print_hide=1, hidden=1),
+
+ dict(fieldname='ack_no', label='Ack. No.', fieldtype='Data', read_only=1, hidden=1, insert_after='einvoice_section',
+ no_copy=1, print_hide=1),
+
+ dict(fieldname='ack_date', label='Ack. Date', fieldtype='Data', read_only=1, hidden=1, insert_after='ack_no', no_copy=1, print_hide=1),
- dict(fieldname='signed_qr_code', fieldtype='Code', options='JSON', hidden=1, no_copy=1, print_hide=1, read_only=1),
+ dict(fieldname='irn_cancel_date', label='Cancel Date', fieldtype='Data', read_only=1, hidden=1, insert_after='ack_date',
+ no_copy=1, print_hide=1),
- dict(fieldname='qrcode_image', label='QRCode', fieldtype='Attach Image', hidden=1, no_copy=1, print_hide=1, read_only=1)
+ dict(fieldname='signed_einvoice', label='Signed E-Invoice', fieldtype='Code', options='JSON', hidden=1, insert_after='irn_cancel_date',
+ no_copy=1, print_hide=1, read_only=1),
+
+ dict(fieldname='signed_qr_code', label='Signed QRCode', fieldtype='Code', options='JSON', hidden=1, insert_after='signed_einvoice',
+ no_copy=1, print_hide=1, read_only=1),
+
+ dict(fieldname='qrcode_image', label='QRCode', fieldtype='Attach Image', hidden=1, insert_after='signed_qr_code',
+ no_copy=1, print_hide=1, read_only=1),
+
+ dict(fieldname='einvoice_status', label='E-Invoice Status', fieldtype='Select', insert_after='qrcode_image',
+ options='\nPending\nGenerated\nCancelled\nFailed', default=None, hidden=1, no_copy=1, print_hide=1, read_only=1),
+
+ dict(fieldname='failure_description', label='E-Invoice Failure Description', fieldtype='Code', options='JSON',
+ hidden=1, insert_after='einvoice_status', no_copy=1, print_hide=1, read_only=1)
]
custom_fields = {
diff --git a/erpnext/regional/india/utils.py b/erpnext/regional/india/utils.py
index 082a32f3ff..7709ddf42c 100644
--- a/erpnext/regional/india/utils.py
+++ b/erpnext/regional/india/utils.py
@@ -41,24 +41,25 @@ def validate_gstin_for_india(doc, method):
return
if len(doc.gstin) != 15:
- frappe.throw(_("Invalid GSTIN! A GSTIN must have 15 characters."))
+ frappe.throw(_("A GSTIN must have 15 characters."), title=_("Invalid GSTIN"))
if gst_category and gst_category == 'UIN Holders':
if not GSTIN_UIN_FORMAT.match(doc.gstin):
- frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"))
+ frappe.throw(_("The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"),
+ title=_("Invalid GSTIN"))
else:
if not GSTIN_FORMAT.match(doc.gstin):
- frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the format of GSTIN."))
+ frappe.throw(_("The input you've entered doesn't match the format of GSTIN."), title=_("Invalid GSTIN"))
validate_gstin_check_digit(doc.gstin)
set_gst_state_and_state_number(doc)
if not doc.gst_state:
- frappe.throw(_("Please Enter GST state"))
+ frappe.throw(_("Please enter GST state"), title=_("Invalid State"))
if doc.gst_state_number != doc.gstin[:2]:
- frappe.throw(_("Invalid GSTIN! First 2 digits of GSTIN should match with State number {0}.")
- .format(doc.gst_state_number))
+ frappe.throw(_("First 2 digits of GSTIN should match with State number {0}.")
+ .format(doc.gst_state_number), title=_("Invalid GSTIN"))
def validate_pan_for_india(doc, method):
if doc.get('country') != 'India' or not doc.pan:
diff --git a/erpnext/regional/report/e_invoice_summary/__init__.py b/erpnext/regional/report/e_invoice_summary/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/erpnext/regional/report/e_invoice_summary/e_invoice_summary.js b/erpnext/regional/report/e_invoice_summary/e_invoice_summary.js
new file mode 100644
index 0000000000..4713217d83
--- /dev/null
+++ b/erpnext/regional/report/e_invoice_summary/e_invoice_summary.js
@@ -0,0 +1,55 @@
+// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+/* eslint-disable */
+
+frappe.query_reports["E-Invoice Summary"] = {
+ "filters": [
+ {
+ "fieldtype": "Link",
+ "options": "Company",
+ "reqd": 1,
+ "fieldname": "company",
+ "label": __("Company"),
+ "default": frappe.defaults.get_user_default("Company"),
+ },
+ {
+ "fieldtype": "Link",
+ "options": "Customer",
+ "fieldname": "customer",
+ "label": __("Customer")
+ },
+ {
+ "fieldtype": "Date",
+ "reqd": 1,
+ "fieldname": "from_date",
+ "label": __("From Date"),
+ "default": frappe.datetime.add_months(frappe.datetime.get_today(), -1),
+ },
+ {
+ "fieldtype": "Date",
+ "reqd": 1,
+ "fieldname": "to_date",
+ "label": __("To Date"),
+ "default": frappe.datetime.get_today(),
+ },
+ {
+ "fieldtype": "Select",
+ "fieldname": "status",
+ "label": __("Status"),
+ "options": "\nPending\nGenerated\nCancelled\nFailed"
+ }
+ ],
+
+ "formatter": function (value, row, column, data, default_formatter) {
+ value = default_formatter(value, row, column, data);
+
+ if (column.fieldname == "einvoice_status" && value) {
+ if (value == 'Pending') value = `${value}`;
+ else if (value == 'Generated') value = `${value}`;
+ else if (value == 'Cancelled') value = `${value}`;
+ else if (value == 'Failed') value = `${value}`;
+ }
+
+ return value;
+ }
+};
diff --git a/erpnext/regional/report/e_invoice_summary/e_invoice_summary.json b/erpnext/regional/report/e_invoice_summary/e_invoice_summary.json
new file mode 100644
index 0000000000..4deb073a53
--- /dev/null
+++ b/erpnext/regional/report/e_invoice_summary/e_invoice_summary.json
@@ -0,0 +1,28 @@
+{
+ "add_total_row": 0,
+ "columns": [],
+ "creation": "2021-03-12 11:23:37.312294",
+ "disable_prepared_report": 0,
+ "disabled": 0,
+ "docstatus": 0,
+ "doctype": "Report",
+ "filters": [],
+ "idx": 0,
+ "is_standard": "Yes",
+ "json": "{}",
+ "letter_head": "Logo",
+ "modified": "2021-03-12 12:36:48.689413",
+ "modified_by": "Administrator",
+ "module": "Regional",
+ "name": "E-Invoice Summary",
+ "owner": "Administrator",
+ "prepared_report": 0,
+ "ref_doctype": "Sales Invoice",
+ "report_name": "E-Invoice Summary",
+ "report_type": "Script Report",
+ "roles": [
+ {
+ "role": "Administrator"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/erpnext/regional/report/e_invoice_summary/e_invoice_summary.py b/erpnext/regional/report/e_invoice_summary/e_invoice_summary.py
new file mode 100644
index 0000000000..47acf291a3
--- /dev/null
+++ b/erpnext/regional/report/e_invoice_summary/e_invoice_summary.py
@@ -0,0 +1,106 @@
+# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+from __future__ import unicode_literals
+import frappe
+from frappe import _
+
+def execute(filters=None):
+ validate_filters(filters)
+
+ columns = get_columns()
+ data = get_data(filters)
+
+ return columns, data
+
+def validate_filters(filters={}):
+ filters = frappe._dict(filters)
+
+ if not filters.company:
+ frappe.throw(_('{} is mandatory for generating E-Invoice Summary Report').format(_('Company')), title=_('Invalid Filter'))
+ if filters.company:
+ # validate if company has e-invoicing enabled
+ pass
+ if not filters.from_date or not filters.to_date:
+ frappe.throw(_('From Date & To Date is mandatory for generating E-Invoice Summary Report'), title=_('Invalid Filter'))
+ if filters.from_date > filters.to_date:
+ frappe.throw(_('From Date must be before To Date'), title=_('Invalid Filter'))
+
+def get_data(filters={}):
+ query_filters = {
+ 'posting_date': ['between', [filters.from_date, filters.to_date]],
+ 'einvoice_status': ['is', 'set'],
+ 'company': filters.company
+ }
+ if filters.customer:
+ query_filters['customer'] = filters.customer
+ if filters.status:
+ query_filters['einvoice_status'] = filters.status
+
+ data = frappe.get_all(
+ 'Sales Invoice',
+ filters=query_filters,
+ fields=[d.get('fieldname') for d in get_columns()]
+ )
+
+ return data
+
+def get_columns():
+ return [
+ {
+ "fieldtype": "Date",
+ "fieldname": "posting_date",
+ "label": _("Posting Date"),
+ "width": 0
+ },
+ {
+ "fieldtype": "Link",
+ "fieldname": "name",
+ "label": _("Sales Invoice"),
+ "options": "Sales Invoice",
+ "width": 140
+ },
+ {
+ "fieldtype": "Data",
+ "fieldname": "einvoice_status",
+ "label": _("Status"),
+ "width": 100
+ },
+ {
+ "fieldtype": "Link",
+ "fieldname": "customer",
+ "options": "Customer",
+ "label": _("Customer")
+ },
+ {
+ "fieldtype": "Check",
+ "fieldname": "is_return",
+ "label": _("Is Return"),
+ "width": 85
+ },
+ {
+ "fieldtype": "Data",
+ "fieldname": "ack_no",
+ "label": "Ack. No.",
+ "width": 145
+ },
+ {
+ "fieldtype": "Data",
+ "fieldname": "ack_date",
+ "label": "Ack. Date",
+ "width": 165
+ },
+ {
+ "fieldtype": "Data",
+ "fieldname": "irn",
+ "label": _("IRN No."),
+ "width": 250
+ },
+ {
+ "fieldtype": "Currency",
+ "options": "Company:company:default_currency",
+ "fieldname": "base_grand_total",
+ "label": _("Grand Total"),
+ "width": 120
+ }
+ ]
\ No newline at end of file
From a19c98255f89d40d6defdf356a72c7e3853a96d8 Mon Sep 17 00:00:00 2001
From: Saqib
Date: Mon, 12 Apr 2021 19:02:28 +0530
Subject: [PATCH 201/207] fix: patch condition (#25301)
---
erpnext/patches/v12_0/add_company_link_to_einvoice_settings.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/patches/v12_0/add_company_link_to_einvoice_settings.py b/erpnext/patches/v12_0/add_company_link_to_einvoice_settings.py
index fe284e814c..3b560fd43a 100644
--- a/erpnext/patches/v12_0/add_company_link_to_einvoice_settings.py
+++ b/erpnext/patches/v12_0/add_company_link_to_einvoice_settings.py
@@ -12,5 +12,5 @@ def execute():
select dl.link_name from `tabAddress` a, `tabDynamic Link` dl
where a.gstin = %s and dl.parent = a.name and dl.link_doctype = 'Company'
""", (creds.get('gstin')))
- if company_name[0]:
+ if company_name and len(company_name) == 1:
frappe.db.set_value('E Invoice User', creds.get('name'), 'company', company_name[0][0])
\ No newline at end of file
From c65751d97f262637535251225bfca089a2390f10 Mon Sep 17 00:00:00 2001
From: Ankush Menat
Date: Mon, 12 Apr 2021 19:45:34 +0530
Subject: [PATCH 202/207] test: ignore floating point errors in test_bom
---
erpnext/manufacturing/doctype/bom/test_bom.py | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/erpnext/manufacturing/doctype/bom/test_bom.py b/erpnext/manufacturing/doctype/bom/test_bom.py
index cd61d2a31d..7108338dab 100644
--- a/erpnext/manufacturing/doctype/bom/test_bom.py
+++ b/erpnext/manufacturing/doctype/bom/test_bom.py
@@ -93,15 +93,15 @@ class TestBOM(unittest.TestCase):
base_raw_material_cost = raw_material_cost * flt(bom.conversion_rate, bom.precision("conversion_rate"))
base_op_cost = op_cost * flt(bom.conversion_rate, bom.precision("conversion_rate"))
- # test amounts in selected currency
- self.assertEqual(bom.operating_cost, op_cost)
- self.assertEqual(bom.raw_material_cost, raw_material_cost)
- self.assertEqual(bom.total_cost, raw_material_cost + op_cost)
+ # test amounts in selected currency, almostEqual checks for 7 digits by default
+ self.assertAlmostEqual(bom.operating_cost, op_cost)
+ self.assertAlmostEqual(bom.raw_material_cost, raw_material_cost)
+ self.assertAlmostEqual(bom.total_cost, raw_material_cost + op_cost)
# test amounts in selected currency
- self.assertEqual(bom.base_operating_cost, base_op_cost)
- self.assertEqual(bom.base_raw_material_cost, base_raw_material_cost)
- self.assertEqual(bom.base_total_cost, base_raw_material_cost + base_op_cost)
+ self.assertAlmostEqual(bom.base_operating_cost, base_op_cost)
+ self.assertAlmostEqual(bom.base_raw_material_cost, base_raw_material_cost)
+ self.assertAlmostEqual(bom.base_total_cost, base_raw_material_cost + base_op_cost)
def test_bom_cost_multi_uom_multi_currency_based_on_price_list(self):
frappe.db.set_value("Price List", "_Test Price List", "price_not_uom_dependent", 1)
From 20140425c820b0dd861116f87f456dced07f2c2d Mon Sep 17 00:00:00 2001
From: Abdullah Abouzekry <1107178+abdouz@users.noreply.github.com>
Date: Tue, 13 Apr 2021 08:06:39 +0200
Subject: [PATCH 203/207] fix: sales order not saving due type mismatch in
promo scheme (#24748) (#25222)
---
erpnext/accounts/doctype/pricing_rule/utils.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/accounts/doctype/pricing_rule/utils.py b/erpnext/accounts/doctype/pricing_rule/utils.py
index c676abd4c6..b91a7a5bd2 100644
--- a/erpnext/accounts/doctype/pricing_rule/utils.py
+++ b/erpnext/accounts/doctype/pricing_rule/utils.py
@@ -471,7 +471,7 @@ def apply_pricing_rule_on_transaction(doc):
if not d.get(pr_field): continue
- if d.validate_applied_rule and doc.get(field) < d.get(pr_field):
+ if d.validate_applied_rule and doc.get(field) is not None and doc.get(field) < d.get(pr_field):
frappe.msgprint(_("User has not applied rule on the invoice {0}")
.format(doc.name))
else:
From 65f25c27b340f9d9e370e882e474ff656d8c8848 Mon Sep 17 00:00:00 2001
From: Rushabh Mehta
Date: Tue, 13 Apr 2021 11:58:16 +0530
Subject: [PATCH 204/207] fix(minor): fix dynamically changing grid properties
---
erpnext/accounts/doctype/bank/bank.js | 5 +-
.../doctype/journal_entry/journal_entry.js | 38 ++++------
.../payment_reconciliation.js | 5 +-
.../doctype/pos_settings/pos_settings.js | 7 +-
.../purchase_invoice/purchase_invoice.js | 9 ---
.../doctype/sales_invoice/sales_invoice.js | 3 -
.../patient_assessment/patient_assessment.js | 8 ++-
.../doctype/therapy_plan/therapy_plan.js | 10 ++-
.../manufacturing/doctype/routing/routing.js | 9 ++-
.../salary_structure/salary_structure.js | 11 ++-
.../products_settings/products_settings.js | 10 +--
erpnext/public/js/controllers/accounts.js | 71 -------------------
.../setup/doctype/item_group/item_group.js | 12 ++--
.../item_variant_settings.js | 5 +-
.../doctype/packing_slip/packing_slip.js | 15 ----
.../purchase_receipt/purchase_receipt.js | 7 --
.../service_level_agreement.js | 6 +-
17 files changed, 69 insertions(+), 162 deletions(-)
diff --git a/erpnext/accounts/doctype/bank/bank.js b/erpnext/accounts/doctype/bank/bank.js
index 49b2b186c4..8c0abc2447 100644
--- a/erpnext/accounts/doctype/bank/bank.js
+++ b/erpnext/accounts/doctype/bank/bank.js
@@ -42,10 +42,7 @@ let add_fields_to_mapping_table = function (frm) {
});
});
- frappe.meta.get_docfield("Bank Transaction Mapping", "bank_transaction_field",
- frm.doc.name).options = options;
-
- frm.fields_dict.bank_transaction_mapping.grid.refresh();
+ frm.fields_dict.bank_transaction_mapping.grid.update_docfield_property('frm.fields_dict.bank_transaction_mapping.grid', 'options', options);
};
erpnext.integrations.refreshPlaidLink = class refreshPlaidLink {
diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.js b/erpnext/accounts/doctype/journal_entry/journal_entry.js
index 37b03f3f0e..411bd3d6fc 100644
--- a/erpnext/accounts/doctype/journal_entry/journal_entry.js
+++ b/erpnext/accounts/doctype/journal_entry/journal_entry.js
@@ -327,18 +327,16 @@ erpnext.accounts.JournalEntry = frappe.ui.form.Controller.extend({
},
setup_balance_formatter: function() {
- var me = this;
- $.each(["balance", "party_balance"], function(i, field) {
- var df = frappe.meta.get_docfield("Journal Entry Account", field, me.frm.doc.name);
- df.formatter = function(value, df, options, doc) {
- var currency = frappe.meta.get_field_currency(df, doc);
- var dr_or_cr = value ? ('') : "";
- return ""
- + ((value==null || value==="") ? "" : format_currency(Math.abs(value), currency))
- + " " + dr_or_cr
- + " ";
- }
- })
+ const formatter = function(value, df, options, doc) {
+ var currency = frappe.meta.get_field_currency(df, doc);
+ var dr_or_cr = value ? ('') : "";
+ return ""
+ + ((value==null || value==="") ? "" : format_currency(Math.abs(value), currency))
+ + " " + dr_or_cr
+ + " ";
+ }
+ this.frm.fields_dict.accounts.grid.update_docfield_property('balance', 'formatter', formatter);
+ this.frm.fields_dict.accounts.grid.update_docfield_property('party_balance', 'formatter', formatter);
},
reference_name: function(doc, cdt, cdn) {
@@ -431,15 +429,6 @@ cur_frm.cscript.validate = function(doc,cdt,cdn) {
cur_frm.cscript.update_totals(doc);
}
-cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){
- if(doc.select_print_heading){
- // print heading
- cur_frm.pformat.print_heading = doc.select_print_heading;
- }
- else
- cur_frm.pformat.print_heading = __("Journal Entry");
-}
-
frappe.ui.form.on("Journal Entry Account", {
party: function(frm, cdt, cdn) {
var d = frappe.get_doc(cdt, cdn);
@@ -511,8 +500,11 @@ $.extend(erpnext.journal_entry, {
};
$.each(field_label_map, function (fieldname, label) {
- var df = frappe.meta.get_docfield("Journal Entry Account", fieldname, frm.doc.name);
- df.label = frm.doc.multi_currency ? (label + " in Account Currency") : label;
+ frm.fields_dict.accounts.grid.update_docfield_property(
+ fieldname,
+ 'label',
+ frm.doc.multi_currency ? (label + " in Account Currency") : label
+ );
})
},
diff --git a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.js b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.js
index 6b07197ec1..b693863fb2 100644
--- a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.js
+++ b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.js
@@ -234,8 +234,9 @@ erpnext.accounts.PaymentReconciliationController = frappe.ui.form.Controller.ext
});
if (invoices) {
- frappe.meta.get_docfield("Payment Reconciliation Payment", "invoice_number",
- me.frm.doc.name).options = "\n" + invoices.join("\n");
+ this.frm.fields_dict.payment.grid.update_docfield_property(
+ 'invoice_number', options, "\n" + invoices.join("\n")
+ )
$.each(me.frm.doc.payments || [], function(i, p) {
if(!in_list(invoices, cstr(p.invoice_number))) p.invoice_number = null;
diff --git a/erpnext/accounts/doctype/pos_settings/pos_settings.js b/erpnext/accounts/doctype/pos_settings/pos_settings.js
index 8890d59403..4037a927fa 100644
--- a/erpnext/accounts/doctype/pos_settings/pos_settings.js
+++ b/erpnext/accounts/doctype/pos_settings/pos_settings.js
@@ -16,8 +16,13 @@ frappe.ui.form.on('POS Settings', {
}
});
- frappe.meta.get_docfield("POS Field", "fieldname", frm.doc.name).options = [""].concat(fields);
+ frm.fields_dict.invoice_fields.grid.update_docfield_property(
+ 'fieldname',
+ 'options',
+ [""].concat(fields)
+ );
});
+
}
});
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
index 66a8e206a8..e61cde8fd0 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -496,15 +496,6 @@ cur_frm.fields_dict['items'].grid.get_field('project').get_query = function(doc,
}
}
-cur_frm.cscript.select_print_heading = function(doc,cdt,cdn){
- if(doc.select_print_heading){
- // print heading
- cur_frm.pformat.print_heading = doc.select_print_heading;
- }
- else
- cur_frm.pformat.print_heading = __("Purchase Invoice");
-}
-
frappe.ui.form.on("Purchase Invoice", {
setup: function(frm) {
frm.custom_make_buttons = {
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index 26d60389f6..8a42d9e13c 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -1,9 +1,6 @@
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
-// print heading
-cur_frm.pformat.print_heading = 'Invoice';
-
{% include 'erpnext/selling/sales_common.js' %};
frappe.provide("erpnext.accounts");
diff --git a/erpnext/healthcare/doctype/patient_assessment/patient_assessment.js b/erpnext/healthcare/doctype/patient_assessment/patient_assessment.js
index c7074e88d5..f28d32c22c 100644
--- a/erpnext/healthcare/doctype/patient_assessment/patient_assessment.js
+++ b/erpnext/healthcare/doctype/patient_assessment/patient_assessment.js
@@ -39,11 +39,13 @@ frappe.ui.form.on('Patient Assessment', {
},
set_score_range: function(frm) {
- let options = [];
+ let options = [''];
for(let i = frm.doc.scale_min; i <= frm.doc.scale_max; i++) {
options.push(i);
}
- frappe.meta.get_docfield('Patient Assessment Sheet', 'score', frm.doc.name).options = [''].concat(options);
+ frm.fields_dict.assessment_sheet.grid.update_docfield_property(
+ 'score', 'options', options
+ );
},
calculate_total_score: function(frm, cdt, cdn) {
@@ -83,4 +85,4 @@ frappe.ui.form.on('Patient Assessment Sheet', {
score: function(frm, cdt, cdn) {
frm.events.calculate_total_score(frm, cdt, cdn);
}
-});
\ No newline at end of file
+});
diff --git a/erpnext/healthcare/doctype/therapy_plan/therapy_plan.js b/erpnext/healthcare/doctype/therapy_plan/therapy_plan.js
index d1f72d625b..3bad65c312 100644
--- a/erpnext/healthcare/doctype/therapy_plan/therapy_plan.js
+++ b/erpnext/healthcare/doctype/therapy_plan/therapy_plan.js
@@ -58,8 +58,12 @@ frappe.ui.form.on('Therapy Plan', {
}
if (frm.doc.therapy_plan_template) {
- frappe.meta.get_docfield('Therapy Plan Detail', 'therapy_type', frm.doc.name).read_only = 1;
- frappe.meta.get_docfield('Therapy Plan Detail', 'no_of_sessions', frm.doc.name).read_only = 1;
+ frm.fields_dict.therapy_plan_details.grid.update_docfield_property(
+ 'therapy_type', 'read_only', 1,
+ );
+ frm.fields_dict.therapy_plan_details.grid.update_docfield_property(
+ 'no_of_sessions', 'read_only', 1
+ );
}
},
@@ -126,4 +130,4 @@ frappe.ui.form.on('Therapy Plan Detail', {
frm.set_value('total_sessions', total);
refresh_field('total_sessions');
}
-});
\ No newline at end of file
+});
diff --git a/erpnext/manufacturing/doctype/routing/routing.js b/erpnext/manufacturing/doctype/routing/routing.js
index 9b1a8ca670..032c9cd9a2 100644
--- a/erpnext/manufacturing/doctype/routing/routing.js
+++ b/erpnext/manufacturing/doctype/routing/routing.js
@@ -11,10 +11,9 @@ frappe.ui.form.on('Routing', {
},
display_sequence_id_column: function(frm) {
- frappe.meta.get_docfield("BOM Operation", "sequence_id",
- frm.doc.name).in_list_view = true;
-
- frm.fields_dict.operations.grid.refresh();
+ frm.fields_dict.operations.grid.update_docfield_property(
+ 'sequence_id', 'in_list_view', 1
+ );
},
calculate_operating_cost: function(frm, child) {
@@ -69,4 +68,4 @@ frappe.ui.form.on('BOM Operation', {
const d = locals[cdt][cdn];
frm.events.calculate_operating_cost(frm, d);
}
-});
\ No newline at end of file
+});
diff --git a/erpnext/payroll/doctype/salary_structure/salary_structure.js b/erpnext/payroll/doctype/salary_structure/salary_structure.js
index 6aa1387363..21e9d81225 100755
--- a/erpnext/payroll/doctype/salary_structure/salary_structure.js
+++ b/erpnext/payroll/doctype/salary_structure/salary_structure.js
@@ -111,12 +111,17 @@ frappe.ui.form.on('Salary Structure', {
frappe.set_route('Form', 'Salary Structure Assignment', doc.name);
});
frm.add_custom_button(__("Assign to Employees"),function () {
- frm.trigger('assign_to_employees')
- })
+ frm.trigger('assign_to_employees')
+ })
}
+
+ // set columns read-only
let fields_read_only = ["is_tax_applicable", "is_flexible_benefit", "variable_based_on_taxable_salary"];
fields_read_only.forEach(function(field) {
- frappe.meta.get_docfield("Salary Detail", field, frm.doc.name).read_only = 1;
+ frm.fields_dict.earnings.grid.update_docfield_property(
+ field, 'read_only', 1);
+ frm.fields_dict.deductions.grid.update_docfield_property(
+ field, 'read_only', 1);
});
frm.trigger('set_earning_deduction_component');
},
diff --git a/erpnext/portal/doctype/products_settings/products_settings.js b/erpnext/portal/doctype/products_settings/products_settings.js
index b68b5d7aa8..2f8b037164 100644
--- a/erpnext/portal/doctype/products_settings/products_settings.js
+++ b/erpnext/portal/doctype/products_settings/products_settings.js
@@ -10,10 +10,12 @@ frappe.ui.form.on('Products Settings', {
df => ['Link', 'Table MultiSelect'].includes(df.fieldtype) && !df.hidden
).map(df => ({ label: df.label, value: df.fieldname }));
- const field = frappe.meta.get_docfield("Website Filter Field", "fieldname", frm.docname);
- field.fieldtype = 'Select';
- field.options = valid_fields;
- frm.fields_dict.filter_fields.grid.refresh();
+ frm.fields_dict.filter_fields.grid.update_docfield_property(
+ 'fieldname', 'fieldtype', 'Select'
+ );
+ frm.fields_dict.filter_fields.grid.update_docfield_property(
+ 'fieldname', 'options', valid_fields
+ );
});
}
});
diff --git a/erpnext/public/js/controllers/accounts.js b/erpnext/public/js/controllers/accounts.js
index 649eb454ac..ceeecb28a2 100644
--- a/erpnext/public/js/controllers/accounts.js
+++ b/erpnext/public/js/controllers/accounts.js
@@ -276,74 +276,3 @@ erpnext.taxes.set_conditional_mandatory_rate_or_amount = function(grid_row) {
}
}
}
-
-
-// For customizing print
-cur_frm.pformat.total = function(doc) { return ''; }
-cur_frm.pformat.discount_amount = function(doc) { return ''; }
-cur_frm.pformat.grand_total = function(doc) { return ''; }
-cur_frm.pformat.rounded_total = function(doc) { return ''; }
-cur_frm.pformat.in_words = function(doc) { return ''; }
-
-cur_frm.pformat.taxes= function(doc){
- //function to make row of table
- var make_row = function(title, val, bold, is_negative) {
- var bstart = ''; var bend = '';
- return '' + (bold?bstart:'') + title + (bold?bend:'') + ' | '
- + '' + (is_negative ? '- ' : '')
- + format_currency(val, doc.currency) + ' | ';
- }
-
- function print_hide(fieldname) {
- var doc_field = frappe.meta.get_docfield(doc.doctype, fieldname, doc.name);
- return doc_field.print_hide;
- }
-
- out ='';
- if (!doc.print_without_amount) {
- var cl = doc.taxes || [];
-
- // outer table
- var out=' | ';
-
- // main table
-
- out +='';
-
- if(!print_hide('total')) {
- out += make_row('Total', doc.total, 1);
- }
-
- // Discount Amount on net total
- if(!print_hide('discount_amount') && doc.apply_discount_on == "Net Total" && doc.discount_amount)
- out += make_row('Discount Amount', doc.discount_amount, 0, 1);
-
- // add rows
- if(cl.length){
- for(var i=0;i';
- out += '';
- out += 'In Words | ';
- out += '' + doc.in_words + ' | ';
- }
- out += '
| ';
- }
- return out;
-}
\ No newline at end of file
diff --git a/erpnext/setup/doctype/item_group/item_group.js b/erpnext/setup/doctype/item_group/item_group.js
index 1413cb2862..885d874720 100644
--- a/erpnext/setup/doctype/item_group/item_group.js
+++ b/erpnext/setup/doctype/item_group/item_group.js
@@ -61,7 +61,7 @@ frappe.ui.form.on("Item Group", {
frappe.set_route("List", "Item", {"item_group": frm.doc.name});
});
}
-
+
frappe.model.with_doctype('Item', () => {
const item_meta = frappe.get_meta('Item');
@@ -69,10 +69,12 @@ frappe.ui.form.on("Item Group", {
df => ['Link', 'Table MultiSelect'].includes(df.fieldtype) && !df.hidden
).map(df => ({ label: df.label, value: df.fieldname }));
- const field = frappe.meta.get_docfield("Website Filter Field", "fieldname", frm.docname);
- field.fieldtype = 'Select';
- field.options = valid_fields;
- frm.fields_dict.filter_fields.grid.refresh();
+ frm.fields_dict.filter_fields.grid.update_docfield_property(
+ 'fieldname', 'fieldtype', 'Select'
+ );
+ frm.fields_dict.filter_fields.grid.update_docfield_property(
+ 'fieldname', 'options', valid_fields
+ );
});
},
diff --git a/erpnext/stock/doctype/item_variant_settings/item_variant_settings.js b/erpnext/stock/doctype/item_variant_settings/item_variant_settings.js
index 24f7e31a0c..e8fb34732f 100644
--- a/erpnext/stock/doctype/item_variant_settings/item_variant_settings.js
+++ b/erpnext/stock/doctype/item_variant_settings/item_variant_settings.js
@@ -15,8 +15,9 @@ frappe.ui.form.on('Item Variant Settings', {
}
});
- const child = frappe.meta.get_docfield("Variant Field", "field_name", frm.doc.name);
- child.options = allow_fields;
+ frm.fields_dict.fields.grid.update_docfield_property(
+ 'field_name', 'options', allow_fields
+ );
});
}
});
diff --git a/erpnext/stock/doctype/packing_slip/packing_slip.js b/erpnext/stock/doctype/packing_slip/packing_slip.js
index bd14e5f616..40d46852d0 100644
--- a/erpnext/stock/doctype/packing_slip/packing_slip.js
+++ b/erpnext/stock/doctype/packing_slip/packing_slip.js
@@ -110,19 +110,4 @@ cur_frm.cscript.calc_net_total_pkg = function(doc, ps_detail) {
refresh_many(['net_weight_pkg', 'net_weight_uom', 'gross_weight_uom', 'gross_weight_pkg']);
}
-var make_row = function(title,val,bold){
- var bstart = ''; var bend = '';
- return ' | '+(bold?bstart:'')+title+(bold?bend:'')+' | '
- +''+ val +' | '
- +' '
-}
-
-cur_frm.pformat.net_weight_pkg= function(doc){
- return '' + make_row('Net Weight', doc.net_weight_pkg) + ' '
-}
-
-cur_frm.pformat.gross_weight_pkg= function(doc){
- return '' + make_row('Gross Weight', doc.gross_weight_pkg) + ' '
-}
-
// TODO: validate gross weight field
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.js b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.js
index 57cc3504a9..4d1a514c6b 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.js
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.js
@@ -248,13 +248,6 @@ cur_frm.fields_dict['items'].grid.get_field('project').get_query = function(doc,
}
}
-cur_frm.cscript.select_print_heading = function(doc, cdt, cdn) {
- if(doc.select_print_heading)
- cur_frm.pformat.print_heading = doc.select_print_heading;
- else
- cur_frm.pformat.print_heading = "Purchase Receipt";
-}
-
cur_frm.fields_dict['select_print_heading'].get_query = function(doc, cdt, cdn) {
return {
filters: [
diff --git a/erpnext/support/doctype/service_level_agreement/service_level_agreement.js b/erpnext/support/doctype/service_level_agreement/service_level_agreement.js
index 5346195a39..00060b9530 100644
--- a/erpnext/support/doctype/service_level_agreement/service_level_agreement.js
+++ b/erpnext/support/doctype/service_level_agreement/service_level_agreement.js
@@ -10,7 +10,9 @@ frappe.ui.form.on('Service Level Agreement', {
let statuses = frappe.meta.get_docfield('Issue', 'status', frm.doc.name).options;
statuses = statuses.split('\n');
allow_statuses = statuses.filter((status) => !exclude_statuses.includes(status));
- frappe.meta.get_docfield('Pause SLA On Status', 'status', frm.doc.name).options = [''].concat(allow_statuses);
+ frm.fields_dict.pause_sla_on.grid.update_docfield_property(
+ 'status', 'options', [''].concat(allow_statuses)
+ );
});
}
-});
\ No newline at end of file
+});
From 3c58fd4d5e3384482cbca1c82a270397a00eb688 Mon Sep 17 00:00:00 2001
From: Rushabh Mehta
Date: Tue, 13 Apr 2021 12:05:10 +0530
Subject: [PATCH 205/207] fix(minor): fix dynamically changing grid properties
---
erpnext/accounts/doctype/bank/bank.js | 4 +++-
.../doctype/payment_reconciliation/payment_reconciliation.js | 2 +-
erpnext/accounts/doctype/pos_settings/pos_settings.js | 4 +---
3 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/erpnext/accounts/doctype/bank/bank.js b/erpnext/accounts/doctype/bank/bank.js
index 8c0abc2447..059e1d3158 100644
--- a/erpnext/accounts/doctype/bank/bank.js
+++ b/erpnext/accounts/doctype/bank/bank.js
@@ -42,7 +42,9 @@ let add_fields_to_mapping_table = function (frm) {
});
});
- frm.fields_dict.bank_transaction_mapping.grid.update_docfield_property('frm.fields_dict.bank_transaction_mapping.grid', 'options', options);
+ frm.fields_dict.bank_transaction_mapping.grid.update_docfield_property(
+ 'bank_transaction_field', 'options', options
+ );
};
erpnext.integrations.refreshPlaidLink = class refreshPlaidLink {
diff --git a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.js b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.js
index b693863fb2..a27659b8f7 100644
--- a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.js
+++ b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.js
@@ -235,7 +235,7 @@ erpnext.accounts.PaymentReconciliationController = frappe.ui.form.Controller.ext
if (invoices) {
this.frm.fields_dict.payment.grid.update_docfield_property(
- 'invoice_number', options, "\n" + invoices.join("\n")
+ 'invoice_number', 'options', "\n" + invoices.join("\n")
)
$.each(me.frm.doc.payments || [], function(i, p) {
diff --git a/erpnext/accounts/doctype/pos_settings/pos_settings.js b/erpnext/accounts/doctype/pos_settings/pos_settings.js
index 4037a927fa..3625393a80 100644
--- a/erpnext/accounts/doctype/pos_settings/pos_settings.js
+++ b/erpnext/accounts/doctype/pos_settings/pos_settings.js
@@ -17,9 +17,7 @@ frappe.ui.form.on('POS Settings', {
});
frm.fields_dict.invoice_fields.grid.update_docfield_property(
- 'fieldname',
- 'options',
- [""].concat(fields)
+ 'fieldname', 'options', [""].concat(fields)
);
});
From ff935b45860cc26e43abef045373753a41c0c864 Mon Sep 17 00:00:00 2001
From: Rushabh Mehta
Date: Tue, 13 Apr 2021 12:09:36 +0530
Subject: [PATCH 206/207] fix(minor): fix dynamically changing grid properties
---
erpnext/healthcare/doctype/therapy_plan/therapy_plan.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/erpnext/healthcare/doctype/therapy_plan/therapy_plan.js b/erpnext/healthcare/doctype/therapy_plan/therapy_plan.js
index 3bad65c312..42e231dc66 100644
--- a/erpnext/healthcare/doctype/therapy_plan/therapy_plan.js
+++ b/erpnext/healthcare/doctype/therapy_plan/therapy_plan.js
@@ -59,7 +59,7 @@ frappe.ui.form.on('Therapy Plan', {
if (frm.doc.therapy_plan_template) {
frm.fields_dict.therapy_plan_details.grid.update_docfield_property(
- 'therapy_type', 'read_only', 1,
+ 'therapy_type', 'read_only', 1
);
frm.fields_dict.therapy_plan_details.grid.update_docfield_property(
'no_of_sessions', 'read_only', 1
From 82d0a1a13e510b1031bb4cca6316575adbf65f31 Mon Sep 17 00:00:00 2001
From: Suraj Shetty
Date: Tue, 13 Apr 2021 12:35:42 +0530
Subject: [PATCH 207/207] style: Add missing semicolons - & make formatting
consistent
---
erpnext/accounts/doctype/journal_entry/journal_entry.js | 2 +-
.../payment_reconciliation/payment_reconciliation.js | 2 +-
.../payroll/doctype/salary_structure/salary_structure.js | 6 ++++--
3 files changed, 6 insertions(+), 4 deletions(-)
diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.js b/erpnext/accounts/doctype/journal_entry/journal_entry.js
index 411bd3d6fc..d76641dc9b 100644
--- a/erpnext/accounts/doctype/journal_entry/journal_entry.js
+++ b/erpnext/accounts/doctype/journal_entry/journal_entry.js
@@ -334,7 +334,7 @@ erpnext.accounts.JournalEntry = frappe.ui.form.Controller.extend({
+ ((value==null || value==="") ? "" : format_currency(Math.abs(value), currency))
+ " " + dr_or_cr
+ "";
- }
+ };
this.frm.fields_dict.accounts.grid.update_docfield_property('balance', 'formatter', formatter);
this.frm.fields_dict.accounts.grid.update_docfield_property('party_balance', 'formatter', formatter);
},
diff --git a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.js b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.js
index a27659b8f7..08103184d5 100644
--- a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.js
+++ b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.js
@@ -236,7 +236,7 @@ erpnext.accounts.PaymentReconciliationController = frappe.ui.form.Controller.ext
if (invoices) {
this.frm.fields_dict.payment.grid.update_docfield_property(
'invoice_number', 'options', "\n" + invoices.join("\n")
- )
+ );
$.each(me.frm.doc.payments || [], function(i, p) {
if(!in_list(invoices, cstr(p.invoice_number))) p.invoice_number = null;
diff --git a/erpnext/payroll/doctype/salary_structure/salary_structure.js b/erpnext/payroll/doctype/salary_structure/salary_structure.js
index 21e9d81225..b539b1b8a9 100755
--- a/erpnext/payroll/doctype/salary_structure/salary_structure.js
+++ b/erpnext/payroll/doctype/salary_structure/salary_structure.js
@@ -119,9 +119,11 @@ frappe.ui.form.on('Salary Structure', {
let fields_read_only = ["is_tax_applicable", "is_flexible_benefit", "variable_based_on_taxable_salary"];
fields_read_only.forEach(function(field) {
frm.fields_dict.earnings.grid.update_docfield_property(
- field, 'read_only', 1);
+ field, 'read_only', 1
+ );
frm.fields_dict.deductions.grid.update_docfield_property(
- field, 'read_only', 1);
+ field, 'read_only', 1
+ );
});
frm.trigger('set_earning_deduction_component');
},
|