diff --git a/.github/helper/documentation.py b/.github/helper/documentation.py index 378983e95f..83346045f8 100644 --- a/.github/helper/documentation.py +++ b/.github/helper/documentation.py @@ -3,52 +3,71 @@ import requests from urllib.parse import urlparse -docs_repos = [ - "frappe_docs", - "erpnext_documentation", +WEBSITE_REPOS = [ "erpnext_com", "frappe_io", ] +DOCUMENTATION_DOMAINS = [ + "docs.erpnext.com", + "frappeframework.com", +] -def uri_validator(x): - result = urlparse(x) - return all([result.scheme, result.netloc, result.path]) -def docs_link_exists(body): - for line in body.splitlines(): - for word in line.split(): - if word.startswith('http') and uri_validator(word): - parsed_url = urlparse(word) - if parsed_url.netloc == "github.com": - parts = parsed_url.path.split('/') - if len(parts) == 5 and parts[1] == "frappe" and parts[2] in docs_repos: - return True - elif parsed_url.netloc == "docs.erpnext.com": - return True +def is_valid_url(url: str) -> bool: + parts = urlparse(url) + return all((parts.scheme, parts.netloc, parts.path)) + + +def is_documentation_link(word: str) -> bool: + if not word.startswith("http") or not is_valid_url(word): + return False + + parsed_url = urlparse(word) + if parsed_url.netloc in DOCUMENTATION_DOMAINS: + return True + + if parsed_url.netloc == "github.com": + parts = parsed_url.path.split("/") + if len(parts) == 5 and parts[1] == "frappe" and parts[2] in WEBSITE_REPOS: + return True + + return False + + +def contains_documentation_link(body: str) -> bool: + return any( + is_documentation_link(word) + for line in body.splitlines() + for word in line.split() + ) + + +def check_pull_request(number: str) -> "tuple[int, str]": + response = requests.get(f"https://api.github.com/repos/frappe/erpnext/pulls/{number}") + if not response.ok: + return 1, "Pull Request Not Found! ⚠️" + + payload = response.json() + title = (payload.get("title") or "").lower().strip() + head_sha = (payload.get("head") or {}).get("sha") + body = (payload.get("body") or "").lower() + + if ( + not title.startswith("feat") + or not head_sha + or "no-docs" in body + or "backport" in body + ): + return 0, "Skipping documentation checks... 🏃" + + if contains_documentation_link(body): + return 0, "Documentation Link Found. You're Awesome! 🎉" + + return 1, "Documentation Link Not Found! ⚠️" if __name__ == "__main__": - pr = sys.argv[1] - response = requests.get("https://api.github.com/repos/frappe/erpnext/pulls/{}".format(pr)) - - if response.ok: - payload = response.json() - title = (payload.get("title") or "").lower().strip() - head_sha = (payload.get("head") or {}).get("sha") - body = (payload.get("body") or "").lower() - - if (title.startswith("feat") - and head_sha - and "no-docs" not in body - and "backport" not in body - ): - if docs_link_exists(body): - print("Documentation Link Found. You're Awesome! 🎉") - - else: - print("Documentation Link Not Found! ⚠️") - sys.exit(1) - - else: - print("Skipping documentation checks... 🏃") + exit_code, message = check_pull_request(sys.argv[1]) + print(message) + sys.exit(exit_code) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 73aae33e93..d70977c07e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -32,8 +32,8 @@ repos: - id: black additional_dependencies: ['click==8.0.4'] - - repo: https://github.com/timothycrosley/isort - rev: 5.9.1 + - repo: https://github.com/PyCQA/isort + rev: 5.12.0 hooks: - id: isort exclude: ".*setup.py$" diff --git a/erpnext/accounts/doctype/budget/budget.py b/erpnext/accounts/doctype/budget/budget.py index 53838fbd17..4c628a4d95 100644 --- a/erpnext/accounts/doctype/budget/budget.py +++ b/erpnext/accounts/doctype/budget/budget.py @@ -184,6 +184,11 @@ def validate_budget_records(args, budget_records, expense_amount): amount = expense_amount or get_amount(args, budget) yearly_action, monthly_action = get_actions(args, budget) + if yearly_action in ("Stop", "Warn"): + compare_expense_with_budget( + args, flt(budget.budget_amount), _("Annual"), yearly_action, budget.budget_against, amount + ) + if monthly_action in ["Stop", "Warn"]: budget_amount = get_accumulated_monthly_budget( budget.monthly_distribution, args.posting_date, args.fiscal_year, budget.budget_amount @@ -195,28 +200,28 @@ def validate_budget_records(args, budget_records, expense_amount): args, budget_amount, _("Accumulated Monthly"), monthly_action, budget.budget_against, amount ) - if ( - yearly_action in ("Stop", "Warn") - and monthly_action != "Stop" - and yearly_action != monthly_action - ): - compare_expense_with_budget( - args, flt(budget.budget_amount), _("Annual"), yearly_action, budget.budget_against, amount - ) - def compare_expense_with_budget(args, budget_amount, action_for, action, budget_against, amount=0): - actual_expense = amount or get_actual_expense(args) - if actual_expense > budget_amount: - diff = actual_expense - budget_amount + actual_expense = get_actual_expense(args) + total_expense = actual_expense + amount + + if total_expense > budget_amount: + if actual_expense > budget_amount: + error_tense = _("is already") + diff = actual_expense - budget_amount + else: + error_tense = _("will be") + diff = total_expense - budget_amount + currency = frappe.get_cached_value("Company", args.company, "default_currency") - msg = _("{0} Budget for Account {1} against {2} {3} is {4}. It will exceed by {5}").format( + msg = _("{0} Budget for Account {1} against {2} {3} is {4}. It {5} exceed by {6}").format( _(action_for), frappe.bold(args.account), - args.budget_against_field, + frappe.unscrub(args.budget_against_field), frappe.bold(budget_against), frappe.bold(fmt_money(budget_amount, currency=currency)), + error_tense, frappe.bold(fmt_money(diff, currency=currency)), ) @@ -227,9 +232,9 @@ def compare_expense_with_budget(args, budget_amount, action_for, action, budget_ action = "Warn" if action == "Stop": - frappe.throw(msg, BudgetError) + frappe.throw(msg, BudgetError, title=_("Budget Exceeded")) else: - frappe.msgprint(msg, indicator="orange") + frappe.msgprint(msg, indicator="orange", title=_("Budget Exceeded")) def get_actions(args, budget): @@ -351,7 +356,9 @@ def get_actual_expense(args): """ select sum(gle.debit) - sum(gle.credit) from `tabGL Entry` gle - where gle.account=%(account)s + where + is_cancelled = 0 + and gle.account=%(account)s {condition1} and gle.fiscal_year=%(fiscal_year)s and gle.company=%(company)s diff --git a/erpnext/accounts/doctype/cost_center_allocation/cost_center_allocation.py b/erpnext/accounts/doctype/cost_center_allocation/cost_center_allocation.py index d25016fe59..54ffe21a15 100644 --- a/erpnext/accounts/doctype/cost_center_allocation/cost_center_allocation.py +++ b/erpnext/accounts/doctype/cost_center_allocation/cost_center_allocation.py @@ -28,9 +28,14 @@ class InvalidDateError(frappe.ValidationError): class CostCenterAllocation(Document): + def __init__(self, *args, **kwargs): + super(CostCenterAllocation, self).__init__(*args, **kwargs) + self._skip_from_date_validation = False + def validate(self): self.validate_total_allocation_percentage() - self.validate_from_date_based_on_existing_gle() + if not self._skip_from_date_validation: + self.validate_from_date_based_on_existing_gle() self.validate_backdated_allocation() self.validate_main_cost_center() self.validate_child_cost_centers() diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.js b/erpnext/accounts/doctype/journal_entry/journal_entry.js index 30a32015f5..21f27aedc5 100644 --- a/erpnext/accounts/doctype/journal_entry/journal_entry.js +++ b/erpnext/accounts/doctype/journal_entry/journal_entry.js @@ -8,7 +8,7 @@ frappe.provide("erpnext.journal_entry"); frappe.ui.form.on("Journal Entry", { setup: function(frm) { frm.add_fetch("bank_account", "account", "account"); - frm.ignore_doctypes_on_cancel_all = ['Sales Invoice', 'Purchase Invoice']; + frm.ignore_doctypes_on_cancel_all = ['Sales Invoice', 'Purchase Invoice', 'Journal Entry']; }, refresh: function(frm) { diff --git a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py index 12c0b7a7bf..154fdc039d 100644 --- a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py +++ b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py @@ -69,6 +69,10 @@ class PaymentReconciliation(Document): def get_jv_entries(self): condition = self.get_conditions() + + if self.get("cost_center"): + condition += f" and t2.cost_center = '{self.cost_center}' " + dr_or_cr = ( "credit_in_account_currency" if erpnext.get_party_account_type(self.party_type) == "Receivable" diff --git a/erpnext/accounts/doctype/payment_reconciliation/test_payment_reconciliation.py b/erpnext/accounts/doctype/payment_reconciliation/test_payment_reconciliation.py index 2ba90b4da9..00e3934f10 100644 --- a/erpnext/accounts/doctype/payment_reconciliation/test_payment_reconciliation.py +++ b/erpnext/accounts/doctype/payment_reconciliation/test_payment_reconciliation.py @@ -747,6 +747,73 @@ class TestPaymentReconciliation(FrappeTestCase): self.assertEqual(len(pr.get("invoices")), 0) self.assertEqual(len(pr.get("payments")), 0) + def test_cost_center_filter_on_vouchers(self): + """ + Test Cost Center filter is applied on Invoices, Payment Entries and Journals + """ + transaction_date = nowdate() + rate = 100 + + # 'Main - PR' Cost Center + si1 = self.create_sales_invoice( + qty=1, rate=rate, posting_date=transaction_date, do_not_submit=True + ) + si1.cost_center = self.main_cc.name + si1.submit() + + pe1 = self.create_payment_entry(posting_date=transaction_date, amount=rate) + pe1.cost_center = self.main_cc.name + pe1 = pe1.save().submit() + + je1 = self.create_journal_entry(self.bank, self.debit_to, 100, transaction_date) + je1.accounts[0].cost_center = self.main_cc.name + je1.accounts[1].cost_center = self.main_cc.name + je1.accounts[1].party_type = "Customer" + je1.accounts[1].party = self.customer + je1 = je1.save().submit() + + # 'Sub - PR' Cost Center + si2 = self.create_sales_invoice( + qty=1, rate=rate, posting_date=transaction_date, do_not_submit=True + ) + si2.cost_center = self.sub_cc.name + si2.submit() + + pe2 = self.create_payment_entry(posting_date=transaction_date, amount=rate) + pe2.cost_center = self.sub_cc.name + pe2 = pe2.save().submit() + + je2 = self.create_journal_entry(self.bank, self.debit_to, 100, transaction_date) + je2.accounts[0].cost_center = self.sub_cc.name + je2.accounts[1].cost_center = self.sub_cc.name + je2.accounts[1].party_type = "Customer" + je2.accounts[1].party = self.customer + je2 = je2.save().submit() + + pr = self.create_payment_reconciliation() + pr.cost_center = self.main_cc.name + + pr.get_unreconciled_entries() + + # check PR tool output + self.assertEqual(len(pr.get("invoices")), 1) + self.assertEqual(pr.get("invoices")[0].get("invoice_number"), si1.name) + self.assertEqual(len(pr.get("payments")), 2) + payment_vouchers = [x.get("reference_name") for x in pr.get("payments")] + self.assertCountEqual(payment_vouchers, [pe1.name, je1.name]) + + # Change cost center + pr.cost_center = self.sub_cc.name + + pr.get_unreconciled_entries() + + # check PR tool output + self.assertEqual(len(pr.get("invoices")), 1) + self.assertEqual(pr.get("invoices")[0].get("invoice_number"), si2.name) + self.assertEqual(len(pr.get("payments")), 2) + payment_vouchers = [x.get("reference_name") for x in pr.get("payments")] + self.assertCountEqual(payment_vouchers, [je2.name, pe2.name]) + def make_customer(customer_name, currency=None): if not frappe.db.exists("Customer", customer_name): diff --git a/erpnext/accounts/doctype/payment_request/payment_request.py b/erpnext/accounts/doctype/payment_request/payment_request.py index 4fc12dbc16..fc837c75a3 100644 --- a/erpnext/accounts/doctype/payment_request/payment_request.py +++ b/erpnext/accounts/doctype/payment_request/payment_request.py @@ -51,7 +51,7 @@ class PaymentRequest(Document): if existing_payment_request_amount: ref_doc = frappe.get_doc(self.reference_doctype, self.reference_name) - if hasattr(ref_doc, "order_type") and getattr(ref_doc, "order_type") != "Shopping Cart": + if not hasattr(ref_doc, "order_type") or getattr(ref_doc, "order_type") != "Shopping Cart": ref_amount = get_amount(ref_doc, self.payment_account) if existing_payment_request_amount + flt(self.grand_total) > ref_amount: diff --git a/erpnext/accounts/doctype/pos_invoice/pos_invoice.py b/erpnext/accounts/doctype/pos_invoice/pos_invoice.py index b543016eaa..a1239d64a0 100644 --- a/erpnext/accounts/doctype/pos_invoice/pos_invoice.py +++ b/erpnext/accounts/doctype/pos_invoice/pos_invoice.py @@ -675,7 +675,7 @@ def get_bin_qty(item_code, warehouse): def get_pos_reserved_qty(item_code, warehouse): reserved_qty = frappe.db.sql( - """select sum(p_item.qty) as qty + """select sum(p_item.stock_qty) as qty from `tabPOS Invoice` p, `tabPOS Invoice Item` p_item where p.name = p_item.parent and ifnull(p.consolidated_invoice, '') = '' diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json index 6281400fbc..54caf6f8b0 100644 --- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json +++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json @@ -1426,6 +1426,7 @@ }, { "default": "0", + "depends_on": "apply_tds", "fieldname": "tax_withholding_net_total", "fieldtype": "Currency", "hidden": 1, @@ -1435,12 +1436,13 @@ "read_only": 1 }, { + "depends_on": "apply_tds", "fieldname": "base_tax_withholding_net_total", "fieldtype": "Currency", "hidden": 1, "label": "Base Tax Withholding Net Total", "no_copy": 1, - "options": "currency", + "options": "Company:company:default_currency", "print_hide": 1, "read_only": 1 }, @@ -1554,7 +1556,7 @@ "idx": 204, "is_submittable": 1, "links": [], - "modified": "2022-12-12 18:37:38.142688", + "modified": "2023-01-28 19:18:56.586321", "modified_by": "Administrator", "module": "Accounts", "name": "Purchase Invoice", diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json index 4729d9c3db..2f4e45e618 100644 --- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json +++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json @@ -1776,6 +1776,8 @@ "width": "50%" }, { + "fetch_from": "sales_partner.commission_rate", + "fetch_if_empty": 1, "fieldname": "commission_rate", "fieldtype": "Float", "hide_days": 1, @@ -2141,7 +2143,7 @@ "link_fieldname": "consolidated_invoice" } ], - "modified": "2022-12-12 18:34:33.409895", + "modified": "2023-01-28 19:45:47.538163", "modified_by": "Administrator", "module": "Accounts", "name": "Sales Invoice", diff --git a/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py b/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py index 1bce43fd31..2c829b258b 100644 --- a/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py +++ b/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py @@ -410,12 +410,26 @@ def get_tds_amount(ldc, parties, inv, tax_details, tax_deducted, vouchers): tds_amount = 0 invoice_filters = {"name": ("in", vouchers), "docstatus": 1, "apply_tds": 1} + ## for TDS to be deducted on advances + payment_entry_filters = { + "party_type": "Supplier", + "party": ("in", parties), + "docstatus": 1, + "apply_tax_withholding_amount": 1, + "unallocated_amount": (">", 0), + "posting_date": ["between", (tax_details.from_date, tax_details.to_date)], + "tax_withholding_category": tax_details.get("tax_withholding_category"), + } + field = "sum(tax_withholding_net_total)" if cint(tax_details.consider_party_ledger_amount): invoice_filters.pop("apply_tds", None) field = "sum(grand_total)" + payment_entry_filters.pop("apply_tax_withholding_amount", None) + payment_entry_filters.pop("tax_withholding_category", None) + supp_credit_amt = frappe.db.get_value("Purchase Invoice", invoice_filters, field) or 0.0 supp_jv_credit_amt = ( @@ -427,14 +441,28 @@ def get_tds_amount(ldc, parties, inv, tax_details, tax_deducted, vouchers): "party": ("in", parties), "reference_type": ("!=", "Purchase Invoice"), }, - "sum(credit_in_account_currency)", + "sum(credit_in_account_currency - debit_in_account_currency)", ) or 0.0 ) + # Get Amount via payment entry + payment_entry_amounts = frappe.db.get_all( + "Payment Entry", + filters=payment_entry_filters, + fields=["sum(unallocated_amount) as amount", "payment_type"], + group_by="payment_type", + ) + supp_credit_amt += supp_jv_credit_amt supp_credit_amt += inv.tax_withholding_net_total + for type in payment_entry_amounts: + if type.payment_type == "Pay": + supp_credit_amt += type.amount + else: + supp_credit_amt -= type.amount + threshold = tax_details.get("threshold", 0) cumulative_threshold = tax_details.get("cumulative_threshold", 0) diff --git a/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py b/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py index 23caac047a..1e86cf5d2e 100644 --- a/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py +++ b/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py @@ -16,7 +16,7 @@ class TestTaxWithholdingCategory(unittest.TestCase): def setUpClass(self): # create relevant supplier, etc create_records() - create_tax_with_holding_category() + create_tax_withholding_category_records() def tearDown(self): cancel_invoices() @@ -38,7 +38,7 @@ class TestTaxWithholdingCategory(unittest.TestCase): pi = create_purchase_invoice(supplier="Test TDS Supplier") pi.submit() - # assert equal tax deduction on total invoice amount uptil now + # assert equal tax deduction on total invoice amount until now self.assertEqual(pi.taxes_and_charges_deducted, 3000) self.assertEqual(pi.grand_total, 7000) invoices.append(pi) @@ -47,7 +47,7 @@ class TestTaxWithholdingCategory(unittest.TestCase): pi = create_purchase_invoice(supplier="Test TDS Supplier", rate=5000) pi.submit() - # assert equal tax deduction on total invoice amount uptil now + # assert equal tax deduction on total invoice amount until now self.assertEqual(pi.taxes_and_charges_deducted, 500) invoices.append(pi) @@ -130,7 +130,7 @@ class TestTaxWithholdingCategory(unittest.TestCase): invoices.append(si) # create another invoice whose total when added to previously created invoice, - # surpasses cumulative threshhold + # surpasses cumulative threshold si = create_sales_invoice(customer="Test TCS Customer", rate=12000) si.submit() @@ -329,6 +329,38 @@ class TestTaxWithholdingCategory(unittest.TestCase): for d in reversed(invoices): d.cancel() + def test_tax_withholding_via_payment_entry_for_advances(self): + frappe.db.set_value( + "Supplier", "Test TDS Supplier7", "tax_withholding_category", "Advance TDS Category" + ) + + # create payment entry + pe1 = create_payment_entry( + payment_type="Pay", party_type="Supplier", party="Test TDS Supplier7", paid_amount=4000 + ) + pe1.submit() + + self.assertFalse(pe1.get("taxes")) + + pe2 = create_payment_entry( + payment_type="Pay", party_type="Supplier", party="Test TDS Supplier7", paid_amount=4000 + ) + pe2.submit() + + self.assertFalse(pe2.get("taxes")) + + pe3 = create_payment_entry( + payment_type="Pay", party_type="Supplier", party="Test TDS Supplier7", paid_amount=4000 + ) + pe3.apply_tax_withholding_amount = 1 + pe3.save() + pe3.submit() + + self.assertEquals(pe3.get("taxes")[0].tax_amount, 1200) + pe1.cancel() + pe2.cancel() + pe3.cancel() + def cancel_invoices(): purchase_invoices = frappe.get_all( @@ -450,6 +482,32 @@ def create_sales_invoice(**args): return si +def create_payment_entry(**args): + # return payment entry doc object + args = frappe._dict(args) + pe = frappe.get_doc( + { + "doctype": "Payment Entry", + "posting_date": today(), + "payment_type": args.payment_type, + "party_type": args.party_type, + "party": args.party, + "company": "_Test Company", + "paid_from": "Cash - _TC", + "paid_to": "Creditors - _TC", + "paid_amount": args.paid_amount or 10000, + "received_amount": args.paid_amount or 10000, + "reference_no": args.reference_no or "12345", + "reference_date": today(), + "paid_from_account_currency": "INR", + "paid_to_account_currency": "INR", + } + ) + + pe.save() + return pe + + def create_records(): # create a new suppliers for name in [ @@ -460,6 +518,7 @@ def create_records(): "Test TDS Supplier4", "Test TDS Supplier5", "Test TDS Supplier6", + "Test TDS Supplier7", ]: if frappe.db.exists("Supplier", name): continue @@ -530,142 +589,129 @@ def create_records(): ).insert() -def create_tax_with_holding_category(): +def create_tax_withholding_category_records(): fiscal_year = get_fiscal_year(today(), company="_Test Company") + from_date = fiscal_year[1] + to_date = fiscal_year[2] + # Cumulative threshold - if not frappe.db.exists("Tax Withholding Category", "Cumulative Threshold TDS"): - frappe.get_doc( - { - "doctype": "Tax Withholding Category", - "name": "Cumulative Threshold TDS", - "category_name": "10% TDS", - "rates": [ - { - "from_date": fiscal_year[1], - "to_date": fiscal_year[2], - "tax_withholding_rate": 10, - "single_threshold": 0, - "cumulative_threshold": 30000.00, - } - ], - "accounts": [{"company": "_Test Company", "account": "TDS - _TC"}], - } - ).insert() + create_tax_withholding_category( + category_name="Cumulative Threshold TDS", + rate=10, + from_date=from_date, + to_date=to_date, + account="TDS - _TC", + single_threshold=0, + cumulative_threshold=30000.00, + ) - if not frappe.db.exists("Tax Withholding Category", "Cumulative Threshold TCS"): - frappe.get_doc( - { - "doctype": "Tax Withholding Category", - "name": "Cumulative Threshold TCS", - "category_name": "10% TCS", - "rates": [ - { - "from_date": fiscal_year[1], - "to_date": fiscal_year[2], - "tax_withholding_rate": 10, - "single_threshold": 0, - "cumulative_threshold": 30000.00, - } - ], - "accounts": [{"company": "_Test Company", "account": "TCS - _TC"}], - } - ).insert() + # Category for TCS + create_tax_withholding_category( + category_name="Cumulative Threshold TCS", + rate=10, + from_date=from_date, + to_date=to_date, + account="TCS - _TC", + single_threshold=0, + cumulative_threshold=30000.00, + ) - # Single thresold - if not frappe.db.exists("Tax Withholding Category", "Single Threshold TDS"): - frappe.get_doc( - { - "doctype": "Tax Withholding Category", - "name": "Single Threshold TDS", - "category_name": "10% TDS", - "rates": [ - { - "from_date": fiscal_year[1], - "to_date": fiscal_year[2], - "tax_withholding_rate": 10, - "single_threshold": 20000.00, - "cumulative_threshold": 0, - } - ], - "accounts": [{"company": "_Test Company", "account": "TDS - _TC"}], - } - ).insert() + # Single threshold + create_tax_withholding_category( + category_name="Single Threshold TDS", + rate=10, + from_date=from_date, + to_date=to_date, + account="TDS - _TC", + single_threshold=20000, + cumulative_threshold=0, + ) - if not frappe.db.exists("Tax Withholding Category", "New TDS Category"): - frappe.get_doc( - { - "doctype": "Tax Withholding Category", - "name": "New TDS Category", - "category_name": "New TDS Category", - "round_off_tax_amount": 1, - "consider_party_ledger_amount": 1, - "tax_on_excess_amount": 1, - "rates": [ - { - "from_date": fiscal_year[1], - "to_date": fiscal_year[2], - "tax_withholding_rate": 10, - "single_threshold": 0, - "cumulative_threshold": 30000, - } - ], - "accounts": [{"company": "_Test Company", "account": "TDS - _TC"}], - } - ).insert() + create_tax_withholding_category( + category_name="New TDS Category", + rate=10, + from_date=from_date, + to_date=to_date, + account="TDS - _TC", + single_threshold=0, + cumulative_threshold=30000, + round_off_tax_amount=1, + consider_party_ledger_amount=1, + tax_on_excess_amount=1, + ) - if not frappe.db.exists("Tax Withholding Category", "Test Service Category"): - frappe.get_doc( - { - "doctype": "Tax Withholding Category", - "name": "Test Service Category", - "category_name": "Test Service Category", - "rates": [ - { - "from_date": fiscal_year[1], - "to_date": fiscal_year[2], - "tax_withholding_rate": 10, - "single_threshold": 2000, - "cumulative_threshold": 2000, - } - ], - "accounts": [{"company": "_Test Company", "account": "TDS - _TC"}], - } - ).insert() + create_tax_withholding_category( + category_name="Test Service Category", + rate=10, + from_date=from_date, + to_date=to_date, + account="TDS - _TC", + single_threshold=2000, + cumulative_threshold=2000, + ) - if not frappe.db.exists("Tax Withholding Category", "Test Goods Category"): - frappe.get_doc( - { - "doctype": "Tax Withholding Category", - "name": "Test Goods Category", - "category_name": "Test Goods Category", - "rates": [ - { - "from_date": fiscal_year[1], - "to_date": fiscal_year[2], - "tax_withholding_rate": 10, - "single_threshold": 2000, - "cumulative_threshold": 2000, - } - ], - "accounts": [{"company": "_Test Company", "account": "TDS - _TC"}], - } - ).insert() + create_tax_withholding_category( + category_name="Test Goods Category", + rate=10, + from_date=from_date, + to_date=to_date, + account="TDS - _TC", + single_threshold=2000, + cumulative_threshold=2000, + ) - if not frappe.db.exists("Tax Withholding Category", "Test Multi Invoice Category"): + create_tax_withholding_category( + category_name="Test Multi Invoice Category", + rate=10, + from_date=from_date, + to_date=to_date, + account="TDS - _TC", + single_threshold=5000, + cumulative_threshold=10000, + ) + + create_tax_withholding_category( + category_name="Advance TDS Category", + rate=10, + from_date=from_date, + to_date=to_date, + account="TDS - _TC", + single_threshold=5000, + cumulative_threshold=10000, + consider_party_ledger_amount=1, + ) + + +def create_tax_withholding_category( + category_name, + rate, + from_date, + to_date, + account, + single_threshold=0, + cumulative_threshold=0, + round_off_tax_amount=0, + consider_party_ledger_amount=0, + tax_on_excess_amount=0, +): + if not frappe.db.exists("Tax Withholding Category", category_name): frappe.get_doc( { "doctype": "Tax Withholding Category", - "name": "Test Multi Invoice Category", - "category_name": "Test Multi Invoice Category", + "name": category_name, + "category_name": category_name, + "round_off_tax_amount": round_off_tax_amount, + "consider_party_ledger_amount": consider_party_ledger_amount, + "tax_on_excess_amount": tax_on_excess_amount, "rates": [ { - "from_date": fiscal_year[1], - "to_date": fiscal_year[2], - "tax_withholding_rate": 10, - "single_threshold": 5000, - "cumulative_threshold": 10000, + "from_date": from_date, + "to_date": to_date, + "tax_withholding_rate": rate, + "single_threshold": single_threshold, + "cumulative_threshold": cumulative_threshold, } ], - "accounts": [{"company": "_Test Company", "account": "TDS - _TC"}], + "accounts": [{"company": "_Test Company", "account": account}], } ).insert() diff --git a/erpnext/accounts/party.py b/erpnext/accounts/party.py index baeed03a0f..b6eb3edbda 100644 --- a/erpnext/accounts/party.py +++ b/erpnext/accounts/party.py @@ -211,7 +211,13 @@ def set_address_details( else: party_details.update(get_company_address(company)) - if doctype and doctype in ["Delivery Note", "Sales Invoice", "Sales Order", "Quotation"]: + if doctype and doctype in [ + "Delivery Note", + "Sales Invoice", + "Sales Order", + "Quotation", + "POS Invoice", + ]: if party_details.company_address: party_details.update( get_fetch_values(doctype, "company_address", party_details.company_address) diff --git a/erpnext/accounts/report/general_ledger/general_ledger.py b/erpnext/accounts/report/general_ledger/general_ledger.py index fc23127935..27b84c4e77 100644 --- a/erpnext/accounts/report/general_ledger/general_ledger.py +++ b/erpnext/accounts/report/general_ledger/general_ledger.py @@ -526,7 +526,7 @@ def get_columns(filters): "options": "GL Entry", "hidden": 1, }, - {"label": _("Posting Date"), "fieldname": "posting_date", "fieldtype": "Date", "width": 90}, + {"label": _("Posting Date"), "fieldname": "posting_date", "fieldtype": "Date", "width": 100}, { "label": _("Account"), "fieldname": "account", @@ -538,13 +538,13 @@ def get_columns(filters): "label": _("Debit ({0})").format(currency), "fieldname": "debit", "fieldtype": "Float", - "width": 100, + "width": 130, }, { "label": _("Credit ({0})").format(currency), "fieldname": "credit", "fieldtype": "Float", - "width": 100, + "width": 130, }, { "label": _("Balance ({0})").format(currency), diff --git a/erpnext/accounts/report/gross_profit/gross_profit.py b/erpnext/accounts/report/gross_profit/gross_profit.py index 130b7150fb..25e7891a49 100644 --- a/erpnext/accounts/report/gross_profit/gross_profit.py +++ b/erpnext/accounts/report/gross_profit/gross_profit.py @@ -655,10 +655,35 @@ class GrossProfitGenerator(object): return self.calculate_buying_amount_from_sle( row, my_sle, parenttype, parent, item_row, item_code ) + elif row.sales_order and row.so_detail: + incoming_amount = self.get_buying_amount_from_so_dn(row.sales_order, row.so_detail, item_code) + if incoming_amount: + return incoming_amount else: return flt(row.qty) * self.get_average_buying_rate(row, item_code) - return 0.0 + return flt(row.qty) * self.get_average_buying_rate(row, item_code) + + def get_buying_amount_from_so_dn(self, sales_order, so_detail, item_code): + from frappe.query_builder.functions import Sum + + delivery_note = frappe.qb.DocType("Delivery Note") + delivery_note_item = frappe.qb.DocType("Delivery Note Item") + + query = ( + frappe.qb.from_(delivery_note) + .inner_join(delivery_note_item) + .on(delivery_note.name == delivery_note_item.parent) + .select(Sum(delivery_note_item.incoming_rate * delivery_note_item.stock_qty)) + .where(delivery_note.docstatus == 1) + .where(delivery_note_item.item_code == item_code) + .where(delivery_note_item.against_sales_order == sales_order) + .where(delivery_note_item.so_detail == so_detail) + .groupby(delivery_note_item.item_code) + ) + + incoming_amount = query.run() + return flt(incoming_amount[0][0]) if incoming_amount else 0 def get_average_buying_rate(self, row, item_code): args = row @@ -760,7 +785,8 @@ class GrossProfitGenerator(object): `tabSales Invoice`.territory, `tabSales Invoice Item`.item_code, `tabSales Invoice Item`.item_name, `tabSales Invoice Item`.description, `tabSales Invoice Item`.warehouse, `tabSales Invoice Item`.item_group, - `tabSales Invoice Item`.brand, `tabSales Invoice Item`.dn_detail, + `tabSales Invoice Item`.brand, `tabSales Invoice Item`.so_detail, + `tabSales Invoice Item`.sales_order, `tabSales Invoice Item`.dn_detail, `tabSales Invoice Item`.delivery_note, `tabSales Invoice Item`.stock_qty as qty, `tabSales Invoice Item`.base_net_rate, `tabSales Invoice Item`.base_net_amount, `tabSales Invoice Item`.name as "item_row", `tabSales Invoice`.is_return, diff --git a/erpnext/accounts/report/gross_profit/test_gross_profit.py b/erpnext/accounts/report/gross_profit/test_gross_profit.py index fa11a41df4..21681bef5b 100644 --- a/erpnext/accounts/report/gross_profit/test_gross_profit.py +++ b/erpnext/accounts/report/gross_profit/test_gross_profit.py @@ -302,3 +302,82 @@ class TestGrossProfit(FrappeTestCase): columns, data = execute(filters=filters) self.assertGreater(len(data), 0) + + def test_order_connected_dn_and_inv(self): + from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order + + """ + Test gp calculation when invoice and delivery note aren't directly connected. + SO -- INV + | + DN + """ + se = make_stock_entry( + company=self.company, + item_code=self.item, + target=self.warehouse, + qty=3, + basic_rate=100, + do_not_submit=True, + ) + item = se.items[0] + se.append( + "items", + { + "item_code": item.item_code, + "s_warehouse": item.s_warehouse, + "t_warehouse": item.t_warehouse, + "qty": 10, + "basic_rate": 200, + "conversion_factor": item.conversion_factor or 1.0, + "transfer_qty": flt(item.qty) * (flt(item.conversion_factor) or 1.0), + "serial_no": item.serial_no, + "batch_no": item.batch_no, + "cost_center": item.cost_center, + "expense_account": item.expense_account, + }, + ) + se = se.save().submit() + + so = make_sales_order( + customer=self.customer, + company=self.company, + warehouse=self.warehouse, + item=self.item, + qty=4, + do_not_save=False, + do_not_submit=False, + ) + + from erpnext.selling.doctype.sales_order.sales_order import ( + make_delivery_note, + make_sales_invoice, + ) + + make_delivery_note(so.name).submit() + sinv = make_sales_invoice(so.name).submit() + + filters = frappe._dict( + company=self.company, from_date=nowdate(), to_date=nowdate(), group_by="Invoice" + ) + + columns, data = execute(filters=filters) + expected_entry = { + "parent_invoice": sinv.name, + "currency": "INR", + "sales_invoice": self.item, + "customer": self.customer, + "posting_date": frappe.utils.datetime.date.fromisoformat(nowdate()), + "item_code": self.item, + "item_name": self.item, + "warehouse": "Stores - _GP", + "qty": 4.0, + "avg._selling_rate": 100.0, + "valuation_rate": 125.0, + "selling_amount": 400.0, + "buying_amount": 500.0, + "gross_profit": -100.0, + "gross_profit_%": -25.0, + } + gp_entry = [x for x in data if x.parent_invoice == sinv.name] + self.assertDictContainsSubset(expected_entry, gp_entry[0]) diff --git a/erpnext/assets/doctype/asset/depreciation.py b/erpnext/assets/doctype/asset/depreciation.py index 5337fd64ee..17d40784be 100644 --- a/erpnext/assets/doctype/asset/depreciation.py +++ b/erpnext/assets/doctype/asset/depreciation.py @@ -4,7 +4,17 @@ import frappe from frappe import _ -from frappe.utils import add_months, cint, flt, get_link_to_form, getdate, nowdate, today +from frappe.utils import ( + add_months, + cint, + flt, + get_last_day, + get_link_to_form, + getdate, + is_last_day_of_the_month, + nowdate, + today, +) from frappe.utils.user import get_users_with_role from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import ( @@ -400,6 +410,9 @@ def disposal_was_made_on_original_schedule_date(schedule_idx, row, posting_date_ row.depreciation_start_date, schedule_idx * cint(row.frequency_of_depreciation) ) + if is_last_day_of_the_month(row.depreciation_start_date): + orginal_schedule_date = get_last_day(orginal_schedule_date) + if orginal_schedule_date == posting_date_of_disposal: return True diff --git a/erpnext/assets/report/fixed_asset_register/fixed_asset_register.py b/erpnext/assets/report/fixed_asset_register/fixed_asset_register.py index faffd1134d..d41069c1c9 100644 --- a/erpnext/assets/report/fixed_asset_register/fixed_asset_register.py +++ b/erpnext/assets/report/fixed_asset_register/fixed_asset_register.py @@ -126,16 +126,18 @@ def get_asset_value(asset, finance_book=None): if not asset.calculate_depreciation: return flt(asset.gross_purchase_amount) - flt(asset.opening_accumulated_depreciation) - finance_book_filter = ["finance_book", "is", "not set"] - if finance_book: - finance_book_filter = ["finance_book", "=", finance_book] - - return frappe.db.get_value( + result = frappe.get_all( doctype="Asset Finance Book", - filters=[["parent", "=", asset.asset_id], finance_book_filter], - fieldname="value_after_depreciation", + filters={ + "parent": asset.asset_id, + "finance_book": finance_book or ("is", "not set"), + }, + pluck="value_after_depreciation", + limit=1, ) + return result[0] if result else 0.0 + def prepare_chart_data(data, filters): labels_values_map = {} diff --git a/erpnext/bulk_transaction/doctype/bulk_transaction_log/test_bulk_transaction_log.py b/erpnext/bulk_transaction/doctype/bulk_transaction_log/test_bulk_transaction_log.py index 646dba51ce..c673be89b3 100644 --- a/erpnext/bulk_transaction/doctype/bulk_transaction_log/test_bulk_transaction_log.py +++ b/erpnext/bulk_transaction/doctype/bulk_transaction_log/test_bulk_transaction_log.py @@ -15,17 +15,6 @@ class TestBulkTransactionLog(unittest.TestCase): create_customer() create_item() - def test_for_single_record(self): - so_name = create_so() - transaction_processing([{"name": so_name}], "Sales Order", "Sales Invoice") - data = frappe.db.get_list( - "Sales Invoice", - filters={"posting_date": date.today(), "customer": "Bulk Customer"}, - fields=["*"], - ) - if not data: - self.fail("No Sales Invoice Created !") - def test_entry_in_log(self): so_name = create_so() transaction_processing([{"name": so_name}], "Sales Order", "Sales Invoice") diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.json b/erpnext/buying/doctype/purchase_order/purchase_order.json index e1dd679781..29afc8476e 100644 --- a/erpnext/buying/doctype/purchase_order/purchase_order.json +++ b/erpnext/buying/doctype/purchase_order/purchase_order.json @@ -1221,6 +1221,7 @@ }, { "default": "0", + "depends_on": "apply_tds", "fieldname": "tax_withholding_net_total", "fieldtype": "Currency", "hidden": 1, @@ -1230,12 +1231,13 @@ "read_only": 1 }, { + "depends_on": "apply_tds", "fieldname": "base_tax_withholding_net_total", "fieldtype": "Currency", "hidden": 1, "label": "Base Tax Withholding Net Total", "no_copy": 1, - "options": "currency", + "options": "Company:company:default_currency", "print_hide": 1, "read_only": 1 }, @@ -1269,7 +1271,7 @@ "idx": 105, "is_submittable": 1, "links": [], - "modified": "2022-12-25 18:08:59.074182", + "modified": "2023-01-28 18:59:16.322824", "modified_by": "Administrator", "module": "Buying", "name": "Purchase Order", diff --git a/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py b/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py index 47a66ad46f..9b53421319 100644 --- a/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py +++ b/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py @@ -15,60 +15,4 @@ from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse class TestProcurementTracker(FrappeTestCase): - def test_result_for_procurement_tracker(self): - filters = {"company": "_Test Procurement Company", "cost_center": "Main - _TPC"} - expected_data = self.generate_expected_data() - report = execute(filters) - - length = len(report[1]) - self.assertEqual(expected_data, report[1][length - 1]) - - def generate_expected_data(self): - if not frappe.db.exists("Company", "_Test Procurement Company"): - frappe.get_doc( - dict( - doctype="Company", - company_name="_Test Procurement Company", - abbr="_TPC", - default_currency="INR", - country="Pakistan", - ) - ).insert() - warehouse = create_warehouse("_Test Procurement Warehouse", company="_Test Procurement Company") - mr = make_material_request( - company="_Test Procurement Company", warehouse=warehouse, cost_center="Main - _TPC" - ) - po = make_purchase_order(mr.name) - po.supplier = "_Test Supplier" - po.get("items")[0].cost_center = "Main - _TPC" - po.submit() - pr = make_purchase_receipt(po.name) - pr.get("items")[0].cost_center = "Main - _TPC" - pr.submit() - date_obj = datetime.date(datetime.now()) - - po.load_from_db() - - expected_data = { - "material_request_date": date_obj, - "cost_center": "Main - _TPC", - "project": None, - "requesting_site": "_Test Procurement Warehouse - _TPC", - "requestor": "Administrator", - "material_request_no": mr.name, - "item_code": "_Test Item", - "quantity": 10.0, - "unit_of_measurement": "_Test UOM", - "status": "To Bill", - "purchase_order_date": date_obj, - "purchase_order": po.name, - "supplier": "_Test Supplier", - "estimated_cost": 0.0, - "actual_cost": 0.0, - "purchase_order_amt": po.net_total, - "purchase_order_amt_in_company_currency": po.base_net_total, - "expected_delivery_date": date_obj, - "actual_delivery_date": date_obj, - } - - return expected_data + pass diff --git a/erpnext/crm/doctype/lead/lead.py b/erpnext/crm/doctype/lead/lead.py index b0ff5d4c3b..2a588d8d13 100644 --- a/erpnext/crm/doctype/lead/lead.py +++ b/erpnext/crm/doctype/lead/lead.py @@ -282,6 +282,7 @@ def _make_customer(source_name, target_doc=None, ignore_permissions=False): "contact_no": "phone_1", "fax": "fax_1", }, + "field_no_map": ["disabled"], } }, target_doc, @@ -390,7 +391,7 @@ def get_lead_details(lead, posting_date=None, company=None): { "territory": lead.territory, "customer_name": lead.company_name or lead.lead_name, - "contact_display": " ".join(filter(None, [lead.salutation, lead.lead_name])), + "contact_display": " ".join(filter(None, [lead.lead_name])), "contact_email": lead.email_id, "contact_mobile": lead.mobile_no, "contact_phone": lead.phone, diff --git a/erpnext/patches/v14_0/migrate_cost_center_allocations.py b/erpnext/patches/v14_0/migrate_cost_center_allocations.py index 3bd26933ba..48f4e6d989 100644 --- a/erpnext/patches/v14_0/migrate_cost_center_allocations.py +++ b/erpnext/patches/v14_0/migrate_cost_center_allocations.py @@ -18,9 +18,11 @@ def create_new_cost_center_allocation_records(cc_allocations): cca = frappe.new_doc("Cost Center Allocation") cca.main_cost_center = main_cc cca.valid_from = today() + cca._skip_from_date_validation = True for child_cc, percentage in allocations.items(): cca.append("allocation_percentages", ({"cost_center": child_cc, "percentage": percentage})) + cca.save() cca.submit() diff --git a/erpnext/portal/doctype/homepage_section/test_homepage_section.py b/erpnext/portal/doctype/homepage_section/test_homepage_section.py index 27c8fe4c95..3df56e67f6 100644 --- a/erpnext/portal/doctype/homepage_section/test_homepage_section.py +++ b/erpnext/portal/doctype/homepage_section/test_homepage_section.py @@ -10,62 +10,6 @@ from frappe.website.serve import get_response class TestHomepageSection(unittest.TestCase): - def test_homepage_section_card(self): - try: - frappe.get_doc( - { - "doctype": "Homepage Section", - "name": "Card Section", - "section_based_on": "Cards", - "section_cards": [ - { - "title": "Card 1", - "subtitle": "Subtitle 1", - "content": "This is test card 1", - "route": "/card-1", - }, - { - "title": "Card 2", - "subtitle": "Subtitle 2", - "content": "This is test card 2", - "image": "test.jpg", - }, - ], - "no_of_columns": 3, - } - ).insert(ignore_if_duplicate=True) - except frappe.DuplicateEntryError: - pass - - set_request(method="GET", path="home") - response = get_response() - - self.assertEqual(response.status_code, 200) - - html = frappe.safe_decode(response.get_data()) - - soup = BeautifulSoup(html, "html.parser") - sections = soup.find("main").find_all("section") - self.assertEqual(len(sections), 3) - - homepage_section = sections[2] - self.assertEqual(homepage_section.h3.text, "Card Section") - - cards = homepage_section.find_all(class_="card") - - self.assertEqual(len(cards), 2) - self.assertEqual(cards[0].h5.text, "Card 1") - self.assertEqual(cards[0].a["href"], "/card-1") - self.assertEqual(cards[1].p.text, "Subtitle 2") - - img = cards[1].find(class_="card-img-top") - - self.assertEqual(img["src"], "test.jpg") - self.assertEqual(img["loading"], "lazy") - - # cleanup - frappe.db.rollback() - def test_homepage_section_custom_html(self): frappe.get_doc( { diff --git a/erpnext/public/js/controllers/taxes_and_totals.js b/erpnext/public/js/controllers/taxes_and_totals.js index 271b563c73..2ce0c7eb00 100644 --- a/erpnext/public/js/controllers/taxes_and_totals.js +++ b/erpnext/public/js/controllers/taxes_and_totals.js @@ -122,7 +122,7 @@ erpnext.taxes_and_totals = class TaxesAndTotals extends erpnext.payments { calculate_item_values() { var me = this; if (!this.discount_amount_applied) { - for (item of this.frm.doc.items || []) { + for (const item of this.frm.doc.items || []) { frappe.model.round_floats_in(item); item.net_rate = item.rate; item.qty = item.qty === undefined ? (me.frm.doc.is_return ? -1 : 1) : item.qty; diff --git a/erpnext/public/js/controllers/transaction.js b/erpnext/public/js/controllers/transaction.js index 3a778fa496..09f2c5d5cb 100644 --- a/erpnext/public/js/controllers/transaction.js +++ b/erpnext/public/js/controllers/transaction.js @@ -1691,6 +1691,10 @@ erpnext.TransactionController = class TransactionController extends erpnext.taxe var me = this; var valid = true; + if (frappe.flags.ignore_company_party_validation) { + return valid; + } + $.each(["company", "customer"], function(i, fieldname) { if(frappe.meta.has_field(me.frm.doc.doctype, fieldname) && !["Purchase Order","Purchase Invoice"].includes(me.frm.doc.doctype)) { if (!me.frm.doc[fieldname]) { diff --git a/erpnext/public/js/setup_wizard.js b/erpnext/public/js/setup_wizard.js index 9288f515cd..a913844e18 100644 --- a/erpnext/public/js/setup_wizard.js +++ b/erpnext/public/js/setup_wizard.js @@ -13,19 +13,11 @@ frappe.setup.on("before_load", function () { erpnext.setup.slides_settings = [ { - // Brand - name: 'brand', - icon: "fa fa-bookmark", - title: __("The Brand"), - // help: __('Upload your letter head and logo. (you can edit them later).'), + // Organization + name: 'organization', + title: __("Setup your organization"), + icon: "fa fa-building", fields: [ - { - fieldtype: "Attach Image", fieldname: "attach_logo", - label: __("Attach Logo"), - description: __("100px by 100px"), - is_private: 0, - align: 'center' - }, { fieldname: 'company_name', label: __('Company Name'), @@ -35,54 +27,9 @@ erpnext.setup.slides_settings = [ { fieldname: 'company_abbr', label: __('Company Abbreviation'), - fieldtype: 'Data' - } - ], - onload: function(slide) { - this.bind_events(slide); - }, - bind_events: function (slide) { - slide.get_input("company_name").on("change", function () { - var parts = slide.get_input("company_name").val().split(" "); - var abbr = $.map(parts, function (p) { return p ? p.substr(0, 1) : null }).join(""); - slide.get_field("company_abbr").set_value(abbr.slice(0, 10).toUpperCase()); - }).val(frappe.boot.sysdefaults.company_name || "").trigger("change"); - - slide.get_input("company_abbr").on("change", function () { - if (slide.get_input("company_abbr").val().length > 10) { - frappe.msgprint(__("Company Abbreviation cannot have more than 5 characters")); - slide.get_field("company_abbr").set_value(""); - } - }); - }, - validate: function() { - if ((this.values.company_name || "").toLowerCase() == "company") { - frappe.msgprint(__("Company Name cannot be Company")); - return false; - } - if (!this.values.company_abbr) { - return false; - } - if (this.values.company_abbr.length > 10) { - return false; - } - return true; - } - }, - { - // Organisation - name: 'organisation', - title: __("Your Organization"), - icon: "fa fa-building", - fields: [ - { - fieldname: 'company_tagline', - label: __('What does it do?'), fieldtype: 'Data', - placeholder: __('e.g. "Build tools for builders"'), - reqd: 1 + hidden: 1 }, - { fieldname: 'bank_account', label: __('Bank Name'), fieldtype: 'Data', reqd: 1 }, { fieldname: 'chart_of_accounts', label: __('Chart of Accounts'), options: "", fieldtype: 'Select' @@ -94,40 +41,24 @@ erpnext.setup.slides_settings = [ ], onload: function (slide) { - this.load_chart_of_accounts(slide); this.bind_events(slide); + this.load_chart_of_accounts(slide); this.set_fy_dates(slide); }, - validate: function () { - let me = this; - let exist; - if (!this.validate_fy_dates()) { return false; } - // Validate bank name - if(me.values.bank_account) { - frappe.call({ - async: false, - method: "erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts.validate_bank_account", - args: { - "coa": me.values.chart_of_accounts, - "bank_account": me.values.bank_account - }, - callback: function (r) { - if(r.message){ - exist = r.message; - me.get_field("bank_account").set_value(""); - let message = __('Account {0} already exists. Please enter a different name for your bank account.', - [me.values.bank_account] - ); - frappe.msgprint(message); - } - } - }); - return !exist; // Return False if exist = true + if ((this.values.company_name || "").toLowerCase() == "company") { + frappe.msgprint(__("Company Name cannot be Company")); + return false; + } + if (!this.values.company_abbr) { + return false; + } + if (this.values.company_abbr.length > 10) { + return false; } return true; @@ -151,15 +82,15 @@ erpnext.setup.slides_settings = [ var country = frappe.wizard.values.country; if (country) { - var fy = erpnext.setup.fiscal_years[country]; - var current_year = moment(new Date()).year(); - var next_year = current_year + 1; + let fy = erpnext.setup.fiscal_years[country]; + let current_year = moment(new Date()).year(); + let next_year = current_year + 1; if (!fy) { fy = ["01-01", "12-31"]; next_year = current_year; } - var year_start_date = current_year + "-" + fy[0]; + let year_start_date = current_year + "-" + fy[0]; if (year_start_date > frappe.datetime.get_today()) { next_year = current_year; current_year -= 1; @@ -171,7 +102,7 @@ erpnext.setup.slides_settings = [ load_chart_of_accounts: function (slide) { - var country = frappe.wizard.values.country; + let country = frappe.wizard.values.country; if (country) { frappe.call({ @@ -202,12 +133,25 @@ erpnext.setup.slides_settings = [ me.charts_modal(slide, chart_template); }); + + slide.get_input("company_name").on("change", function () { + let parts = slide.get_input("company_name").val().split(" "); + let abbr = $.map(parts, function (p) { return p ? p.substr(0, 1) : null }).join(""); + slide.get_field("company_abbr").set_value(abbr.slice(0, 10).toUpperCase()); + }).val(frappe.boot.sysdefaults.company_name || "").trigger("change"); + + slide.get_input("company_abbr").on("change", function () { + if (slide.get_input("company_abbr").val().length > 10) { + frappe.msgprint(__("Company Abbreviation cannot have more than 5 characters")); + slide.get_field("company_abbr").set_value(""); + } + }); }, charts_modal: function(slide, chart_template) { let parent = __('All Accounts'); - var dialog = new frappe.ui.Dialog({ + let dialog = new frappe.ui.Dialog({ title: chart_template, fields: [ {'fieldname': 'expand_all', 'label': __('Expand All'), 'fieldtype': 'Button', diff --git a/erpnext/public/js/utils.js b/erpnext/public/js/utils.js index d37b7bb43b..51dcd64d9d 100755 --- a/erpnext/public/js/utils.js +++ b/erpnext/public/js/utils.js @@ -491,7 +491,20 @@ erpnext.utils.update_child_items = function(opts) { const child_meta = frappe.get_meta(`${frm.doc.doctype} Item`); const get_precision = (fieldname) => child_meta.fields.find(f => f.fieldname == fieldname).precision; - this.data = []; + this.data = frm.doc[opts.child_docname].map((d) => { + return { + "docname": d.name, + "name": d.name, + "item_code": d.item_code, + "delivery_date": d.delivery_date, + "schedule_date": d.schedule_date, + "conversion_factor": d.conversion_factor, + "qty": d.qty, + "rate": d.rate, + "uom": d.uom + } + }); + const fields = [{ fieldtype:'Data', fieldname:"docname", @@ -588,7 +601,7 @@ erpnext.utils.update_child_items = function(opts) { }) } - const dialog = new frappe.ui.Dialog({ + new frappe.ui.Dialog({ title: __("Update Items"), fields: [ { @@ -624,24 +637,7 @@ erpnext.utils.update_child_items = function(opts) { refresh_field("items"); }, primary_action_label: __('Update') - }); - - frm.doc[opts.child_docname].forEach(d => { - dialog.fields_dict.trans_items.df.data.push({ - "docname": d.name, - "name": d.name, - "item_code": d.item_code, - "delivery_date": d.delivery_date, - "schedule_date": d.schedule_date, - "conversion_factor": d.conversion_factor, - "qty": d.qty, - "rate": d.rate, - "uom": d.uom - }); - this.data = dialog.fields_dict.trans_items.df.data; - dialog.fields_dict.trans_items.grid.refresh(); - }) - dialog.show(); + }).show(); } erpnext.utils.map_current_doc = function(opts) { diff --git a/erpnext/selling/doctype/sales_order/sales_order.py b/erpnext/selling/doctype/sales_order/sales_order.py index accf5f22a6..ca6a51a6f3 100755 --- a/erpnext/selling/doctype/sales_order/sales_order.py +++ b/erpnext/selling/doctype/sales_order/sales_order.py @@ -26,7 +26,7 @@ from erpnext.manufacturing.doctype.production_plan.production_plan import ( from erpnext.selling.doctype.customer.customer import check_credit_limit from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults from erpnext.stock.doctype.item.item import get_item_defaults -from erpnext.stock.get_item_details import get_default_bom +from erpnext.stock.get_item_details import get_default_bom, get_price_list_rate from erpnext.stock.stock_balance import get_reserved_qty, update_bin_qty form_grid_templates = {"items": "templates/form_grid/item_grid.html"} @@ -590,6 +590,23 @@ def make_material_request(source_name, target_doc=None): target.qty = qty - requested_item_qty.get(source.name, 0) target.stock_qty = flt(target.qty) * flt(target.conversion_factor) + args = target.as_dict().copy() + args.update( + { + "company": source_parent.get("company"), + "price_list": frappe.db.get_single_value("Buying Settings", "buying_price_list"), + "currency": source_parent.get("currency"), + "conversion_rate": source_parent.get("conversion_rate"), + } + ) + + target.rate = flt( + get_price_list_rate(args=args, item_doc=frappe.get_cached_doc("Item", target.item_code)).get( + "price_list_rate" + ) + ) + target.amount = target.qty * target.rate + doc = get_mapped_doc( "Sales Order", source_name, diff --git a/erpnext/selling/page/point_of_sale/point_of_sale.py b/erpnext/selling/page/point_of_sale/point_of_sale.py index 999ddc23f0..158ac1d049 100644 --- a/erpnext/selling/page/point_of_sale/point_of_sale.py +++ b/erpnext/selling/page/point_of_sale/point_of_sale.py @@ -17,45 +17,79 @@ from erpnext.stock.utils import scan_barcode def search_by_term(search_term, warehouse, price_list): result = search_for_serial_or_batch_or_barcode_number(search_term) or {} - item_code = result.get("item_code") or search_term - serial_no = result.get("serial_no") or "" - batch_no = result.get("batch_no") or "" - barcode = result.get("barcode") or "" + item_code = result.get("item_code", search_term) + serial_no = result.get("serial_no", "") + batch_no = result.get("batch_no", "") + barcode = result.get("barcode", "") - if result: - item_info = frappe.db.get_value( - "Item", - item_code, - [ - "name as item_code", - "item_name", - "description", - "stock_uom", - "image as item_image", - "is_stock_item", - ], - as_dict=1, - ) + if not result: + return - item_stock_qty, is_stock_item = get_stock_availability(item_code, warehouse) - price_list_rate, currency = frappe.db.get_value( - "Item Price", - {"price_list": price_list, "item_code": item_code}, - ["price_list_rate", "currency"], - ) or [None, None] + item_doc = frappe.get_doc("Item", item_code) - item_info.update( + if not item_doc: + return + + item = { + "barcode": barcode, + "batch_no": batch_no, + "description": item_doc.description, + "is_stock_item": item_doc.is_stock_item, + "item_code": item_doc.name, + "item_image": item_doc.image, + "item_name": item_doc.item_name, + "serial_no": serial_no, + "stock_uom": item_doc.stock_uom, + "uom": item_doc.stock_uom, + } + + if barcode: + barcode_info = next(filter(lambda x: x.barcode == barcode, item_doc.get("barcodes", [])), None) + if barcode_info and barcode_info.uom: + uom = next(filter(lambda x: x.uom == barcode_info.uom, item_doc.uoms), {}) + item.update( + { + "uom": barcode_info.uom, + "conversion_factor": uom.get("conversion_factor", 1), + } + ) + + item_stock_qty, is_stock_item = get_stock_availability(item_code, warehouse) + item_stock_qty = item_stock_qty // item.get("conversion_factor") + item.update({"actual_qty": item_stock_qty}) + + price = frappe.get_list( + doctype="Item Price", + filters={ + "price_list": price_list, + "item_code": item_code, + }, + fields=["uom", "stock_uom", "currency", "price_list_rate"], + ) + + def __sort(p): + p_uom = p.get("uom") + + if p_uom == item.get("uom"): + return 0 + elif p_uom == item.get("stock_uom"): + return 1 + else: + return 2 + + # sort by fallback preference. always pick exact uom match if available + price = sorted(price, key=__sort) + + if len(price) > 0: + p = price.pop(0) + item.update( { - "serial_no": serial_no, - "batch_no": batch_no, - "barcode": barcode, - "price_list_rate": price_list_rate, - "currency": currency, - "actual_qty": item_stock_qty, + "currency": p.get("currency"), + "price_list_rate": p.get("price_list_rate"), } ) - return {"items": [item_info]} + return {"items": [item]} @frappe.whitelist() @@ -121,33 +155,43 @@ def get_items(start, page_length, price_list, item_group, pos_profile, search_te as_dict=1, ) - if items_data: - items = [d.item_code for d in items_data] - item_prices_data = frappe.get_all( + # return (empty) list if there are no results + if not items_data: + return result + + for item in items_data: + uoms = frappe.get_doc("Item", item.item_code).get("uoms", []) + + item.actual_qty, _ = get_stock_availability(item.item_code, warehouse) + item.uom = item.stock_uom + + item_price = frappe.get_all( "Item Price", - fields=["item_code", "price_list_rate", "currency"], - filters={"price_list": price_list, "item_code": ["in", items]}, + fields=["price_list_rate", "currency", "uom"], + filters={ + "price_list": price_list, + "item_code": item.item_code, + "selling": True, + }, ) - item_prices = {} - for d in item_prices_data: - item_prices[d.item_code] = d + if not item_price: + result.append(item) - for item in items_data: - item_code = item.item_code - item_price = item_prices.get(item_code) or {} - item_stock_qty, is_stock_item = get_stock_availability(item_code, warehouse) + for price in item_price: + uom = next(filter(lambda x: x.uom == price.uom, uoms), {}) - row = {} - row.update(item) - row.update( + if price.uom != item.stock_uom and uom and uom.conversion_factor: + item.actual_qty = item.actual_qty // uom.conversion_factor + + result.append( { - "price_list_rate": item_price.get("price_list_rate"), - "currency": item_price.get("currency"), - "actual_qty": item_stock_qty, + **item, + "price_list_rate": price.get("price_list_rate"), + "currency": price.get("currency"), + "uom": price.uom or item.uom, } ) - result.append(row) return {"items": result} diff --git a/erpnext/selling/page/point_of_sale/pos_controller.js b/erpnext/selling/page/point_of_sale/pos_controller.js index 595b9196e8..c442774d0f 100644 --- a/erpnext/selling/page/point_of_sale/pos_controller.js +++ b/erpnext/selling/page/point_of_sale/pos_controller.js @@ -542,12 +542,12 @@ erpnext.PointOfSale.Controller = class { if (!this.frm.doc.customer) return this.raise_customer_selection_alert(); - const { item_code, batch_no, serial_no, rate } = item; + const { item_code, batch_no, serial_no, rate, uom } = item; if (!item_code) return; - const new_item = { item_code, batch_no, rate, [field]: value }; + const new_item = { item_code, batch_no, rate, uom, [field]: value }; if (serial_no) { await this.check_serial_no_availablilty(item_code, this.frm.doc.set_warehouse, serial_no); @@ -649,6 +649,7 @@ erpnext.PointOfSale.Controller = class { const is_stock_item = resp[1]; frappe.dom.unfreeze(); + const bold_uom = item_row.stock_uom.bold(); const bold_item_code = item_row.item_code.bold(); const bold_warehouse = warehouse.bold(); const bold_available_qty = available_qty.toString().bold() @@ -664,7 +665,7 @@ erpnext.PointOfSale.Controller = class { } } else if (is_stock_item && available_qty < qty_needed) { frappe.throw({ - message: __('Stock quantity not enough for Item Code: {0} under warehouse {1}. Available quantity {2}.', [bold_item_code, bold_warehouse, bold_available_qty]), + message: __('Stock quantity not enough for Item Code: {0} under warehouse {1}. Available quantity {2} {3}.', [bold_item_code, bold_warehouse, bold_available_qty, bold_uom]), indicator: 'orange' }); frappe.utils.play_sound("error"); diff --git a/erpnext/selling/page/point_of_sale/pos_item_cart.js b/erpnext/selling/page/point_of_sale/pos_item_cart.js index e7dd211c0f..12cc629776 100644 --- a/erpnext/selling/page/point_of_sale/pos_item_cart.js +++ b/erpnext/selling/page/point_of_sale/pos_item_cart.js @@ -609,7 +609,7 @@ erpnext.PointOfSale.ItemCart = class { if (item_data.rate && item_data.amount && item_data.rate !== item_data.amount) { return `