Merge pull request #29654 from alyf-de/revert-bu-schluessel
revert: BU Schlüssel (a21f76f)
diff --git a/.github/helper/install.sh b/.github/helper/install.sh
index eab6d50..859146b 100644
--- a/.github/helper/install.sh
+++ b/.github/helper/install.sh
@@ -40,10 +40,14 @@
echo "travis" | psql -h 127.0.0.1 -p 5432 -c "CREATE USER test_frappe WITH PASSWORD 'test_frappe'" -U postgres;
fi
-wget -O /tmp/wkhtmltox.tar.xz https://github.com/frappe/wkhtmltopdf/raw/master/wkhtmltox-0.12.3_linux-generic-amd64.tar.xz
-tar -xf /tmp/wkhtmltox.tar.xz -C /tmp
-sudo mv /tmp/wkhtmltox/bin/wkhtmltopdf /usr/local/bin/wkhtmltopdf
-sudo chmod o+x /usr/local/bin/wkhtmltopdf
+
+install_whktml() {
+ wget -O /tmp/wkhtmltox.tar.xz https://github.com/frappe/wkhtmltopdf/raw/master/wkhtmltox-0.12.3_linux-generic-amd64.tar.xz
+ tar -xf /tmp/wkhtmltox.tar.xz -C /tmp
+ sudo mv /tmp/wkhtmltox/bin/wkhtmltopdf /usr/local/bin/wkhtmltopdf
+ sudo chmod o+x /usr/local/bin/wkhtmltopdf
+}
+install_whktml &
cd ~/frappe-bench || exit
@@ -57,5 +61,5 @@
if [ "$TYPE" == "server" ]; then bench setup requirements --dev; fi
bench start &> bench_run_logs.txt &
+CI=Yes bench build --app frappe &
bench --site test_site reinstall --yes
-bench build --app frappe
diff --git a/.github/stale.yml b/.github/stale.yml
index 8b7cb9b..1c2dcf3 100644
--- a/.github/stale.yml
+++ b/.github/stale.yml
@@ -30,6 +30,7 @@
exemptLabels:
- valid
- to-validate
+ - QA
markComment: >
This issue has been automatically marked as inactive because it has not had
recent activity and it wasn't validated by maintainer team. It will be
diff --git a/.mergify.yml b/.mergify.yml
index f3d0409..b7d1df4 100644
--- a/.mergify.yml
+++ b/.mergify.yml
@@ -14,9 +14,39 @@
close:
comment:
message: |
- @{{author}}, thanks for the contribution, but we do not accept pull requests on a stable branch. Please raise PR on an appropriate hotfix branch.
+ @{{author}}, thanks for the contribution, but we do not accept pull requests on a stable branch. Please raise PR on an appropriate hotfix branch.
https://github.com/frappe/erpnext/wiki/Pull-Request-Checklist#which-branch
+ - name: backport to develop
+ conditions:
+ - label="backport develop"
+ actions:
+ backport:
+ branches:
+ - develop
+ assignees:
+ - "{{ author }}"
+
+ - name: backport to version-14-hotfix
+ conditions:
+ - label="backport version-14-hotfix"
+ actions:
+ backport:
+ branches:
+ - version-14-hotfix
+ assignees:
+ - "{{ author }}"
+
+ - name: backport to version-14-pre-release
+ conditions:
+ - label="backport version-14-pre-release"
+ actions:
+ backport:
+ branches:
+ - version-14-pre-release
+ assignees:
+ - "{{ author }}"
+
- name: backport to version-13-hotfix
conditions:
- label="backport version-13-hotfix"
@@ -55,4 +85,4 @@
branches:
- version-12-pre-release
assignees:
- - "{{ author }}"
\ No newline at end of file
+ - "{{ author }}"
diff --git a/cypress/integration/test_bulk_transaction_processing.js b/cypress/integration/test_bulk_transaction_processing.js
new file mode 100644
index 0000000..428ec51
--- /dev/null
+++ b/cypress/integration/test_bulk_transaction_processing.js
@@ -0,0 +1,44 @@
+describe("Bulk Transaction Processing", () => {
+ before(() => {
+ cy.login();
+ cy.visit("/app/website");
+ });
+
+ it("Creates To Sales Order", () => {
+ cy.visit("/app/sales-order");
+ cy.url().should("include", "/sales-order");
+ cy.window()
+ .its("frappe.csrf_token")
+ .then((csrf_token) => {
+ return cy
+ .request({
+ url: "/api/method/erpnext.tests.ui_test_bulk_transaction_processing.create_records",
+ method: "POST",
+ headers: {
+ Accept: "application/json",
+ "Content-Type": "application/json",
+ "X-Frappe-CSRF-Token": csrf_token,
+ },
+ timeout: 60000,
+ })
+ .then((res) => {
+ expect(res.status).eq(200);
+ });
+ });
+ cy.wait(5000);
+ cy.get(
+ ".list-row-head > .list-header-subject > .list-row-col > .list-check-all"
+ ).check({ force: true });
+ cy.wait(3000);
+ cy.get(".actions-btn-group > .btn-primary").click({ force: true });
+ cy.wait(3000);
+ cy.get(".dropdown-menu-right > .user-action > .dropdown-item")
+ .contains("Sales Invoice")
+ .click({ force: true });
+ cy.wait(3000);
+ cy.get(".modal-content > .modal-footer > .standard-actions")
+ .contains("Yes")
+ .click({ force: true });
+ cy.contains("Creation of Sales Invoice successful");
+ });
+});
diff --git a/erpnext/__init__.py b/erpnext/__init__.py
index 0b4696c..dcfad1f 100644
--- a/erpnext/__init__.py
+++ b/erpnext/__init__.py
@@ -2,8 +2,6 @@
import frappe
-from erpnext.hooks import regional_overrides
-
__version__ = '14.0.0-dev'
def get_default_company(user=None):
@@ -121,20 +119,15 @@
@erpnext.allow_regional
def myfunction():
pass'''
+
def caller(*args, **kwargs):
- region = get_region()
- fn_name = inspect.getmodule(fn).__name__ + '.' + fn.__name__
- if region in regional_overrides and fn_name in regional_overrides[region]:
- return frappe.get_attr(regional_overrides[region][fn_name])(*args, **kwargs)
- else:
+ overrides = frappe.get_hooks("regional_overrides", {}).get(get_region())
+ function_path = f"{inspect.getmodule(fn).__name__}.{fn.__name__}"
+
+ if not overrides or function_path not in overrides:
return fn(*args, **kwargs)
+ # Priority given to last installed app
+ return frappe.get_attr(overrides[function_path][-1])(*args, **kwargs)
+
return caller
-
-def get_last_membership(member):
- '''Returns last membership if exists'''
- last_membership = frappe.get_all('Membership', 'name,to_date,membership_type',
- dict(member=member, paid=1), order_by='to_date desc', limit=1)
-
- if last_membership:
- return last_membership[0]
diff --git a/erpnext/accounts/deferred_revenue.py b/erpnext/accounts/deferred_revenue.py
index 9e2cdff..ab1061b 100644
--- a/erpnext/accounts/deferred_revenue.py
+++ b/erpnext/accounts/deferred_revenue.py
@@ -120,6 +120,7 @@
prev_gl_entry = frappe.db.sql('''
select name, posting_date from `tabGL Entry` where company=%s and account=%s and
voucher_type=%s and voucher_no=%s and voucher_detail_no=%s
+ and is_cancelled = 0
order by posting_date desc limit 1
''', (doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name), as_dict=True)
@@ -227,6 +228,7 @@
gl_entries_details = frappe.db.sql('''
select sum({0}) as total_credit, sum({1}) as total_credit_in_account_currency, voucher_detail_no
from `tabGL Entry` where company=%s and account=%s and voucher_type=%s and voucher_no=%s and voucher_detail_no=%s
+ and is_cancelled = 0
group by voucher_detail_no
'''.format(total_credit_debit, total_credit_debit_currency),
(doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name), as_dict=True)
@@ -282,7 +284,7 @@
return
# check if books nor frozen till endate:
- if getdate(end_date) >= getdate(accounts_frozen_upto):
+ if accounts_frozen_upto and (end_date) <= getdate(accounts_frozen_upto):
end_date = get_last_day(add_days(accounts_frozen_upto, 1))
if via_journal_entry:
diff --git a/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.js b/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.js
index 335f850..46ba27c 100644
--- a/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.js
+++ b/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.js
@@ -14,6 +14,10 @@
});
},
+ onload: function (frm) {
+ frm.trigger('bank_account');
+ },
+
refresh: function (frm) {
frappe.require("bank-reconciliation-tool.bundle.js", () =>
frm.trigger("make_reconciliation_tool")
@@ -51,7 +55,7 @@
bank_account: function (frm) {
frappe.db.get_value(
"Bank Account",
- frm.bank_account,
+ frm.doc.bank_account,
"account",
(r) => {
frappe.db.get_value(
@@ -60,6 +64,7 @@
"account_currency",
(r) => {
frm.currency = r.account_currency;
+ frm.trigger("render_chart");
}
);
}
@@ -124,7 +129,7 @@
}
},
- render_chart(frm) {
+ render_chart: frappe.utils.debounce((frm) => {
frm.cards_manager = new erpnext.accounts.bank_reconciliation.NumberCardManager(
{
$reconciliation_tool_cards: frm.get_field(
@@ -136,7 +141,7 @@
currency: frm.currency,
}
);
- },
+ }, 500),
render(frm) {
if (frm.doc.bank_account) {
diff --git a/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py b/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py
index 4211bd0..f3351dd 100644
--- a/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py
+++ b/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py
@@ -7,6 +7,7 @@
import frappe
from frappe import _
from frappe.model.document import Document
+from frappe.query_builder.custom import ConstantColumn
from frappe.utils import flt
from erpnext import get_company_currency
@@ -275,6 +276,10 @@
}
matching_vouchers = []
+
+ matching_vouchers.extend(get_loan_vouchers(bank_account, transaction,
+ document_types, filters))
+
for query in subquery:
matching_vouchers.extend(
frappe.db.sql(query, filters,)
@@ -311,6 +316,114 @@
return queries
+def get_loan_vouchers(bank_account, transaction, document_types, filters):
+ vouchers = []
+ amount_condition = True if "exact_match" in document_types else False
+
+ if transaction.withdrawal > 0 and "loan_disbursement" in document_types:
+ vouchers.extend(get_ld_matching_query(bank_account, amount_condition, filters))
+
+ if transaction.deposit > 0 and "loan_repayment" in document_types:
+ vouchers.extend(get_lr_matching_query(bank_account, amount_condition, filters))
+
+ return vouchers
+
+def get_ld_matching_query(bank_account, amount_condition, filters):
+ loan_disbursement = frappe.qb.DocType("Loan Disbursement")
+ matching_reference = loan_disbursement.reference_number == filters.get("reference_number")
+ matching_party = loan_disbursement.applicant_type == filters.get("party_type") and \
+ loan_disbursement.applicant == filters.get("party")
+
+ rank = (
+ frappe.qb.terms.Case()
+ .when(matching_reference, 1)
+ .else_(0)
+ )
+
+ rank1 = (
+ frappe.qb.terms.Case()
+ .when(matching_party, 1)
+ .else_(0)
+ )
+
+ query = frappe.qb.from_(loan_disbursement).select(
+ rank + rank1 + 1,
+ ConstantColumn("Loan Disbursement").as_("doctype"),
+ loan_disbursement.name,
+ loan_disbursement.disbursed_amount,
+ loan_disbursement.reference_number,
+ loan_disbursement.reference_date,
+ loan_disbursement.applicant_type,
+ loan_disbursement.disbursement_date
+ ).where(
+ loan_disbursement.docstatus == 1
+ ).where(
+ loan_disbursement.clearance_date.isnull()
+ ).where(
+ loan_disbursement.disbursement_account == bank_account
+ )
+
+ if amount_condition:
+ query.where(
+ loan_disbursement.disbursed_amount == filters.get('amount')
+ )
+ else:
+ query.where(
+ loan_disbursement.disbursed_amount <= filters.get('amount')
+ )
+
+ vouchers = query.run(as_list=True)
+
+ return vouchers
+
+def get_lr_matching_query(bank_account, amount_condition, filters):
+ loan_repayment = frappe.qb.DocType("Loan Repayment")
+ matching_reference = loan_repayment.reference_number == filters.get("reference_number")
+ matching_party = loan_repayment.applicant_type == filters.get("party_type") and \
+ loan_repayment.applicant == filters.get("party")
+
+ rank = (
+ frappe.qb.terms.Case()
+ .when(matching_reference, 1)
+ .else_(0)
+ )
+
+ rank1 = (
+ frappe.qb.terms.Case()
+ .when(matching_party, 1)
+ .else_(0)
+ )
+
+ query = frappe.qb.from_(loan_repayment).select(
+ rank + rank1 + 1,
+ ConstantColumn("Loan Repayment").as_("doctype"),
+ loan_repayment.name,
+ loan_repayment.amount_paid,
+ loan_repayment.reference_number,
+ loan_repayment.reference_date,
+ loan_repayment.applicant_type,
+ loan_repayment.posting_date
+ ).where(
+ loan_repayment.docstatus == 1
+ ).where(
+ loan_repayment.clearance_date.isnull()
+ ).where(
+ loan_repayment.payment_account == bank_account
+ )
+
+ if amount_condition:
+ query.where(
+ loan_repayment.amount_paid == filters.get('amount')
+ )
+ else:
+ query.where(
+ loan_repayment.amount_paid <= filters.get('amount')
+ )
+
+ vouchers = query.run()
+
+ return vouchers
+
def get_pe_matching_query(amount_condition, account_from_to, transaction):
# get matching payment entries query
if transaction.deposit > 0:
@@ -348,7 +461,6 @@
# We have mapping at the bank level
# So one bank could have both types of bank accounts like asset and liability
# So cr_or_dr should be judged only on basis of withdrawal and deposit and not account type
- company_account = frappe.get_value("Bank Account", transaction.bank_account, "account")
cr_or_dr = "credit" if transaction.withdrawal > 0 else "debit"
return f"""
diff --git a/erpnext/accounts/doctype/bank_transaction/bank_transaction.py b/erpnext/accounts/doctype/bank_transaction/bank_transaction.py
index 51e1d6e..a476cab 100644
--- a/erpnext/accounts/doctype/bank_transaction/bank_transaction.py
+++ b/erpnext/accounts/doctype/bank_transaction/bank_transaction.py
@@ -49,7 +49,8 @@
def clear_linked_payment_entries(self, for_cancel=False):
for payment_entry in self.payment_entries:
- if payment_entry.payment_document in ["Payment Entry", "Journal Entry", "Purchase Invoice", "Expense Claim"]:
+ if payment_entry.payment_document in ["Payment Entry", "Journal Entry", "Purchase Invoice", "Expense Claim", "Loan Repayment",
+ "Loan Disbursement"]:
self.clear_simple_entry(payment_entry, for_cancel=for_cancel)
elif payment_entry.payment_document == "Sales Invoice":
@@ -116,11 +117,18 @@
payment_entry.payment_entry, paid_amount_field)
elif payment_entry.payment_document == "Journal Entry":
- return frappe.db.get_value('Journal Entry Account', {'parent': payment_entry.payment_entry, 'account': bank_account}, "sum(credit_in_account_currency)")
+ return frappe.db.get_value('Journal Entry Account', {'parent': payment_entry.payment_entry, 'account': bank_account},
+ "sum(credit_in_account_currency)")
elif payment_entry.payment_document == "Expense Claim":
return frappe.db.get_value(payment_entry.payment_document, payment_entry.payment_entry, "total_amount_reimbursed")
+ elif payment_entry.payment_document == "Loan Disbursement":
+ return frappe.db.get_value(payment_entry.payment_document, payment_entry.payment_entry, "disbursed_amount")
+
+ elif payment_entry.payment_document == "Loan Repayment":
+ return frappe.db.get_value(payment_entry.payment_document, payment_entry.payment_entry, "amount_paid")
+
else:
frappe.throw("Please reconcile {0}: {1} manually".format(payment_entry.payment_document, payment_entry.payment_entry))
diff --git a/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py b/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py
index 72b6893..d84b8e0 100644
--- a/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py
+++ b/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py
@@ -109,7 +109,7 @@
frappe.get_doc({
"doctype": "Bank",
"bank_name":bank_name,
- }).insert()
+ }).insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
@@ -119,7 +119,7 @@
"account_name":"Checking Account",
"bank": bank_name,
"account": account_name
- }).insert()
+ }).insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
@@ -184,7 +184,7 @@
"supplier_group":"All Supplier Groups",
"supplier_type": "Company",
"supplier_name": "Conrad Electronic"
- }).insert()
+ }).insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
@@ -203,7 +203,7 @@
"supplier_group":"All Supplier Groups",
"supplier_type": "Company",
"supplier_name": "Mr G"
- }).insert()
+ }).insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
@@ -227,7 +227,7 @@
"supplier_group":"All Supplier Groups",
"supplier_type": "Company",
"supplier_name": "Poore Simon's"
- }).insert()
+ }).insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
@@ -237,7 +237,7 @@
"customer_group":"All Customer Groups",
"customer_type": "Company",
"customer_name": "Poore Simon's"
- }).insert()
+ }).insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
@@ -266,7 +266,7 @@
"customer_group":"All Customer Groups",
"customer_type": "Company",
"customer_name": "Fayva"
- }).insert()
+ }).insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
diff --git a/erpnext/accounts/doctype/cash_flow_mapping_template_details/cash_flow_mapping_template_details.json b/erpnext/accounts/doctype/cash_flow_mapping_template_details/cash_flow_mapping_template_details.json
index 22cf797..02c6875 100644
--- a/erpnext/accounts/doctype/cash_flow_mapping_template_details/cash_flow_mapping_template_details.json
+++ b/erpnext/accounts/doctype/cash_flow_mapping_template_details/cash_flow_mapping_template_details.json
@@ -1,94 +1,34 @@
{
- "allow_copy": 0,
- "allow_guest_to_view": 0,
- "allow_import": 0,
- "allow_rename": 0,
- "autoname": "field:mapping",
- "beta": 0,
- "creation": "2018-02-08 10:18:48.513608",
- "custom": 0,
- "docstatus": 0,
- "doctype": "DocType",
- "document_type": "",
- "editable_grid": 1,
- "engine": "InnoDB",
+ "actions": [],
+ "creation": "2018-02-08 10:18:48.513608",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+ "mapping"
+ ],
"fields": [
{
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "mapping",
- "fieldtype": "Link",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Mapping",
- "length": 0,
- "no_copy": 0,
- "options": "Cash Flow Mapping",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
+ "fieldname": "mapping",
+ "fieldtype": "Link",
+ "in_list_view": 1,
+ "label": "Mapping",
+ "options": "Cash Flow Mapping",
+ "reqd": 1,
+ "unique": 1
}
- ],
- "has_web_view": 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": "2018-02-08 10:33:39.413930",
- "modified_by": "Administrator",
- "module": "Accounts",
- "name": "Cash Flow Mapping Template Details",
- "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": "System Manager",
- "set_user_permissions": 0,
- "share": 1,
- "submit": 0,
- "write": 1
- }
- ],
- "quick_entry": 1,
- "read_only": 0,
- "read_only_onload": 0,
- "show_name_in_global_search": 0,
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_changes": 1,
- "track_seen": 0
+ ],
+ "istable": 1,
+ "links": [],
+ "modified": "2022-02-21 03:34:57.902332",
+ "modified_by": "Administrator",
+ "module": "Accounts",
+ "name": "Cash Flow Mapping Template Details",
+ "owner": "Administrator",
+ "permissions": [],
+ "quick_entry": 1,
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "states": [],
+ "track_changes": 1
}
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/opening_invoice_creation_tool/opening_invoice_creation_tool.py b/erpnext/accounts/doctype/opening_invoice_creation_tool/opening_invoice_creation_tool.py
index 19d8d49..6e7b80e 100644
--- a/erpnext/accounts/doctype/opening_invoice_creation_tool/opening_invoice_creation_tool.py
+++ b/erpnext/accounts/doctype/opening_invoice_creation_tool/opening_invoice_creation_tool.py
@@ -166,8 +166,9 @@
frappe.scrub(row.party_type): row.party,
"is_pos": 0,
"doctype": "Sales Invoice" if self.invoice_type == "Sales" else "Purchase Invoice",
- "update_stock": 0,
- "invoice_number": row.invoice_number
+ "update_stock": 0, # important: https://github.com/frappe/erpnext/pull/23559
+ "invoice_number": row.invoice_number,
+ "disable_rounded_total": 1
})
accounting_dimension = get_accounting_dimensions()
diff --git a/erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py b/erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py
index 6700e9b..77d54a6 100644
--- a/erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py
+++ b/erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py
@@ -1,11 +1,8 @@
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
-import unittest
-
import frappe
-from frappe.cache_manager import clear_doctype_cache
-from frappe.custom.doctype.property_setter.property_setter import make_property_setter
+from frappe.tests.utils import FrappeTestCase
from erpnext.accounts.doctype.accounting_dimension.test_accounting_dimension import (
create_dimension,
@@ -17,11 +14,13 @@
test_dependencies = ["Customer", "Supplier", "Accounting Dimension"]
-class TestOpeningInvoiceCreationTool(unittest.TestCase):
- def setUp(self):
+class TestOpeningInvoiceCreationTool(FrappeTestCase):
+ @classmethod
+ def setUpClass(self):
if not frappe.db.exists("Company", "_Test Opening Invoice Company"):
make_company()
create_dimension()
+ return super().setUpClass()
def make_invoices(self, invoice_type="Sales", company=None, party_1=None, party_2=None, invoice_number=None, department=None):
doc = frappe.get_single("Opening Invoice Creation Tool")
@@ -31,26 +30,20 @@
return doc.make_invoices()
def test_opening_sales_invoice_creation(self):
- property_setter = make_property_setter("Sales Invoice", "update_stock", "default", 1, "Check")
- try:
- invoices = self.make_invoices(company="_Test Opening Invoice Company")
+ invoices = self.make_invoices(company="_Test Opening Invoice Company")
- self.assertEqual(len(invoices), 2)
- expected_value = {
- "keys": ["customer", "outstanding_amount", "status"],
- 0: ["_Test Customer", 300, "Overdue"],
- 1: ["_Test Customer 1", 250, "Overdue"],
- }
- self.check_expected_values(invoices, expected_value)
+ self.assertEqual(len(invoices), 2)
+ expected_value = {
+ "keys": ["customer", "outstanding_amount", "status"],
+ 0: ["_Test Customer", 300, "Overdue"],
+ 1: ["_Test Customer 1", 250, "Overdue"],
+ }
+ self.check_expected_values(invoices, expected_value)
- si = frappe.get_doc("Sales Invoice", invoices[0])
+ si = frappe.get_doc("Sales Invoice", invoices[0])
- # Check if update stock is not enabled
- self.assertEqual(si.update_stock, 0)
-
- finally:
- property_setter.delete()
- clear_doctype_cache("Sales Invoice")
+ # Check if update stock is not enabled
+ self.assertEqual(si.update_stock, 0)
def check_expected_values(self, invoices, expected_value, invoice_type="Sales"):
doctype = "Sales Invoice" if invoice_type == "Sales" else "Purchase Invoice"
diff --git a/erpnext/accounts/doctype/payment_entry/payment_entry.js b/erpnext/accounts/doctype/payment_entry/payment_entry.js
index 3be3925..b2b818a 100644
--- a/erpnext/accounts/doctype/payment_entry/payment_entry.js
+++ b/erpnext/accounts/doctype/payment_entry/payment_entry.js
@@ -114,8 +114,6 @@
var doctypes = ["Expense Claim", "Journal Entry"];
} else if (frm.doc.party_type == "Student") {
var doctypes = ["Fees"];
- } else if (frm.doc.party_type == "Donor") {
- var doctypes = ["Donation"];
} else {
var doctypes = ["Journal Entry"];
}
@@ -144,7 +142,7 @@
const child = locals[cdt][cdn];
const filters = {"docstatus": 1, "company": doc.company};
const party_type_doctypes = ['Sales Invoice', 'Sales Order', 'Purchase Invoice',
- 'Purchase Order', 'Expense Claim', 'Fees', 'Dunning', 'Donation'];
+ 'Purchase Order', 'Expense Claim', 'Fees', 'Dunning'];
if (in_list(party_type_doctypes, child.reference_doctype)) {
filters[doc.party_type.toLowerCase()] = doc.party;
@@ -196,8 +194,14 @@
frm.doc.paid_from_account_currency != frm.doc.paid_to_account_currency));
frm.toggle_display("base_paid_amount", frm.doc.paid_from_account_currency != company_currency);
- frm.toggle_display("base_total_taxes_and_charges", frm.doc.total_taxes_and_charges &&
- (frm.doc.paid_from_account_currency != company_currency));
+
+ if (frm.doc.payment_type == "Pay") {
+ frm.toggle_display("base_total_taxes_and_charges", frm.doc.total_taxes_and_charges &&
+ (frm.doc.paid_to_account_currency != company_currency));
+ } else {
+ frm.toggle_display("base_total_taxes_and_charges", frm.doc.total_taxes_and_charges &&
+ (frm.doc.paid_from_account_currency != company_currency));
+ }
frm.toggle_display("base_received_amount", (
frm.doc.paid_to_account_currency != company_currency
@@ -232,7 +236,8 @@
var company_currency = frm.doc.company? frappe.get_doc(":Company", frm.doc.company).default_currency: "";
frm.set_currency_labels(["base_paid_amount", "base_received_amount", "base_total_allocated_amount",
- "difference_amount", "base_paid_amount_after_tax", "base_received_amount_after_tax"], company_currency);
+ "difference_amount", "base_paid_amount_after_tax", "base_received_amount_after_tax",
+ "base_total_taxes_and_charges"], company_currency);
frm.set_currency_labels(["paid_amount"], frm.doc.paid_from_account_currency);
frm.set_currency_labels(["received_amount"], frm.doc.paid_to_account_currency);
@@ -341,6 +346,8 @@
}
frm.set_party_account_based_on_party = true;
+ let company_currency = frappe.get_doc(":Company", frm.doc.company).default_currency;
+
return frappe.call({
method: "erpnext.accounts.doctype.payment_entry.payment_entry.get_party_details",
args: {
@@ -374,7 +381,11 @@
if (r.message.bank_account) {
frm.set_value("bank_account", r.message.bank_account);
}
- }
+ },
+ () => frm.events.set_current_exchange_rate(frm, "source_exchange_rate",
+ frm.doc.paid_from_account_currency, company_currency),
+ () => frm.events.set_current_exchange_rate(frm, "target_exchange_rate",
+ frm.doc.paid_to_account_currency, company_currency)
]);
}
}
@@ -478,14 +489,14 @@
},
paid_from_account_currency: function(frm) {
- if(!frm.doc.paid_from_account_currency) return;
- var company_currency = frappe.get_doc(":Company", frm.doc.company).default_currency;
+ if(!frm.doc.paid_from_account_currency || !frm.doc.company) return;
+ let company_currency = frappe.get_doc(":Company", frm.doc.company).default_currency;
if (frm.doc.paid_from_account_currency == company_currency) {
frm.set_value("source_exchange_rate", 1);
} else if (frm.doc.paid_from){
if (in_list(["Internal Transfer", "Pay"], frm.doc.payment_type)) {
- var company_currency = frappe.get_doc(":Company", frm.doc.company).default_currency;
+ let company_currency = frappe.get_doc(":Company", frm.doc.company).default_currency;
frappe.call({
method: "erpnext.setup.utils.get_exchange_rate",
args: {
@@ -505,8 +516,8 @@
},
paid_to_account_currency: function(frm) {
- if(!frm.doc.paid_to_account_currency) return;
- var company_currency = frappe.get_doc(":Company", frm.doc.company).default_currency;
+ if(!frm.doc.paid_to_account_currency || !frm.doc.company) return;
+ let company_currency = frappe.get_doc(":Company", frm.doc.company).default_currency;
frm.events.set_current_exchange_rate(frm, "target_exchange_rate",
frm.doc.paid_to_account_currency, company_currency);
@@ -747,8 +758,7 @@
(frm.doc.payment_type=="Receive" && frm.doc.party_type=="Customer") ||
(frm.doc.payment_type=="Pay" && frm.doc.party_type=="Supplier") ||
(frm.doc.payment_type=="Pay" && frm.doc.party_type=="Employee") ||
- (frm.doc.payment_type=="Receive" && frm.doc.party_type=="Student") ||
- (frm.doc.payment_type=="Receive" && frm.doc.party_type=="Donor")
+ (frm.doc.payment_type=="Receive" && frm.doc.party_type=="Student")
) {
if(total_positive_outstanding > total_negative_outstanding)
if (!frm.doc.paid_amount)
@@ -791,8 +801,7 @@
(frm.doc.payment_type=="Receive" && frm.doc.party_type=="Customer") ||
(frm.doc.payment_type=="Pay" && frm.doc.party_type=="Supplier") ||
(frm.doc.payment_type=="Pay" && frm.doc.party_type=="Employee") ||
- (frm.doc.payment_type=="Receive" && frm.doc.party_type=="Student") ||
- (frm.doc.payment_type=="Receive" && frm.doc.party_type=="Donor")
+ (frm.doc.payment_type=="Receive" && frm.doc.party_type=="Student")
) {
if(total_positive_outstanding_including_order > paid_amount) {
var remaining_outstanding = total_positive_outstanding_including_order - paid_amount;
@@ -951,12 +960,6 @@
frappe.msgprint(__("Row #{0}: Reference Document Type must be one of Expense Claim or Journal Entry", [row.idx]));
return false;
}
-
- if (frm.doc.party_type == "Donor" && row.reference_doctype != "Donation") {
- frappe.model.set_value(row.doctype, row.name, "reference_doctype", null);
- frappe.msgprint(__("Row #{0}: Reference Document Type must be Donation", [row.idx]));
- return false;
- }
}
if (row) {
diff --git a/erpnext/accounts/doctype/payment_entry/payment_entry.json b/erpnext/accounts/doctype/payment_entry/payment_entry.json
index c8d1db9..3fc1adf 100644
--- a/erpnext/accounts/doctype/payment_entry/payment_entry.json
+++ b/erpnext/accounts/doctype/payment_entry/payment_entry.json
@@ -66,7 +66,9 @@
"tax_withholding_category",
"section_break_56",
"taxes",
+ "section_break_60",
"base_total_taxes_and_charges",
+ "column_break_61",
"total_taxes_and_charges",
"deductions_or_loss_section",
"deductions",
@@ -715,12 +717,21 @@
"fieldtype": "Data",
"hidden": 1,
"label": "Paid To Account Type"
+ },
+ {
+ "fieldname": "column_break_61",
+ "fieldtype": "Column Break"
+ },
+ {
+ "fieldname": "section_break_60",
+ "fieldtype": "Section Break",
+ "hide_border": 1
}
],
"index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [],
- "modified": "2021-11-24 18:58:24.919764",
+ "modified": "2022-02-23 20:08:39.559814",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Payment Entry",
@@ -763,6 +774,7 @@
"show_name_in_global_search": 1,
"sort_field": "modified",
"sort_order": "DESC",
+ "states": [],
"title_field": "title",
"track_changes": 1
}
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/payment_entry/payment_entry.py b/erpnext/accounts/doctype/payment_entry/payment_entry.py
index 02a144d..f9f3350 100644
--- a/erpnext/accounts/doctype/payment_entry/payment_entry.py
+++ b/erpnext/accounts/doctype/payment_entry/payment_entry.py
@@ -91,7 +91,6 @@
self.update_expense_claim()
self.update_outstanding_amounts()
self.update_advance_paid()
- self.update_donation()
self.update_payment_schedule()
self.set_status()
@@ -101,7 +100,6 @@
self.update_expense_claim()
self.update_outstanding_amounts()
self.update_advance_paid()
- self.update_donation(cancel=1)
self.delink_advance_entry_references()
self.update_payment_schedule(cancel=1)
self.set_payment_req_status()
@@ -284,8 +282,6 @@
valid_reference_doctypes = ("Expense Claim", "Journal Entry", "Employee Advance", "Gratuity")
elif self.party_type == "Shareholder":
valid_reference_doctypes = ("Journal Entry")
- elif self.party_type == "Donor":
- valid_reference_doctypes = ("Donation")
for d in self.get("references"):
if not d.allocated_amount:
@@ -843,13 +839,6 @@
else:
update_reimbursed_amount(doc, d.allocated_amount)
- def update_donation(self, cancel=0):
- if self.payment_type == "Receive" and self.party_type == "Donor" and self.party:
- for d in self.get("references"):
- if d.reference_doctype=="Donation" and d.reference_name:
- is_paid = 0 if cancel else 1
- frappe.db.set_value("Donation", d.reference_name, "paid", is_paid)
-
def on_recurring(self, reference_doc, auto_repeat_doc):
self.reference_no = reference_doc.name
self.reference_date = nowdate()
@@ -945,8 +934,12 @@
tax.base_total = tax.total * self.source_exchange_rate
- self.total_taxes_and_charges += current_tax_amount
- self.base_total_taxes_and_charges += current_tax_amount * self.source_exchange_rate
+ if self.payment_type == 'Pay':
+ self.base_total_taxes_and_charges += flt(current_tax_amount / self.source_exchange_rate)
+ self.total_taxes_and_charges += flt(current_tax_amount / self.target_exchange_rate)
+ else:
+ self.base_total_taxes_and_charges += flt(current_tax_amount / self.target_exchange_rate)
+ self.total_taxes_and_charges += flt(current_tax_amount / self.source_exchange_rate)
if self.get('taxes'):
self.paid_amount_after_tax = self.get('taxes')[-1].base_total
@@ -1077,7 +1070,7 @@
if d.voucher_type in ("Purchase Invoice"):
d["bill_no"] = frappe.db.get_value(d.voucher_type, d.voucher_no, "bill_no")
- # Get all SO / PO which are not fully billed or aginst which full advance not paid
+ # Get all SO / PO which are not fully billed or against which full advance not paid
orders_to_be_billed = []
if (args.get("party_type") != "Student"):
orders_to_be_billed = get_orders_to_be_billed(args.get("posting_date"),args.get("party_type"),
@@ -1337,10 +1330,6 @@
total_amount = ref_doc.get("grand_total")
exchange_rate = 1
outstanding_amount = ref_doc.get("outstanding_amount")
- elif reference_doctype == "Donation":
- total_amount = ref_doc.get("amount")
- outstanding_amount = total_amount
- exchange_rate = 1
elif reference_doctype == "Dunning":
total_amount = ref_doc.get("dunning_amount")
exchange_rate = 1
@@ -1611,8 +1600,6 @@
party_type = "Employee"
elif dt == "Fees":
party_type = "Student"
- elif dt == "Donation":
- party_type = "Donor"
return party_type
def set_party_account(dt, dn, doc, party_type):
@@ -1640,7 +1627,7 @@
return party_account_currency
def set_payment_type(dt, doc):
- if (dt in ("Sales Order", "Donation") or (dt in ("Sales Invoice", "Fees", "Dunning") and doc.outstanding_amount > 0)) \
+ if (dt == "Sales Order" or (dt in ("Sales Invoice", "Fees", "Dunning") and doc.outstanding_amount > 0)) \
or (dt=="Purchase Invoice" and doc.outstanding_amount < 0):
payment_type = "Receive"
else:
@@ -1673,9 +1660,6 @@
elif dt == "Dunning":
grand_total = doc.grand_total
outstanding_amount = doc.grand_total
- elif dt == "Donation":
- grand_total = doc.amount
- outstanding_amount = doc.amount
elif dt == "Gratuity":
grand_total = doc.amount
outstanding_amount = flt(doc.amount) - flt(doc.paid_amount)
diff --git a/erpnext/accounts/doctype/payment_entry/test_payment_entry.py b/erpnext/accounts/doctype/payment_entry/test_payment_entry.py
index cc3528e..349b8bb 100644
--- a/erpnext/accounts/doctype/payment_entry/test_payment_entry.py
+++ b/erpnext/accounts/doctype/payment_entry/test_payment_entry.py
@@ -633,6 +633,45 @@
self.assertEqual(flt(expected_party_balance), party_balance)
self.assertEqual(flt(expected_party_account_balance), party_account_balance)
+ def test_multi_currency_payment_entry_with_taxes(self):
+ payment_entry = create_payment_entry(party='_Test Supplier USD', paid_to = '_Test Payable USD - _TC',
+ save=True)
+ payment_entry.append('taxes', {
+ 'account_head': '_Test Account Service Tax - _TC',
+ 'charge_type': 'Actual',
+ 'tax_amount': 10,
+ 'add_deduct_tax': 'Add',
+ 'description': 'Test'
+ })
+
+ payment_entry.save()
+ self.assertEqual(payment_entry.base_total_taxes_and_charges, 10)
+ self.assertEqual(flt(payment_entry.total_taxes_and_charges, 2), flt(10 / payment_entry.target_exchange_rate, 2))
+
+def create_payment_entry(**args):
+ payment_entry = frappe.new_doc('Payment Entry')
+ payment_entry.company = args.get('company') or '_Test Company'
+ payment_entry.payment_type = args.get('payment_type') or 'Pay'
+ payment_entry.party_type = args.get('party_type') or 'Supplier'
+ payment_entry.party = args.get('party') or '_Test Supplier'
+ payment_entry.paid_from = args.get('paid_from') or '_Test Bank - _TC'
+ payment_entry.paid_to = args.get('paid_to') or 'Creditors - _TC'
+ payment_entry.paid_amount = args.get('paid_amount') or 1000
+
+ payment_entry.setup_party_account_field()
+ payment_entry.set_missing_values()
+ payment_entry.set_exchange_rate()
+ payment_entry.received_amount = payment_entry.paid_amount / payment_entry.target_exchange_rate
+ payment_entry.reference_no = 'Test001'
+ payment_entry.reference_date = nowdate()
+
+ if args.get('save'):
+ payment_entry.save()
+ if args.get('submit'):
+ payment_entry.submit()
+
+ return payment_entry
+
def create_payment_terms_template():
create_payment_term('Basic Amount Receivable')
diff --git a/erpnext/accounts/doctype/pos_invoice/pos_invoice.py b/erpnext/accounts/doctype/pos_invoice/pos_invoice.py
index 97d34e0..9b3b3aa 100644
--- a/erpnext/accounts/doctype/pos_invoice/pos_invoice.py
+++ b/erpnext/accounts/doctype/pos_invoice/pos_invoice.py
@@ -172,9 +172,10 @@
frappe.throw(error_msg, title=_("Invalid Item"), as_list=True)
def validate_stock_availablility(self):
+ from erpnext.stock.stock_ledger import is_negative_stock_allowed
+
if self.is_return or self.docstatus != 1:
return
- allow_negative_stock = frappe.db.get_single_value('Stock Settings', 'allow_negative_stock')
for d in self.get('items'):
is_service_item = not (frappe.db.get_value('Item', d.get('item_code'), 'is_stock_item'))
if is_service_item:
@@ -186,7 +187,7 @@
elif d.batch_no:
self.validate_pos_reserved_batch_qty(d)
else:
- if allow_negative_stock:
+ if is_negative_stock_allowed(item_code=d.item_code):
return
available_stock, is_stock_item = get_stock_availability(d.item_code, d.warehouse)
@@ -438,7 +439,6 @@
self.paid_amount = 0
def set_account_for_mode_of_payment(self):
- self.payments = [d for d in self.payments if d.amount or d.base_amount or d.default]
for pay in self.payments:
if not pay.account:
pay.account = get_bank_cash_account(pay.mode_of_payment, self.company).get("account")
diff --git a/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py b/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py
index ba751c0..cf8affd 100644
--- a/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py
+++ b/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py
@@ -586,23 +586,29 @@
item_price.insert()
pr = make_pricing_rule(selling=1, priority=5, discount_percentage=10)
pr.save()
- pos_inv = create_pos_invoice(qty=1, do_not_submit=1)
- pos_inv.items[0].rate = 300
- pos_inv.save()
- self.assertEquals(pos_inv.items[0].discount_percentage, 10)
- # rate shouldn't change
- self.assertEquals(pos_inv.items[0].rate, 405)
- pos_inv.ignore_pricing_rule = 1
- pos_inv.items[0].rate = 300
- pos_inv.save()
- self.assertEquals(pos_inv.ignore_pricing_rule, 1)
- # rate should change since pricing rules are ignored
- self.assertEquals(pos_inv.items[0].rate, 300)
+ try:
+ pos_inv = create_pos_invoice(qty=1, do_not_submit=1)
+ pos_inv.items[0].rate = 300
+ pos_inv.save()
+ self.assertEquals(pos_inv.items[0].discount_percentage, 10)
+ # rate shouldn't change
+ self.assertEquals(pos_inv.items[0].rate, 405)
- item_price.delete()
- pos_inv.delete()
- pr.delete()
+ pos_inv.ignore_pricing_rule = 1
+ pos_inv.save()
+ self.assertEquals(pos_inv.ignore_pricing_rule, 1)
+ # rate should reset since pricing rules are ignored
+ self.assertEquals(pos_inv.items[0].rate, 450)
+
+ pos_inv.items[0].rate = 300
+ pos_inv.save()
+ self.assertEquals(pos_inv.items[0].rate, 300)
+
+ finally:
+ item_price.delete()
+ pos_inv.delete()
+ pr.delete()
def create_pos_invoice(**args):
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 0720d9b..d4513c6 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
@@ -135,9 +135,15 @@
i.uom == item.uom and i.net_rate == item.net_rate and i.warehouse == item.warehouse):
found = True
i.qty = i.qty + item.qty
+ i.amount = i.amount + item.net_amount
+ i.net_amount = i.amount
+ i.base_amount = i.base_amount + item.base_net_amount
+ i.base_net_amount = i.base_amount
if not found:
item.rate = item.net_rate
+ item.amount = item.net_amount
+ item.base_amount = item.base_net_amount
item.price_list_rate = 0
si_item = map_child_doc(item, invoice, {"doctype": "Sales Invoice Item"})
items.append(si_item)
@@ -169,6 +175,7 @@
found = True
if not found:
payments.append(payment)
+
rounding_adjustment += doc.rounding_adjustment
rounded_total += doc.rounded_total
base_rounding_adjustment += doc.base_rounding_adjustment
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 3555da8..89f7f18 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 @@
import unittest
import frappe
+from frappe.tests.utils import change_settings
from erpnext.accounts.doctype.pos_closing_entry.test_pos_closing_entry import init_user_and_profile
from erpnext.accounts.doctype.pos_invoice.pos_invoice import make_sales_return
@@ -12,6 +13,7 @@
from erpnext.accounts.doctype.pos_invoice_merge_log.pos_invoice_merge_log import (
consolidate_pos_invoices,
)
+from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
class TestPOSInvoiceMergeLog(unittest.TestCase):
@@ -150,3 +152,229 @@
frappe.set_user("Administrator")
frappe.db.sql("delete from `tabPOS Profile`")
frappe.db.sql("delete from `tabPOS Invoice`")
+
+
+ def test_consolidation_round_off_error_1(self):
+ '''
+ Test round off error in consolidated invoice creation if POS Invoice has inclusive tax
+ '''
+
+ frappe.db.sql("delete from `tabPOS Invoice`")
+
+ try:
+ make_stock_entry(
+ to_warehouse="_Test Warehouse - _TC",
+ item_code="_Test Item",
+ rate=8000,
+ qty=10,
+ )
+
+ init_user_and_profile()
+
+ inv = create_pos_invoice(qty=3, rate=10000, 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": 7.5,
+ "included_in_print_rate": 1
+ })
+ inv.append('payments', {
+ 'mode_of_payment': 'Cash', 'account': 'Cash - _TC', 'amount': 30000
+ })
+ inv.insert()
+ inv.submit()
+
+ inv2 = create_pos_invoice(qty=3, rate=10000, do_not_save=True)
+ 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": 7.5,
+ "included_in_print_rate": 1
+ })
+ inv2.append('payments', {
+ 'mode_of_payment': 'Cash', 'account': 'Cash - _TC', 'amount': 30000
+ })
+ inv2.insert()
+ inv2.submit()
+
+ consolidate_pos_invoices()
+
+ inv.load_from_db()
+ consolidated_invoice = frappe.get_doc('Sales Invoice', inv.consolidated_invoice)
+ self.assertEqual(consolidated_invoice.outstanding_amount, 0)
+ self.assertEqual(consolidated_invoice.status, 'Paid')
+
+ finally:
+ frappe.set_user("Administrator")
+ frappe.db.sql("delete from `tabPOS Profile`")
+ frappe.db.sql("delete from `tabPOS Invoice`")
+
+ def test_consolidation_round_off_error_2(self):
+ '''
+ Test the same case as above but with an Unpaid POS Invoice
+ '''
+ frappe.db.sql("delete from `tabPOS Invoice`")
+
+ try:
+ make_stock_entry(
+ to_warehouse="_Test Warehouse - _TC",
+ item_code="_Test Item",
+ rate=8000,
+ qty=10,
+ )
+
+ init_user_and_profile()
+
+ inv = create_pos_invoice(qty=6, rate=10000, 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": 7.5,
+ "included_in_print_rate": 1
+ })
+ inv.append('payments', {
+ 'mode_of_payment': 'Cash', 'account': 'Cash - _TC', 'amount': 60000
+ })
+ inv.insert()
+ inv.submit()
+
+ inv2 = create_pos_invoice(qty=6, rate=10000, do_not_save=True)
+ 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": 7.5,
+ "included_in_print_rate": 1
+ })
+ inv2.append('payments', {
+ 'mode_of_payment': 'Cash', 'account': 'Cash - _TC', 'amount': 60000
+ })
+ inv2.insert()
+ inv2.submit()
+
+ inv3 = create_pos_invoice(qty=3, rate=600, do_not_save=True)
+ inv3.append('payments', {
+ 'mode_of_payment': 'Cash', 'account': 'Cash - _TC', 'amount': 1000
+ })
+ inv3.insert()
+ inv3.submit()
+
+ consolidate_pos_invoices()
+
+ inv.load_from_db()
+ consolidated_invoice = frappe.get_doc('Sales Invoice', inv.consolidated_invoice)
+ self.assertEqual(consolidated_invoice.outstanding_amount, 800)
+ self.assertNotEqual(consolidated_invoice.status, 'Paid')
+
+ finally:
+ frappe.set_user("Administrator")
+ frappe.db.sql("delete from `tabPOS Profile`")
+ frappe.db.sql("delete from `tabPOS Invoice`")
+
+ @change_settings("System Settings", {"number_format": "#,###.###", "currency_precision": 3, "float_precision": 3})
+ def test_consolidation_round_off_error_3(self):
+ frappe.db.sql("delete from `tabPOS Invoice`")
+
+ try:
+ make_stock_entry(
+ to_warehouse="_Test Warehouse - _TC",
+ item_code="_Test Item",
+ rate=8000,
+ qty=10,
+ )
+ init_user_and_profile()
+
+ item_rates = [69, 59, 29]
+ for i in [1, 2]:
+ inv = create_pos_invoice(is_return=1, do_not_save=1)
+ inv.items = []
+ for rate in item_rates:
+ inv.append("items", {
+ "item_code": "_Test Item",
+ "warehouse": "_Test Warehouse - _TC",
+ "qty": -1,
+ "rate": rate,
+ "income_account": "Sales - _TC",
+ "expense_account": "Cost of Goods Sold - _TC",
+ "cost_center": "_Test Cost Center - _TC",
+ })
+ 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": 15,
+ "included_in_print_rate": 1
+ })
+ inv.payments = []
+ inv.append('payments', {
+ 'mode_of_payment': 'Cash', 'account': 'Cash - _TC', 'amount': -157
+ })
+ inv.paid_amount = -157
+ inv.save()
+ inv.submit()
+
+ consolidate_pos_invoices()
+
+ inv.load_from_db()
+ consolidated_invoice = frappe.get_doc('Sales Invoice', inv.consolidated_invoice)
+ self.assertEqual(consolidated_invoice.status, 'Return')
+ self.assertEqual(consolidated_invoice.rounding_adjustment, -0.001)
+
+ finally:
+ frappe.set_user("Administrator")
+ frappe.db.sql("delete from `tabPOS Profile`")
+ frappe.db.sql("delete from `tabPOS Invoice`")
+
+ def test_consolidation_rounding_adjustment(self):
+ '''
+ Test if the rounding adjustment is calculated correctly
+ '''
+ frappe.db.sql("delete from `tabPOS Invoice`")
+
+ try:
+ make_stock_entry(
+ to_warehouse="_Test Warehouse - _TC",
+ item_code="_Test Item",
+ rate=8000,
+ qty=10,
+ )
+
+ init_user_and_profile()
+
+ inv = create_pos_invoice(qty=1, rate=69.5, do_not_save=True)
+ inv.append('payments', {
+ 'mode_of_payment': 'Cash', 'account': 'Cash - _TC', 'amount': 70
+ })
+ inv.insert()
+ inv.submit()
+
+ inv2 = create_pos_invoice(qty=1, rate=59.5, do_not_save=True)
+ inv2.append('payments', {
+ 'mode_of_payment': 'Cash', 'account': 'Cash - _TC', 'amount': 60
+ })
+ inv2.insert()
+ inv2.submit()
+
+ consolidate_pos_invoices()
+
+ inv.load_from_db()
+ consolidated_invoice = frappe.get_doc('Sales Invoice', inv.consolidated_invoice)
+ self.assertEqual(consolidated_invoice.rounding_adjustment, 1)
+
+ finally:
+ frappe.set_user("Administrator")
+ frappe.db.sql("delete from `tabPOS Profile`")
+ frappe.db.sql("delete from `tabPOS Invoice`")
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/pricing_rule/pricing_rule.py b/erpnext/accounts/doctype/pricing_rule/pricing_rule.py
index ac96b04..933fda8 100644
--- a/erpnext/accounts/doctype/pricing_rule/pricing_rule.py
+++ b/erpnext/accounts/doctype/pricing_rule/pricing_rule.py
@@ -249,13 +249,17 @@
"free_item_data": [],
"parent": args.parent,
"parenttype": args.parenttype,
- "child_docname": args.get('child_docname')
+ "child_docname": args.get('child_docname'),
})
if args.ignore_pricing_rule or not args.item_code:
if frappe.db.exists(args.doctype, args.name) and args.get("pricing_rules"):
- item_details = remove_pricing_rule_for_item(args.get("pricing_rules"),
- item_details, args.get('item_code'))
+ item_details = remove_pricing_rule_for_item(
+ args.get("pricing_rules"),
+ item_details,
+ item_code=args.get("item_code"),
+ rate=args.get("price_list_rate"),
+ )
return item_details
update_args_for_pricing_rule(args)
@@ -308,8 +312,12 @@
if not doc: return item_details
elif args.get("pricing_rules"):
- item_details = remove_pricing_rule_for_item(args.get("pricing_rules"),
- item_details, args.get('item_code'))
+ item_details = remove_pricing_rule_for_item(
+ args.get("pricing_rules"),
+ item_details,
+ item_code=args.get("item_code"),
+ rate=args.get("price_list_rate"),
+ )
return item_details
@@ -390,7 +398,7 @@
item_details[field] += (pricing_rule.get(field, 0)
if pricing_rule else args.get(field, 0))
-def remove_pricing_rule_for_item(pricing_rules, item_details, item_code=None):
+def remove_pricing_rule_for_item(pricing_rules, item_details, item_code=None, rate=None):
from erpnext.accounts.doctype.pricing_rule.utils import (
get_applied_pricing_rules,
get_pricing_rule_items,
@@ -403,6 +411,7 @@
if pricing_rule.rate_or_discount == 'Discount Percentage':
item_details.discount_percentage = 0.0
item_details.discount_amount = 0.0
+ item_details.rate = rate or 0.0
if pricing_rule.rate_or_discount == 'Discount Amount':
item_details.discount_amount = 0.0
@@ -421,6 +430,7 @@
item_details.applied_on_items = ','.join(items)
item_details.pricing_rules = ''
+ item_details.pricing_rule_removed = True
return item_details
@@ -432,9 +442,12 @@
out = []
for item in item_list:
item = frappe._dict(item)
- if item.get('pricing_rules'):
- out.append(remove_pricing_rule_for_item(item.get("pricing_rules"),
- item, item.item_code))
+ if item.get("pricing_rules"):
+ out.append(
+ remove_pricing_rule_for_item(
+ item.get("pricing_rules"), item, item.item_code, item.get("price_list_rate")
+ )
+ )
return out
diff --git a/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py b/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py
index 968137e..8338a5b0 100644
--- a/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py
+++ b/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py
@@ -628,6 +628,46 @@
for doc in [si, si1]:
doc.delete()
+ def test_remove_pricing_rule(self):
+ item = make_item("Water Flask")
+ make_item_price("Water Flask", "_Test Price List", 100)
+
+ pricing_rule_record = {
+ "doctype": "Pricing Rule",
+ "title": "_Test Water Flask Rule",
+ "apply_on": "Item Code",
+ "price_or_product_discount": "Price",
+ "items": [{
+ "item_code": "Water Flask",
+ }],
+ "selling": 1,
+ "currency": "INR",
+ "rate_or_discount": "Discount Percentage",
+ "discount_percentage": 20,
+ "company": "_Test Company"
+ }
+ rule = frappe.get_doc(pricing_rule_record)
+ rule.insert()
+
+ si = create_sales_invoice(do_not_save=True, item_code="Water Flask")
+ si.selling_price_list = "_Test Price List"
+ si.save()
+
+ self.assertEqual(si.items[0].price_list_rate, 100)
+ self.assertEqual(si.items[0].discount_percentage, 20)
+ self.assertEqual(si.items[0].rate, 80)
+
+ si.ignore_pricing_rule = 1
+ si.save()
+
+ self.assertEqual(si.items[0].discount_percentage, 0)
+ self.assertEqual(si.items[0].rate, 100)
+
+ si.delete()
+ rule.delete()
+ frappe.get_doc("Item Price", {"item_code": "Water Flask"}).delete()
+ item.delete()
+
def test_multiple_pricing_rules_with_min_qty(self):
make_pricing_rule(discount_percentage=20, selling=1, priority=1, min_qty=4,
apply_multiple_pricing_rules=1, title="_Test Pricing Rule with Min Qty - 1")
@@ -648,6 +688,7 @@
frappe.delete_doc_if_exists("Pricing Rule", "_Test Pricing Rule with Min Qty - 1")
frappe.delete_doc_if_exists("Pricing Rule", "_Test Pricing Rule with Min Qty - 2")
+
test_dependencies = ["Campaign"]
def make_pricing_rule(**args):
diff --git a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py
index 09aa723..1b34d6d 100644
--- a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py
+++ b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py
@@ -73,7 +73,7 @@
'to_date': doc.to_date,
'company': doc.company,
'finance_book': doc.finance_book if doc.finance_book else None,
- 'account': doc.account if doc.account else None,
+ 'account': [doc.account] if doc.account else None,
'party_type': 'Customer',
'party': [entry.customer],
'presentation_currency': presentation_currency,
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index 76d9cc7..2c31561 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -178,8 +178,8 @@
if self.supplier and account.account_type != "Payable":
frappe.throw(
- _("Please ensure {} account is a Payable account. Change the account type to Payable or select a different account.")
- .format(frappe.bold("Credit To")), title=_("Invalid Account")
+ _("Please ensure {} account {} is a Payable account. Change the account type to Payable or select a different account.")
+ .format(frappe.bold("Credit To"), frappe.bold(self.credit_to)), title=_("Invalid Account")
)
self.party_account_currency = account.account_currency
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice_list.js b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice_list.js
index f6ff83a..82d0030 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice_list.js
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice_list.js
@@ -56,4 +56,14 @@
];
}
},
+
+ onload: function(listview) {
+ listview.page.add_action_item(__("Purchase Receipt"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Purchase Invoice", "Purchase Receipt");
+ });
+
+ listview.page.add_action_item(__("Payment"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Purchase Invoice", "Payment");
+ });
+ }
};
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
index 5062c1c..80b95db 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
@@ -2,7 +2,7 @@
"actions": [],
"allow_import": 1,
"autoname": "naming_series:",
- "creation": "2013-05-24 19:29:05",
+ "creation": "2022-01-25 10:29:57.771398",
"doctype": "DocType",
"engine": "InnoDB",
"field_order": [
@@ -651,7 +651,6 @@
"hide_seconds": 1,
"label": "Ignore Pricing Rule",
"no_copy": 1,
- "permlevel": 0,
"print_hide": 1
},
{
@@ -1974,9 +1973,10 @@
},
{
"default": "0",
+ "description": "Issue a debit note with 0 qty against an existing Sales Invoice",
"fieldname": "is_debit_note",
"fieldtype": "Check",
- "label": "Is Debit Note"
+ "label": "Is Rate Adjustment Entry (Debit Note)"
},
{
"default": "0",
@@ -2038,7 +2038,7 @@
"link_fieldname": "consolidated_invoice"
}
],
- "modified": "2021-12-23 20:19:38.667508",
+ "modified": "2022-03-08 16:08:53.517903",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Sales Invoice",
@@ -2089,8 +2089,9 @@
"show_name_in_global_search": 1,
"sort_field": "modified",
"sort_order": "DESC",
+ "states": [],
"timeline_field": "customer",
"title_field": "title",
"track_changes": 1,
"track_seen": 1
-}
+}
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index bc44358..573da27 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -263,6 +263,9 @@
self.process_common_party_accounting()
def validate_pos_return(self):
+ if self.is_consolidated:
+ # pos return is already validated in pos invoice
+ return
if self.is_pos and self.is_return:
total_amount_in_payments = 0
@@ -285,7 +288,7 @@
filters={ invoice_or_credit_note: self.name },
pluck="pos_closing_entry"
)
- if pos_closing_entry:
+ if pos_closing_entry and pos_closing_entry[0]:
msg = _("To cancel a {} you need to cancel the POS Closing Entry {}.").format(
frappe.bold("Consolidated Sales Invoice"),
get_link_to_form("POS Closing Entry", pos_closing_entry[0])
@@ -572,7 +575,10 @@
frappe.throw(msg, title=_("Invalid Account"))
if self.customer and account.account_type != "Receivable":
- msg = _("Please ensure {} account is a Receivable account.").format(frappe.bold("Debit To")) + " "
+ msg = _("Please ensure {} account {} is a Receivable account.").format(
+ frappe.bold("Debit To"),
+ frappe.bold(self.debit_to)
+ ) + " "
msg += _("Change the account type to Receivable or select a different account.")
frappe.throw(msg, title=_("Invalid Account"))
@@ -1249,14 +1255,14 @@
def update_billing_status_in_dn(self, update_modified=True):
updated_delivery_notes = []
for d in self.get("items"):
- if d.dn_detail:
+ if d.so_detail:
+ updated_delivery_notes += update_billed_amount_based_on_so(d.so_detail, update_modified)
+ elif d.dn_detail:
billed_amt = frappe.db.sql("""select sum(amount) from `tabSales Invoice Item`
where dn_detail=%s and docstatus=1""", d.dn_detail)
billed_amt = billed_amt and billed_amt[0][0] or 0
frappe.db.set_value("Delivery Note Item", d.dn_detail, "billed_amt", billed_amt, update_modified=update_modified)
updated_delivery_notes.append(d.delivery_note)
- elif d.so_detail:
- updated_delivery_notes += update_billed_amount_based_on_so(d.so_detail, update_modified)
for dn in set(updated_delivery_notes):
frappe.get_doc("Delivery Note", dn).update_billing_percentage(update_modified=update_modified)
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice_list.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice_list.js
index 06e6f51..1130284 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice_list.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice_list.js
@@ -21,5 +21,15 @@
};
return [__(doc.status), status_colors[doc.status], "status,=,"+doc.status];
},
- right_column: "grand_total"
+ right_column: "grand_total",
+
+ onload: function(listview) {
+ listview.page.add_action_item(__("Delivery Note"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Sales Invoice", "Delivery Note");
+ });
+
+ listview.page.add_action_item(__("Payment"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Sales Invoice", "Payment");
+ });
+ }
};
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index 941061f..6d929e4 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -1595,6 +1595,56 @@
self.assertEqual(expected_values[gle.account][1], gle.debit)
self.assertEqual(expected_values[gle.account][2], gle.credit)
+ def test_rounding_adjustment_3(self):
+ si = create_sales_invoice(do_not_save=True)
+ si.items = []
+ for d in [(1122, 2), (1122.01, 1), (1122.01, 1)]:
+ si.append("items", {
+ "item_code": "_Test Item",
+ "gst_hsn_code": "999800",
+ "warehouse": "_Test Warehouse - _TC",
+ "qty": d[1],
+ "rate": d[0],
+ "income_account": "Sales - _TC",
+ "cost_center": "_Test Cost Center - _TC"
+ })
+ for tax_account in ["_Test Account VAT - _TC", "_Test Account Service Tax - _TC"]:
+ si.append("taxes", {
+ "charge_type": "On Net Total",
+ "account_head": tax_account,
+ "description": tax_account,
+ "rate": 6,
+ "cost_center": "_Test Cost Center - _TC",
+ "included_in_print_rate": 1
+ })
+ si.save()
+ si.submit()
+ self.assertEqual(si.net_total, 4007.16)
+ self.assertEqual(si.grand_total, 4488.02)
+ self.assertEqual(si.total_taxes_and_charges, 480.86)
+ self.assertEqual(si.rounding_adjustment, -0.02)
+
+ expected_values = dict((d[0], d) for d in [
+ [si.debit_to, 4488.0, 0.0],
+ ["_Test Account Service Tax - _TC", 0.0, 240.43],
+ ["_Test Account VAT - _TC", 0.0, 240.43],
+ ["Sales - _TC", 0.0, 4007.15],
+ ["Round Off - _TC", 0.01, 0]
+ ])
+
+ gl_entries = frappe.db.sql("""select account, debit, credit
+ from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
+ order by account asc""", si.name, as_dict=1)
+
+ debit_credit_diff = 0
+ for gle in gl_entries:
+ self.assertEqual(expected_values[gle.account][0], gle.account)
+ self.assertEqual(expected_values[gle.account][1], gle.debit)
+ self.assertEqual(expected_values[gle.account][2], gle.credit)
+ debit_credit_diff += (gle.debit - gle.credit)
+
+ self.assertEqual(debit_credit_diff, 0)
+
def test_sales_invoice_with_shipping_rule(self):
from erpnext.accounts.doctype.shipping_rule.test_shipping_rule import create_shipping_rule
@@ -2429,14 +2479,22 @@
def test_sales_commission(self):
- si = frappe.copy_doc(test_records[0])
+ si = frappe.copy_doc(test_records[2])
+
+ frappe.db.set_value('Item', si.get('items')[0].item_code, 'grant_commission', 1)
+ frappe.db.set_value('Item', si.get('items')[1].item_code, 'grant_commission', 0)
+
item = copy.deepcopy(si.get('items')[0])
item.update({
"qty": 1,
"rate": 500,
- "grant_commission": 1
})
- si.append("items", item)
+
+ item = copy.deepcopy(si.get('items')[1])
+ item.update({
+ "qty": 1,
+ "rate": 500,
+ })
# Test valid values
for commission_rate, total_commission in ((0, 0), (10, 50), (100, 500)):
diff --git a/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.json b/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.json
index ae9ac35..2901cf0 100644
--- a/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.json
+++ b/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.json
@@ -832,6 +832,7 @@
},
{
"default": "0",
+ "fetch_from": "item_code.grant_commission",
"fieldname": "grant_commission",
"fieldtype": "Check",
"label": "Grant Commission",
@@ -841,7 +842,7 @@
"idx": 1,
"istable": 1,
"links": [],
- "modified": "2021-10-05 12:24:54.968907",
+ "modified": "2022-02-24 14:41:36.392560",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Sales Invoice Item",
@@ -849,5 +850,6 @@
"owner": "Administrator",
"permissions": [],
"sort_field": "modified",
- "sort_order": "DESC"
+ "sort_order": "DESC",
+ "states": []
}
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/sales_taxes_and_charges_template/sales_taxes_and_charges_template.py b/erpnext/accounts/doctype/sales_taxes_and_charges_template/sales_taxes_and_charges_template.py
index b590944..8043a1b 100644
--- a/erpnext/accounts/doctype/sales_taxes_and_charges_template/sales_taxes_and_charges_template.py
+++ b/erpnext/accounts/doctype/sales_taxes_and_charges_template/sales_taxes_and_charges_template.py
@@ -46,7 +46,7 @@
for tax in doc.get("taxes"):
validate_taxes_and_charges(tax)
- validate_account_head(tax, doc)
+ validate_account_head(tax.idx, tax.account_head, doc.company)
validate_cost_center(tax, doc)
validate_inclusive_tax(tax, doc)
@@ -55,5 +55,8 @@
frappe.throw(_("Disabled template must not be default template"))
def validate_for_tax_category(doc):
+ if not doc.tax_category:
+ return
+
if frappe.db.exists(doc.doctype, {"company": doc.company, "tax_category": doc.tax_category, "disabled": 0, "name": ["!=", doc.name]}):
frappe.throw(_("A template with tax category {0} already exists. Only one template is allowed with each tax category").format(frappe.bold(doc.tax_category)))
diff --git a/erpnext/accounts/general_ledger.py b/erpnext/accounts/general_ledger.py
index 55bc967..0cd5e86 100644
--- a/erpnext/accounts/general_ledger.py
+++ b/erpnext/accounts/general_ledger.py
@@ -274,7 +274,7 @@
debit_credit_diff += flt(d.credit)
round_off_account_exists = True
- if round_off_account_exists and abs(debit_credit_diff) <= (1.0 / (10**precision)):
+ if round_off_account_exists and abs(debit_credit_diff) < (1.0 / (10**precision)):
gl_map.remove(round_off_gle)
return
@@ -319,13 +319,18 @@
"""
if not gl_entries:
- gl_entries = frappe.get_all("GL Entry",
- fields = ["*"],
- filters = {
- "voucher_type": voucher_type,
- "voucher_no": voucher_no,
- "is_cancelled": 0
- })
+ gl_entry = frappe.qb.DocType("GL Entry")
+ gl_entries = (frappe.qb.from_(
+ gl_entry
+ ).select(
+ '*'
+ ).where(
+ gl_entry.voucher_type == voucher_type
+ ).where(
+ gl_entry.voucher_no == voucher_no
+ ).where(
+ gl_entry.is_cancelled == 0
+ ).for_update()).run(as_dict=1)
if gl_entries:
validate_accounting_period(gl_entries)
@@ -333,23 +338,24 @@
set_as_cancel(gl_entries[0]['voucher_type'], gl_entries[0]['voucher_no'])
for entry in gl_entries:
- entry['name'] = None
- debit = entry.get('debit', 0)
- credit = entry.get('credit', 0)
+ new_gle = copy.deepcopy(entry)
+ new_gle['name'] = None
+ debit = new_gle.get('debit', 0)
+ credit = new_gle.get('credit', 0)
- debit_in_account_currency = entry.get('debit_in_account_currency', 0)
- credit_in_account_currency = entry.get('credit_in_account_currency', 0)
+ debit_in_account_currency = new_gle.get('debit_in_account_currency', 0)
+ credit_in_account_currency = new_gle.get('credit_in_account_currency', 0)
- entry['debit'] = credit
- entry['credit'] = debit
- entry['debit_in_account_currency'] = credit_in_account_currency
- entry['credit_in_account_currency'] = debit_in_account_currency
+ new_gle['debit'] = credit
+ new_gle['credit'] = debit
+ new_gle['debit_in_account_currency'] = credit_in_account_currency
+ new_gle['credit_in_account_currency'] = debit_in_account_currency
- entry['remarks'] = "On cancellation of " + entry['voucher_no']
- entry['is_cancelled'] = 1
+ new_gle['remarks'] = "On cancellation of " + new_gle['voucher_no']
+ new_gle['is_cancelled'] = 1
- if entry['debit'] or entry['credit']:
- make_entry(entry, adv_adj, "Yes")
+ if new_gle['debit'] or new_gle['credit']:
+ make_entry(new_gle, adv_adj, "Yes")
def check_freezing_date(posting_date, adv_adj=False):
diff --git a/erpnext/accounts/party.py b/erpnext/accounts/party.py
index c13bc23..d6f6c5b 100644
--- a/erpnext/accounts/party.py
+++ b/erpnext/accounts/party.py
@@ -307,7 +307,7 @@
.format(frappe.bold(party_type), frappe.bold(party), frappe.bold(existing_gle_currency), frappe.bold(company)), InvalidAccountCurrency)
def validate_party_accounts(doc):
-
+ from erpnext.controllers.accounts_controller import validate_account_head
companies = []
for account in doc.get("accounts"):
@@ -330,6 +330,9 @@
if doc.default_currency != party_account_currency and doc.default_currency != company_default_currency:
frappe.throw(_("Billing currency must be equal to either default company's currency or party account currency"))
+ # validate if account is mapped for same company
+ validate_account_head(account.idx, account.account, account.company)
+
@frappe.whitelist()
def get_due_date(posting_date, party_type, party, company=None, bill_date=None):
diff --git a/erpnext/accounts/print_format/gst_pos_invoice/gst_pos_invoice.json b/erpnext/accounts/print_format/gst_pos_invoice/gst_pos_invoice.json
deleted file mode 100644
index 1aa1c02..0000000
--- a/erpnext/accounts/print_format/gst_pos_invoice/gst_pos_invoice.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "align_labels_right": 0,
- "creation": "2017-08-08 12:33:04.773099",
- "custom_format": 1,
- "disabled": 0,
- "doc_type": "Sales Invoice",
- "docstatus": 0,
- "doctype": "Print Format",
- "font": "Default",
- "html": "<style>\n\t.print-format table, .print-format tr, \n\t.print-format td, .print-format div, .print-format p {\n\t\tfont-family: Tahoma, sans-serif;\n\t\tline-height: 150%;\n\t\tvertical-align: middle;\n\t}\n\t@media screen {\n\t\t.print-format {\n\t\t\twidth: 4in;\n\t\t\tpadding: 0.25in;\n\t\t\tmin-height: 8in;\n\t\t}\n\t}\n</style>\n\n{% if letter_head %}\n {{ letter_head }}\n{% endif %}\n<p class=\"text-center\">\n\t{{ doc.company }}<br>\n\t{% if doc.company_address_display %}\n\t\t{% set company_address = doc.company_address_display.replace(\"\\n\", \" \").replace(\"<br>\", \" \") %}\n\t\t{% if \"GSTIN\" not in company_address %}\n\t\t\t{{ company_address }}\n\t\t\t<b>{{ _(\"GSTIN\") }}:</b>{{ doc.company_gstin }}\n\t\t{% else %}\n\t\t\t{{ company_address.replace(\"GSTIN\", \"<br>GSTIN\") }}\n\t\t{% endif %}\n\t{% endif %}\n\t<br>\n\t{% if doc.docstatus == 0 %}\n\t\t<b>{{ doc.status + \" \"+ (doc.select_print_heading or _(\"Invoice\")) }}</b><br>\n\t{% else %}\n\t\t<b>{{ doc.select_print_heading or _(\"Invoice\") }}</b><br>\n\t{% endif %}\n</p>\n<p>\n\t<b>{{ _(\"Receipt No\") }}:</b> {{ doc.name }}<br>\n\t<b>{{ _(\"Date\") }}:</b> {{ doc.get_formatted(\"posting_date\") }}<br>\n\t{% if doc.grand_total > 50000 %}\n\t\t{% set customer_address = doc.address_display.replace(\"\\n\", \" \").replace(\"<br>\", \" \") %}\n\t\t<b>{{ _(\"Customer\") }}:</b><br>\n\t\t{{ doc.customer_name }}<br>\n\t\t{{ customer_address }}\n\t{% endif %}\n</p>\n\n<hr>\n<table class=\"table table-condensed cart no-border\">\n\t<thead>\n\t\t<tr>\n\t\t\t<th width=\"50%\">{{ _(\"Item\") }}</b></th>\n\t\t\t<th width=\"25%\" class=\"text-right\">{{ _(\"Qty\") }}</th>\n\t\t\t<th width=\"25%\" class=\"text-right\">{{ _(\"Amount\") }}</th>\n\t\t</tr>\n\t</thead>\n\t<tbody>\n\t\t{%- for item in doc.items -%}\n\t\t<tr>\n\t\t\t<td>\n\t\t\t\t{{ item.item_code }}\n\t\t\t\t{%- if item.item_name != item.item_code -%}\n\t\t\t\t\t<br>{{ item.item_name }}\n\t\t\t\t{%- endif -%}\n\t\t\t\t{%- if item.gst_hsn_code -%}\n\t\t\t\t\t<br><b>{{ _(\"HSN/SAC\") }}:</b> {{ item.gst_hsn_code }}\n\t\t\t\t{%- endif -%}\n\t\t\t\t{%- if item.serial_no -%}\n\t\t\t\t\t<br><b>{{ _(\"Serial No\") }}:</b> {{ item.serial_no }}\n\t\t\t\t{%- endif -%}\n\t\t\t</td>\n\t\t\t<td class=\"text-right\">{{ item.qty }}<br>@ {{ item.rate }}</td>\n\t\t\t<td class=\"text-right\">{{ item.get_formatted(\"amount\") }}</td>\n\t\t</tr>\n\t\t{%- endfor -%}\n\t</tbody>\n</table>\n<table class=\"table table-condensed no-border\">\n\t<tbody>\n\t\t<tr>\n\t\t\t{% if doc.flags.show_inclusive_tax_in_print %}\n\t\t\t\t<td class=\"text-right\" style=\"width: 70%\">\n\t\t\t\t\t{{ _(\"Total Excl. Tax\") }}\n\t\t\t\t</td>\n\t\t\t\t<td class=\"text-right\">\n\t\t\t\t\t{{ doc.get_formatted(\"net_total\", doc) }}\n\t\t\t\t</td>\n\t\t\t{% else %}\n\t\t\t\t<td class=\"text-right\" style=\"width: 70%\">\n\t\t\t\t\t{{ _(\"Total\") }}\n\t\t\t\t</td>\n\t\t\t\t<td class=\"text-right\">\n\t\t\t\t\t{{ doc.get_formatted(\"total\", doc) }}\n\t\t\t\t</td>\n\t\t\t{% endif %}\n\t\t</tr>\n\t\t{%- for row in doc.taxes -%}\n\t\t {%- if (not row.included_in_print_rate or doc.flags.show_inclusive_tax_in_print) and row.tax_amount != 0 -%}\n\t\t\t<tr>\n\t\t\t\t<td class=\"text-right\" style=\"width: 70%\">\n\t\t\t\t\t{{ row.description }}\n\t\t\t\t</td>\n\t\t\t\t<td class=\"text-right\">\n\t\t\t\t\t{{ row.get_formatted(\"tax_amount\", doc) }}\n\t\t\t\t</td>\n\t\t\t<tr>\n\t\t {%- endif -%}\n\t\t{%- endfor -%}\n\t\t{%- if doc.discount_amount -%}\n\t\t<tr>\n\t\t\t<td class=\"text-right\" style=\"width: 75%\">\n\t\t\t\t{{ _(\"Discount\") }}\n\t\t\t</td>\n\t\t\t<td class=\"text-right\">\n\t\t\t\t{{ doc.get_formatted(\"discount_amount\") }}\n\t\t\t</td>\n\t\t</tr>\n\t\t{%- endif -%}\n\t\t<tr>\n\t\t\t<td class=\"text-right\" style=\"width: 75%\">\n\t\t\t\t<b>{{ _(\"Grand Total\") }}</b>\n\t\t\t</td>\n\t\t\t<td class=\"text-right\">\n\t\t\t\t{{ doc.get_formatted(\"grand_total\") }}\n\t\t\t</td>\n\t\t</tr>\n\t\t{%- if doc.rounded_total -%}\n\t\t<tr>\n\t\t\t<td class=\"text-right\" style=\"width: 75%\">\n\t\t\t\t<b>{{ _(\"Rounded Total\") }}</b>\n\t\t\t</td>\n\t\t\t<td class=\"text-right\">\n\t\t\t\t{{ doc.get_formatted(\"rounded_total\") }}\n\t\t\t</td>\n\t\t</tr>\n\t\t{%- endif -%}\n\t\t<tr>\n\t\t\t<td class=\"text-right\" style=\"width: 75%\">\n\t\t\t\t<b>{{ _(\"Paid Amount\") }}</b>\n\t\t\t</td>\n\t\t\t<td class=\"text-right\">\n\t\t\t\t{{ doc.get_formatted(\"paid_amount\") }}\n\t\t\t</td>\n\t\t</tr>\n\t{%- if doc.change_amount -%}\n\t\t<tr>\n\t\t\t<td class=\"text-right\" style=\"width: 75%\">\n\t\t\t\t<b>{{ _(\"Change Amount\") }}</b>\n\t\t\t</td>\n\t\t\t<td class=\"text-right\">\n\t\t\t\t{{ doc.get_formatted(\"change_amount\") }}\n\t\t\t</td>\n\t\t</tr>\n\t{%- endif -%}\n\t</tbody>\n</table>\n<p>{{ doc.terms or \"\" }}</p>\n<p class=\"text-center\">{{ _(\"Thank you, please visit again.\") }}</p>",
- "idx": 0,
- "line_breaks": 0,
- "modified": "2020-04-29 16:39:12.936215",
- "modified_by": "Administrator",
- "module": "Accounts",
- "name": "GST POS Invoice",
- "owner": "Administrator",
- "print_format_builder": 0,
- "print_format_type": "Jinja",
- "raw_printing": 0,
- "show_section_headings": 0,
- "standard": "Yes"
-}
\ No newline at end of file
diff --git a/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py b/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py
index 6c401fb..b72d266 100644
--- a/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py
+++ b/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py
@@ -4,7 +4,12 @@
import frappe
from frappe import _
-from frappe.utils import flt, getdate, nowdate
+from frappe.query_builder.custom import ConstantColumn
+from frappe.query_builder.functions import Sum
+from frappe.utils import flt, getdate
+from pypika import CustomFunction
+
+from erpnext.accounts.utils import get_balance_on
def execute(filters=None):
@@ -18,7 +23,6 @@
data = get_entries(filters)
- from erpnext.accounts.utils import get_balance_on
balance_as_per_system = get_balance_on(filters["account"], filters["report_date"])
total_debit, total_credit = 0,0
@@ -118,7 +122,21 @@
]
def get_entries(filters):
- journal_entries = frappe.db.sql("""
+ journal_entries = get_journal_entries(filters)
+
+ payment_entries = get_payment_entries(filters)
+
+ loan_entries = get_loan_entries(filters)
+
+ pos_entries = []
+ if filters.include_pos_transactions:
+ pos_entries = get_pos_entries(filters)
+
+ return sorted(list(payment_entries)+list(journal_entries+list(pos_entries) + list(loan_entries)),
+ key=lambda k: getdate(k['posting_date']))
+
+def get_journal_entries(filters):
+ return frappe.db.sql("""
select "Journal Entry" as payment_document, jv.posting_date,
jv.name as payment_entry, jvd.debit_in_account_currency as debit,
jvd.credit_in_account_currency as credit, jvd.against_account,
@@ -130,7 +148,8 @@
and ifnull(jv.clearance_date, '4000-01-01') > %(report_date)s
and ifnull(jv.is_opening, 'No') = 'No'""", filters, as_dict=1)
- payment_entries = frappe.db.sql("""
+def get_payment_entries(filters):
+ return frappe.db.sql("""
select
"Payment Entry" as payment_document, name as payment_entry,
reference_no, reference_date as ref_date,
@@ -145,9 +164,8 @@
and ifnull(clearance_date, '4000-01-01') > %(report_date)s
""", filters, as_dict=1)
- pos_entries = []
- if filters.include_pos_transactions:
- pos_entries = frappe.db.sql("""
+def get_pos_entries(filters):
+ return frappe.db.sql("""
select
"Sales Invoice Payment" as payment_document, sip.name as payment_entry, sip.amount as debit,
si.posting_date, si.debit_to as against_account, sip.clearance_date,
@@ -161,8 +179,42 @@
si.posting_date ASC, si.name DESC
""", filters, as_dict=1)
- return sorted(list(payment_entries)+list(journal_entries+list(pos_entries)),
- key=lambda k: k['posting_date'] or getdate(nowdate()))
+def get_loan_entries(filters):
+ loan_docs = []
+ for doctype in ["Loan Disbursement", "Loan Repayment"]:
+ loan_doc = frappe.qb.DocType(doctype)
+ ifnull = CustomFunction('IFNULL', ['value', 'default'])
+
+ if doctype == "Loan Disbursement":
+ amount_field = (loan_doc.disbursed_amount).as_("credit")
+ posting_date = (loan_doc.disbursement_date).as_("posting_date")
+ account = loan_doc.disbursement_account
+ else:
+ amount_field = (loan_doc.amount_paid).as_("debit")
+ posting_date = (loan_doc.posting_date).as_("posting_date")
+ account = loan_doc.payment_account
+
+ entries = frappe.qb.from_(loan_doc).select(
+ ConstantColumn(doctype).as_("payment_document"),
+ (loan_doc.name).as_("payment_entry"),
+ (loan_doc.reference_number).as_("reference_no"),
+ (loan_doc.reference_date).as_("ref_date"),
+ amount_field,
+ posting_date,
+ ).where(
+ loan_doc.docstatus == 1
+ ).where(
+ account == filters.get('account')
+ ).where(
+ posting_date <= getdate(filters.get('report_date'))
+ ).where(
+ ifnull(loan_doc.clearance_date, '4000-01-01') > getdate(filters.get('report_date'))
+ ).run(as_dict=1)
+
+ loan_docs.extend(entries)
+
+ return loan_docs
+
def get_amounts_not_reflected_in_system(filters):
je_amount = frappe.db.sql("""
@@ -182,7 +234,40 @@
pe_amount = flt(pe_amount[0][0]) if pe_amount else 0.0
- return je_amount + pe_amount
+ loan_amount = get_loan_amount(filters)
+
+ return je_amount + pe_amount + loan_amount
+
+def get_loan_amount(filters):
+ total_amount = 0
+ for doctype in ["Loan Disbursement", "Loan Repayment"]:
+ loan_doc = frappe.qb.DocType(doctype)
+ ifnull = CustomFunction('IFNULL', ['value', 'default'])
+
+ if doctype == "Loan Disbursement":
+ amount_field = Sum(loan_doc.disbursed_amount)
+ posting_date = (loan_doc.disbursement_date).as_("posting_date")
+ account = loan_doc.disbursement_account
+ else:
+ amount_field = Sum(loan_doc.amount_paid)
+ posting_date = (loan_doc.posting_date).as_("posting_date")
+ account = loan_doc.payment_account
+
+ amount = frappe.qb.from_(loan_doc).select(
+ amount_field
+ ).where(
+ loan_doc.docstatus == 1
+ ).where(
+ account == filters.get('account')
+ ).where(
+ posting_date > getdate(filters.get('report_date'))
+ ).where(
+ ifnull(loan_doc.clearance_date, '4000-01-01') <= getdate(filters.get('report_date'))
+ ).run()[0][0]
+
+ total_amount += flt(amount)
+
+ return amount
def get_balance_row(label, amount, account_currency):
if amount > 0:
diff --git a/erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py b/erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py
index 758e3e9..1e20f7b 100644
--- a/erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py
+++ b/erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py
@@ -354,9 +354,6 @@
if d.parent_account:
account = d.parent_account_name
- # if not accounts_by_name.get(account):
- # continue
-
for company in companies:
accounts_by_name[account][company] = \
accounts_by_name[account].get(company, 0.0) + d.get(company, 0.0)
@@ -367,7 +364,7 @@
accounts_by_name[account].get("opening_balance", 0.0) + d.get("opening_balance", 0.0)
def get_account_heads(root_type, companies, filters):
- accounts = get_accounts(root_type, filters)
+ accounts = get_accounts(root_type, companies)
if not accounts:
return None, None, None
@@ -396,7 +393,7 @@
for account in accounts:
if account.parent_account:
- account["parent_account_name"] = name_to_account_map[account.parent_account]
+ account["parent_account_name"] = name_to_account_map.get(account.parent_account)
return accounts
@@ -419,12 +416,19 @@
return frappe.db.sql_list("""select name from `tabCompany`
where lft >= {0} and rgt <= {1} order by lft, rgt""".format(lft, rgt))
-def get_accounts(root_type, filters):
- return frappe.db.sql(""" select name, is_group, company,
- parent_account, lft, rgt, root_type, report_type, account_name, account_number
- from
- `tabAccount` where company = %s and root_type = %s
- """ , (filters.get('company'), root_type), as_dict=1)
+def get_accounts(root_type, companies):
+ accounts = []
+ added_accounts = []
+
+ for company in companies:
+ for account in frappe.get_all("Account", fields=["name", "is_group", "company",
+ "parent_account", "lft", "rgt", "root_type", "report_type", "account_name", "account_number"],
+ filters={"company": company, "root_type": root_type}):
+ if account.account_name not in added_accounts:
+ accounts.append(account)
+ added_accounts.append(account.account_name)
+
+ return accounts
def prepare_data(accounts, start_date, end_date, balance_must_be, companies, company_currency, filters):
data = []
diff --git a/erpnext/accounts/report/gross_profit/gross_profit.js b/erpnext/accounts/report/gross_profit/gross_profit.js
index 685f2d6..158ff4d 100644
--- a/erpnext/accounts/report/gross_profit/gross_profit.js
+++ b/erpnext/accounts/report/gross_profit/gross_profit.js
@@ -8,20 +8,22 @@
"label": __("Company"),
"fieldtype": "Link",
"options": "Company",
- "reqd": 1,
- "default": frappe.defaults.get_user_default("Company")
+ "default": frappe.defaults.get_user_default("Company"),
+ "reqd": 1
},
{
"fieldname":"from_date",
"label": __("From Date"),
"fieldtype": "Date",
- "default": frappe.defaults.get_user_default("year_start_date")
+ "default": frappe.defaults.get_user_default("year_start_date"),
+ "reqd": 1
},
{
"fieldname":"to_date",
"label": __("To Date"),
"fieldtype": "Date",
- "default": frappe.defaults.get_user_default("year_end_date")
+ "default": frappe.defaults.get_user_default("year_end_date"),
+ "reqd": 1
},
{
"fieldname":"sales_invoice",
@@ -42,6 +44,11 @@
"parent_field": "parent_invoice",
"initial_depth": 3,
"formatter": function(value, row, column, data, default_formatter) {
+ if (column.fieldname == "sales_invoice" && column.options == "Item" && data.indent == 0) {
+ column._options = "Sales Invoice";
+ } else {
+ column._options = "Item";
+ }
value = default_formatter(value, row, column, data);
if (data && (data.indent == 0.0 || row[1].content == "Total")) {
diff --git a/erpnext/accounts/report/gross_profit/gross_profit.json b/erpnext/accounts/report/gross_profit/gross_profit.json
index 76c560a..0730ffd 100644
--- a/erpnext/accounts/report/gross_profit/gross_profit.json
+++ b/erpnext/accounts/report/gross_profit/gross_profit.json
@@ -1,5 +1,5 @@
{
- "add_total_row": 0,
+ "add_total_row": 1,
"columns": [],
"creation": "2013-02-25 17:03:34",
"disable_prepared_report": 0,
@@ -9,7 +9,7 @@
"filters": [],
"idx": 3,
"is_standard": "Yes",
- "modified": "2021-11-13 19:14:23.730198",
+ "modified": "2022-02-11 10:18:36.956558",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Gross Profit",
diff --git a/erpnext/accounts/report/gross_profit/gross_profit.py b/erpnext/accounts/report/gross_profit/gross_profit.py
index 84effc0..b03bb9b 100644
--- a/erpnext/accounts/report/gross_profit/gross_profit.py
+++ b/erpnext/accounts/report/gross_profit/gross_profit.py
@@ -70,43 +70,42 @@
data.append(row)
def get_data_when_not_grouped_by_invoice(gross_profit_data, filters, group_wise_columns, data):
- for idx, src in enumerate(gross_profit_data.grouped_data):
+ for src in gross_profit_data.grouped_data:
row = []
for col in group_wise_columns.get(scrub(filters.group_by)):
row.append(src.get(col))
row.append(filters.currency)
- if idx == len(gross_profit_data.grouped_data)-1:
- row[0] = "Total"
data.append(row)
def get_columns(group_wise_columns, filters):
columns = []
column_map = frappe._dict({
- "parent": _("Sales Invoice") + ":Link/Sales Invoice:120",
- "invoice_or_item": _("Sales Invoice") + ":Link/Sales Invoice:120",
- "posting_date": _("Posting Date") + ":Date:100",
- "posting_time": _("Posting Time") + ":Data:100",
- "item_code": _("Item Code") + ":Link/Item:100",
- "item_name": _("Item Name") + ":Data:100",
- "item_group": _("Item Group") + ":Link/Item Group:100",
- "brand": _("Brand") + ":Link/Brand:100",
- "description": _("Description") +":Data:100",
- "warehouse": _("Warehouse") + ":Link/Warehouse:100",
- "qty": _("Qty") + ":Float:80",
- "base_rate": _("Avg. Selling Rate") + ":Currency/currency:100",
- "buying_rate": _("Valuation Rate") + ":Currency/currency:100",
- "base_amount": _("Selling Amount") + ":Currency/currency:100",
- "buying_amount": _("Buying Amount") + ":Currency/currency:100",
- "gross_profit": _("Gross Profit") + ":Currency/currency:100",
- "gross_profit_percent": _("Gross Profit %") + ":Percent:100",
- "project": _("Project") + ":Link/Project:100",
- "sales_person": _("Sales person"),
- "allocated_amount": _("Allocated Amount") + ":Currency/currency:100",
- "customer": _("Customer") + ":Link/Customer:100",
- "customer_group": _("Customer Group") + ":Link/Customer Group:100",
- "territory": _("Territory") + ":Link/Territory:100"
+ "parent": {"label": _('Sales Invoice'), "fieldname": "parent_invoice", "fieldtype": "Link", "options": "Sales Invoice", "width": 120},
+ "invoice_or_item": {"label": _('Sales Invoice'), "fieldtype": "Link", "options": "Sales Invoice", "width": 120},
+ "posting_date": {"label": _('Posting Date'), "fieldname": "posting_date", "fieldtype": "Date", "width": 100},
+ "posting_time": {"label": _('Posting Time'), "fieldname": "posting_time", "fieldtype": "Data", "width": 100},
+ "item_code": {"label": _('Item Code'), "fieldname": "item_code", "fieldtype": "Link", "options": "Item", "width": 100},
+ "item_name": {"label": _('Item Name'), "fieldname": "item_name", "fieldtype": "Data", "width": 100},
+ "item_group": {"label": _('Item Group'), "fieldname": "item_group", "fieldtype": "Link", "options": "Item Group", "width": 100},
+ "brand": {"label": _('Brand'), "fieldtype": "Link", "options": "Brand", "width": 100},
+ "description": {"label": _('Description'), "fieldname": "description", "fieldtype": "Data", "width": 100},
+ "warehouse": {"label": _('Warehouse'), "fieldname": "warehouse", "fieldtype": "Link", "options": "warehouse", "width": 100},
+ "qty": {"label": _('Qty'), "fieldname": "qty", "fieldtype": "Float", "width": 80},
+ "base_rate": {"label": _('Avg. Selling Rate'), "fieldname": "avg._selling_rate", "fieldtype": "Currency", "options": "currency", "width": 100},
+ "buying_rate": {"label": _('Valuation Rate'), "fieldname": "valuation_rate", "fieldtype": "Currency", "options": "currency", "width": 100},
+ "base_amount": {"label": _('Selling Amount'), "fieldname": "selling_amount", "fieldtype": "Currency", "options": "currency", "width": 100},
+ "buying_amount": {"label": _('Buying Amount'), "fieldname": "buying_amount", "fieldtype": "Currency", "options": "currency", "width": 100},
+ "gross_profit": {"label": _('Gross Profit'), "fieldname": "gross_profit", "fieldtype": "Currency", "options": "currency", "width": 100},
+ "gross_profit_percent": {"label": _('Gross Profit Percent'), "fieldname": "gross_profit_%",
+ "fieldtype": "Percent", "width": 100},
+ "project": {"label": _('Project'), "fieldname": "project", "fieldtype": "Link", "options": "Project", "width": 100},
+ "sales_person": {"label": _('Sales Person'), "fieldname": "sales_person", "fieldtype": "Data","width": 100},
+ "allocated_amount": {"label": _('Allocated Amount'), "fieldname": "allocated_amount", "fieldtype": "Currency", "options": "currency", "width": 100},
+ "customer": {"label": _('Customer'), "fieldname": "customer", "fieldtype": "Link", "options": "Customer", "width": 100},
+ "customer_group": {"label": _('Customer Group'), "fieldname": "customer_group", "fieldtype": "Link", "options": "customer", "width": 100},
+ "territory": {"label": _('Territory'), "fieldname": "territory", "fieldtype": "Link", "options": "territory", "width": 100},
})
for col in group_wise_columns.get(scrub(filters.group_by)):
@@ -173,7 +172,7 @@
buying_amount = 0
for row in reversed(self.si_list):
- if self.skip_row(row, self.product_bundles):
+ if self.skip_row(row):
continue
row.base_amount = flt(row.base_net_amount, self.currency_precision)
@@ -223,16 +222,6 @@
self.get_average_rate_based_on_group_by()
def get_average_rate_based_on_group_by(self):
- # sum buying / selling totals for group
- self.totals = frappe._dict(
- qty=0,
- base_amount=0,
- buying_amount=0,
- gross_profit=0,
- gross_profit_percent=0,
- base_rate=0,
- buying_rate=0
- )
for key in list(self.grouped):
if self.filters.get("group_by") != "Invoice":
for i, row in enumerate(self.grouped[key]):
@@ -244,7 +233,6 @@
new_row.base_amount += flt(row.base_amount, self.currency_precision)
new_row = self.set_average_rate(new_row)
self.grouped_data.append(new_row)
- self.add_to_totals(new_row)
else:
for i, row in enumerate(self.grouped[key]):
if row.indent == 1.0:
@@ -258,17 +246,6 @@
if (flt(row.qty) or row.base_amount):
row = self.set_average_rate(row)
self.grouped_data.append(row)
- self.add_to_totals(row)
-
- self.set_average_gross_profit(self.totals)
-
- if self.filters.get("group_by") == "Invoice":
- self.totals.indent = 0.0
- self.totals.parent_invoice = ""
- self.totals.invoice_or_item = "Total"
- self.si_list.append(self.totals)
- else:
- self.grouped_data.append(self.totals)
def is_not_invoice_row(self, row):
return (self.filters.get("group_by") == "Invoice" and row.indent != 0.0) or self.filters.get("group_by") != "Invoice"
@@ -284,11 +261,6 @@
new_row.gross_profit_percent = flt(((new_row.gross_profit / new_row.base_amount) * 100.0), self.currency_precision) \
if new_row.base_amount else 0
- def add_to_totals(self, new_row):
- for key in self.totals:
- if new_row.get(key):
- self.totals[key] += new_row[key]
-
def get_returned_invoice_items(self):
returned_invoices = frappe.db.sql("""
select
@@ -306,12 +278,12 @@
self.returned_invoices.setdefault(inv.return_against, frappe._dict())\
.setdefault(inv.item_code, []).append(inv)
- def skip_row(self, row, product_bundles):
+ def skip_row(self, row):
if self.filters.get("group_by") != "Invoice":
if not row.get(scrub(self.filters.get("group_by", ""))):
return True
- elif row.get("is_return") == 1:
- return True
+
+ return False
def get_buying_amount_from_product_bundle(self, row, product_bundle):
buying_amount = 0.0
@@ -369,20 +341,37 @@
return self.average_buying_rate[item_code]
def get_last_purchase_rate(self, item_code, row):
- condition = ''
- if row.project:
- condition += " AND a.project=%s" % (frappe.db.escape(row.project))
- elif row.cost_center:
- condition += " AND a.cost_center=%s" % (frappe.db.escape(row.cost_center))
- if self.filters.to_date:
- condition += " AND modified='%s'" % (self.filters.to_date)
+ purchase_invoice = frappe.qb.DocType("Purchase Invoice")
+ purchase_invoice_item = frappe.qb.DocType("Purchase Invoice Item")
- last_purchase_rate = frappe.db.sql("""
- select (a.base_rate / a.conversion_factor)
- from `tabPurchase Invoice Item` a
- where a.item_code = %s and a.docstatus=1
- {0}
- order by a.modified desc limit 1""".format(condition), item_code)
+ query = (frappe.qb.from_(purchase_invoice_item)
+ .inner_join(
+ purchase_invoice
+ ).on(
+ purchase_invoice.name == purchase_invoice_item.parent
+ ).select(
+ purchase_invoice_item.base_rate / purchase_invoice_item.conversion_factor
+ ).where(
+ purchase_invoice.docstatus == 1
+ ).where(
+ purchase_invoice.posting_date <= self.filters.to_date
+ ).where(
+ purchase_invoice_item.item_code == item_code
+ ))
+
+ if row.project:
+ query.where(
+ purchase_invoice_item.project == row.project
+ )
+
+ if row.cost_center:
+ query.where(
+ purchase_invoice_item.cost_center == row.cost_center
+ )
+
+ query.orderby(purchase_invoice.posting_date, order=frappe.qb.desc)
+ query.limit(1)
+ last_purchase_rate = query.run()
return flt(last_purchase_rate[0][0]) if last_purchase_rate else 0
diff --git a/erpnext/accounts/report/tax_detail/test_tax_detail.py b/erpnext/accounts/report/tax_detail/test_tax_detail.py
index bf668ab..621de82 100644
--- a/erpnext/accounts/report/tax_detail/test_tax_detail.py
+++ b/erpnext/accounts/report/tax_detail/test_tax_detail.py
@@ -61,7 +61,7 @@
# Create GL Entries:
db_doc.submit()
else:
- db_doc.insert()
+ db_doc.insert(ignore_if_duplicate=True)
except frappe.exceptions.DuplicateEntryError:
pass
diff --git a/erpnext/accounts/report/tds_payable_monthly/tds_payable_monthly.py b/erpnext/accounts/report/tds_payable_monthly/tds_payable_monthly.py
index caee1a1..e6cbff5 100644
--- a/erpnext/accounts/report/tds_payable_monthly/tds_payable_monthly.py
+++ b/erpnext/accounts/report/tds_payable_monthly/tds_payable_monthly.py
@@ -23,7 +23,7 @@
def get_result(filters, tds_docs, tds_accounts, tax_category_map):
supplier_map = get_supplier_pan_map()
tax_rate_map = get_tax_rate_map(filters)
- gle_map = get_gle_map(filters, tds_docs)
+ gle_map = get_gle_map(tds_docs)
out = []
for name, details in gle_map.items():
@@ -43,7 +43,7 @@
if entry.account in tds_accounts:
tds_deducted += (entry.credit - entry.debit)
- total_amount_credited += (entry.credit - entry.debit)
+ total_amount_credited += entry.credit
if tds_deducted:
row = {
@@ -78,7 +78,7 @@
return supplier_map
-def get_gle_map(filters, documents):
+def get_gle_map(documents):
# create gle_map of the form
# {"purchase_invoice": list of dict of all gle created for this invoice}
gle_map = {}
@@ -86,7 +86,7 @@
gle = frappe.db.get_all('GL Entry',
{
"voucher_no": ["in", documents],
- "credit": (">", 0)
+ "is_cancelled": 0
},
["credit", "debit", "account", "voucher_no", "posting_date", "voucher_type", "against", "party"],
)
@@ -184,21 +184,28 @@
payment_entries = []
journal_entries = []
tax_category_map = {}
+ or_filters = {}
+ bank_accounts = frappe.get_all('Account', {'is_group': 0, 'account_type': 'Bank'}, pluck="name")
tds_accounts = frappe.get_all("Tax Withholding Account", {'company': filters.get('company')},
pluck="account")
query_filters = {
- "credit": ('>', 0),
"account": ("in", tds_accounts),
"posting_date": ("between", [filters.get("from_date"), filters.get("to_date")]),
- "is_cancelled": 0
+ "is_cancelled": 0,
+ "against": ("not in", bank_accounts)
}
- if filters.get('supplier'):
- query_filters.update({'against': filters.get('supplier')})
+ if filters.get("supplier"):
+ del query_filters["account"]
+ del query_filters["against"]
+ or_filters = {
+ "against": filters.get('supplier'),
+ "party": filters.get('supplier')
+ }
- tds_docs = frappe.get_all("GL Entry", query_filters, ["voucher_no", "voucher_type", "against", "party"])
+ tds_docs = frappe.get_all("GL Entry", filters=query_filters, or_filters=or_filters, fields=["voucher_no", "voucher_type", "against", "party"])
for d in tds_docs:
if d.voucher_type == "Purchase Invoice":
diff --git a/erpnext/accounts/test/test_reports.py b/erpnext/accounts/test/test_reports.py
index 78c109a..4ed966d 100644
--- a/erpnext/accounts/test/test_reports.py
+++ b/erpnext/accounts/test/test_reports.py
@@ -39,10 +39,11 @@
def test_execute_all_accounts_reports(self):
"""Test that all script report in stock modules are executable with supported filters"""
for report, filter in REPORT_FILTER_TEST_CASES:
- execute_script_report(
- report_name=report,
- module="Accounts",
- filters=filter,
- default_filters=DEFAULT_FILTERS,
- optional_filters=OPTIONAL_FILTERS if filter.get("_optional") else None,
- )
+ with self.subTest(report=report):
+ execute_script_report(
+ report_name=report,
+ module="Accounts",
+ filters=filter,
+ default_filters=DEFAULT_FILTERS,
+ optional_filters=OPTIONAL_FILTERS if filter.get("_optional") else None,
+ )
diff --git a/erpnext/accounts/utils.py b/erpnext/accounts/utils.py
index 39e84e3..b17b90b 100644
--- a/erpnext/accounts/utils.py
+++ b/erpnext/accounts/utils.py
@@ -847,7 +847,7 @@
"payment_account": bank_account.name,
"currency": bank_account.account_currency,
"payment_channel": payment_channel
- }).insert(ignore_permissions=True)
+ }).insert(ignore_permissions=True, ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
# already exists, due to a reinstall?
diff --git a/erpnext/assets/doctype/asset/asset.py b/erpnext/assets/doctype/asset/asset.py
index 6e87426..ea473fa 100644
--- a/erpnext/assets/doctype/asset/asset.py
+++ b/erpnext/assets/doctype/asset/asset.py
@@ -417,11 +417,12 @@
def validate_asset_finance_books(self, row):
if flt(row.expected_value_after_useful_life) >= flt(self.gross_purchase_amount):
frappe.throw(_("Row {0}: Expected Value After Useful Life must be less than Gross Purchase Amount")
- .format(row.idx))
+ .format(row.idx), title=_("Invalid Schedule"))
if not row.depreciation_start_date:
if not self.available_for_use_date:
- frappe.throw(_("Row {0}: Depreciation Start Date is required").format(row.idx))
+ frappe.throw(_("Row {0}: Depreciation Start Date is required")
+ .format(row.idx), title=_("Invalid Schedule"))
row.depreciation_start_date = get_last_day(self.available_for_use_date)
if not self.is_existing_asset:
@@ -439,8 +440,9 @@
else:
self.number_of_depreciations_booked = 0
- if cint(self.number_of_depreciations_booked) > cint(row.total_number_of_depreciations):
- frappe.throw(_("Number of Depreciations Booked cannot be greater than Total Number of Depreciations"))
+ if flt(row.total_number_of_depreciations) <= cint(self.number_of_depreciations_booked):
+ frappe.throw(_("Row {0}: Total Number of Depreciations cannot be less than or equal to Number of Depreciations Booked")
+ .format(row.idx), title=_("Invalid Schedule"))
if row.depreciation_start_date and getdate(row.depreciation_start_date) < getdate(self.purchase_date):
frappe.throw(_("Depreciation Row {0}: Next Depreciation Date cannot be before Purchase Date")
diff --git a/erpnext/assets/doctype/asset/asset_dashboard.py b/erpnext/assets/doctype/asset/asset_dashboard.py
index 00d0847..c81b611 100644
--- a/erpnext/assets/doctype/asset/asset_dashboard.py
+++ b/erpnext/assets/doctype/asset/asset_dashboard.py
@@ -1,3 +1,6 @@
+from frappe import _
+
+
def get_data():
return {
'non_standard_fieldnames': {
@@ -5,7 +8,7 @@
},
'transactions': [
{
- 'label': ['Movement'],
+ 'label': _('Movement'),
'items': ['Asset Movement']
}
]
diff --git a/erpnext/assets/doctype/asset/depreciation.py b/erpnext/assets/doctype/asset/depreciation.py
index 874fb63..6e04242 100644
--- a/erpnext/assets/doctype/asset/depreciation.py
+++ b/erpnext/assets/doctype/asset/depreciation.py
@@ -23,7 +23,7 @@
frappe.db.commit()
def get_depreciable_assets(date):
- return frappe.db.sql_list("""select a.name
+ return frappe.db.sql_list("""select distinct a.name
from tabAsset a, `tabDepreciation Schedule` ds
where a.name = ds.parent and a.docstatus=1 and ds.schedule_date<=%s and a.calculate_depreciation = 1
and a.status in ('Submitted', 'Partially Depreciated')
diff --git a/erpnext/assets/doctype/asset/test_asset.py b/erpnext/assets/doctype/asset/test_asset.py
index c08dc21..ffd1065 100644
--- a/erpnext/assets/doctype/asset/test_asset.py
+++ b/erpnext/assets/doctype/asset/test_asset.py
@@ -873,8 +873,9 @@
self.assertRaises(frappe.ValidationError, asset.save)
def test_number_of_depreciations(self):
- """Tests if an error is raised when number_of_depreciations_booked > total_number_of_depreciations."""
+ """Tests if an error is raised when number_of_depreciations_booked >= total_number_of_depreciations."""
+ # number_of_depreciations_booked > total_number_of_depreciations
asset = create_asset(
item_code = "Macbook Pro",
calculate_depreciation = 1,
@@ -889,6 +890,21 @@
self.assertRaises(frappe.ValidationError, asset.save)
+ # number_of_depreciations_booked = total_number_of_depreciations
+ asset_2 = create_asset(
+ item_code = "Macbook Pro",
+ calculate_depreciation = 1,
+ available_for_use_date = "2019-12-31",
+ total_number_of_depreciations = 5,
+ expected_value_after_useful_life = 10000,
+ depreciation_start_date = "2020-07-01",
+ opening_accumulated_depreciation = 10000,
+ number_of_depreciations_booked = 5,
+ do_not_save = 1
+ )
+
+ self.assertRaises(frappe.ValidationError, asset_2.save)
+
def test_depreciation_start_date_is_before_purchase_date(self):
asset = create_asset(
item_code = "Macbook Pro",
@@ -1264,7 +1280,7 @@
if not args.do_not_save:
try:
- asset.save()
+ asset.insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
@@ -1305,7 +1321,7 @@
"is_grouped_asset": is_grouped_asset,
"asset_naming_series": naming_series
})
- item.insert()
+ item.insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
return item
diff --git a/erpnext/assets/doctype/asset_category/test_asset_category.py b/erpnext/assets/doctype/asset_category/test_asset_category.py
index 3d19fa3..2f52248 100644
--- a/erpnext/assets/doctype/asset_category/test_asset_category.py
+++ b/erpnext/assets/doctype/asset_category/test_asset_category.py
@@ -23,7 +23,7 @@
})
try:
- asset_category.insert()
+ asset_category.insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
diff --git a/erpnext/assets/doctype/asset_maintenance/asset_maintenance.js b/erpnext/assets/doctype/asset_maintenance/asset_maintenance.js
index 52996e9..5c03b98 100644
--- a/erpnext/assets/doctype/asset_maintenance/asset_maintenance.js
+++ b/erpnext/assets/doctype/asset_maintenance/asset_maintenance.js
@@ -48,7 +48,7 @@
<div class='col-sm-3 small'>
<a onclick="frappe.set_route('List', 'Asset Maintenance Log',
{'asset_name': '${d.asset_name}','maintenance_status': '${d.maintenance_status}' });">
- ${d.maintenance_status} <span class="badge">${d.count}</span>
+ ${__(d.maintenance_status)} <span class="badge">${d.count}</span>
</a>
</div>
</div>`).appendTo(rows);
diff --git a/erpnext/assets/doctype/asset_repair/asset_repair.js b/erpnext/assets/doctype/asset_repair/asset_repair.js
index d554d52..3fe6b2d 100644
--- a/erpnext/assets/doctype/asset_repair/asset_repair.js
+++ b/erpnext/assets/doctype/asset_repair/asset_repair.js
@@ -68,6 +68,28 @@
});
frappe.ui.form.on('Asset Repair Consumed Item', {
+ item_code: function(frm, cdt, cdn) {
+ var item = locals[cdt][cdn];
+
+ let item_args = {
+ 'item_code': item.item_code,
+ 'warehouse': frm.doc.warehouse,
+ 'qty': item.consumed_quantity,
+ 'serial_no': item.serial_no,
+ 'company': frm.doc.company
+ };
+
+ frappe.call({
+ method: 'erpnext.stock.utils.get_incoming_rate',
+ args: {
+ args: item_args
+ },
+ callback: function(r) {
+ frappe.model.set_value(cdt, cdn, 'valuation_rate', r.message);
+ }
+ });
+ },
+
consumed_quantity: function(frm, cdt, cdn) {
var row = locals[cdt][cdn];
frappe.model.set_value(cdt, cdn, 'total_value', row.consumed_quantity * row.valuation_rate);
diff --git a/erpnext/assets/doctype/asset_repair_consumed_item/asset_repair_consumed_item.json b/erpnext/assets/doctype/asset_repair_consumed_item/asset_repair_consumed_item.json
index f63add1..4685a09 100644
--- a/erpnext/assets/doctype/asset_repair_consumed_item/asset_repair_consumed_item.json
+++ b/erpnext/assets/doctype/asset_repair_consumed_item/asset_repair_consumed_item.json
@@ -13,12 +13,10 @@
],
"fields": [
{
- "fetch_from": "item.valuation_rate",
"fieldname": "valuation_rate",
"fieldtype": "Currency",
"in_list_view": 1,
- "label": "Valuation Rate",
- "read_only": 1
+ "label": "Valuation Rate"
},
{
"fieldname": "consumed_quantity",
@@ -49,7 +47,7 @@
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
- "modified": "2021-11-11 18:23:00.492483",
+ "modified": "2022-02-08 17:37:20.028290",
"modified_by": "Administrator",
"module": "Assets",
"name": "Asset Repair Consumed Item",
diff --git a/erpnext/non_profit/__init__.py b/erpnext/bulk_transaction/__init__.py
similarity index 100%
rename from erpnext/non_profit/__init__.py
rename to erpnext/bulk_transaction/__init__.py
diff --git a/erpnext/non_profit/doctype/__init__.py b/erpnext/bulk_transaction/doctype/__init__.py
similarity index 100%
rename from erpnext/non_profit/doctype/__init__.py
rename to erpnext/bulk_transaction/doctype/__init__.py
diff --git a/erpnext/accounts/print_format/gst_pos_invoice/__init__.py b/erpnext/bulk_transaction/doctype/bulk_transaction_log/__init__.py
similarity index 100%
rename from erpnext/accounts/print_format/gst_pos_invoice/__init__.py
rename to erpnext/bulk_transaction/doctype/bulk_transaction_log/__init__.py
diff --git a/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.js b/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.js
new file mode 100644
index 0000000..0073170
--- /dev/null
+++ b/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.js
@@ -0,0 +1,30 @@
+// Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+
+frappe.ui.form.on('Bulk Transaction Log', {
+
+ refresh: function(frm) {
+ frm.disable_save();
+ frm.add_custom_button(__('Retry Failed Transactions'), ()=>{
+ frappe.confirm(__("Retry Failing Transactions ?"), ()=>{
+ query(frm, 1);
+ }
+ );
+ });
+ }
+});
+
+function query(frm) {
+ frappe.call({
+ method: "erpnext.bulk_transaction.doctype.bulk_transaction_log.bulk_transaction_log.retry_failing_transaction",
+ args: {
+ log_date: frm.doc.log_date
+ }
+ }).then((r) => {
+ if (r.message === "No Failed Records") {
+ frappe.show_alert(__(r.message), 5);
+ } else {
+ frappe.show_alert(__("Retrying Failed Transactions"), 5);
+ }
+ });
+}
\ No newline at end of file
diff --git a/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.json b/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.json
new file mode 100644
index 0000000..da42cf1
--- /dev/null
+++ b/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.json
@@ -0,0 +1,51 @@
+{
+ "actions": [],
+ "allow_rename": 1,
+ "creation": "2021-11-30 13:41:16.343827",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+ "log_date",
+ "logger_data"
+ ],
+ "fields": [
+ {
+ "fieldname": "log_date",
+ "fieldtype": "Date",
+ "label": "Log Date",
+ "read_only": 1
+ },
+ {
+ "fieldname": "logger_data",
+ "fieldtype": "Table",
+ "label": "Logger Data",
+ "options": "Bulk Transaction Log Detail"
+ }
+ ],
+ "index_web_pages_for_search": 1,
+ "links": [],
+ "modified": "2022-02-03 17:23:02.935325",
+ "modified_by": "Administrator",
+ "module": "Bulk Transaction",
+ "name": "Bulk Transaction Log",
+ "owner": "Administrator",
+ "permissions": [
+ {
+ "create": 1,
+ "delete": 1,
+ "email": 1,
+ "export": 1,
+ "print": 1,
+ "read": 1,
+ "report": 1,
+ "role": "System Manager",
+ "share": 1,
+ "write": 1
+ }
+ ],
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "states": [],
+ "track_changes": 1
+}
\ No newline at end of file
diff --git a/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.py b/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.py
new file mode 100644
index 0000000..92f37f5
--- /dev/null
+++ b/erpnext/bulk_transaction/doctype/bulk_transaction_log/bulk_transaction_log.py
@@ -0,0 +1,66 @@
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+from datetime import date
+
+import frappe
+from frappe.model.document import Document
+
+from erpnext.utilities.bulk_transaction import task, update_logger
+
+
+class BulkTransactionLog(Document):
+ pass
+
+
+@frappe.whitelist()
+def retry_failing_transaction(log_date=None):
+ if not log_date:
+ log_date = str(date.today())
+ btp = frappe.qb.DocType("Bulk Transaction Log Detail")
+ data = (
+ frappe.qb.from_(btp)
+ .select(btp.transaction_name, btp.from_doctype, btp.to_doctype)
+ .distinct()
+ .where(btp.retried != 1)
+ .where(btp.transaction_status == "Failed")
+ .where(btp.date == log_date)
+ ).run(as_dict=True)
+
+ if data :
+ if len(data) > 10:
+ frappe.enqueue(job, queue="long", job_name="bulk_retry", data=data, log_date=log_date)
+ else:
+ job(data, log_date)
+ else:
+ return "No Failed Records"
+
+def job(data, log_date):
+ for d in data:
+ failed = []
+ try:
+ frappe.db.savepoint("before_creation_of_record")
+ task(d.transaction_name, d.from_doctype, d.to_doctype)
+ except Exception as e:
+ frappe.db.rollback(save_point="before_creation_of_record")
+ failed.append(e)
+ update_logger(
+ d.transaction_name,
+ e,
+ d.from_doctype,
+ d.to_doctype,
+ status="Failed",
+ log_date=log_date,
+ restarted=1
+ )
+
+ if not failed:
+ update_logger(
+ d.transaction_name,
+ None,
+ d.from_doctype,
+ d.to_doctype,
+ status="Success",
+ log_date=log_date,
+ restarted=1,
+ )
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
new file mode 100644
index 0000000..a78e697
--- /dev/null
+++ b/erpnext/bulk_transaction/doctype/bulk_transaction_log/test_bulk_transaction_log.py
@@ -0,0 +1,81 @@
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
+# See license.txt
+
+import unittest
+from datetime import date
+
+import frappe
+
+from erpnext.utilities.bulk_transaction import transaction_processing
+
+
+class TestBulkTransactionLog(unittest.TestCase):
+
+ def setUp(self):
+ create_company()
+ 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")
+ doc = frappe.get_doc("Bulk Transaction Log", str(date.today()))
+ for d in doc.get("logger_data"):
+ if d.transaction_name == so_name:
+ self.assertEqual(d.transaction_name, so_name)
+ self.assertEqual(d.transaction_status, "Success")
+ self.assertEqual(d.from_doctype, "Sales Order")
+ self.assertEqual(d.to_doctype, "Sales Invoice")
+ self.assertEqual(d.retried, 0)
+
+
+
+def create_company():
+ if not frappe.db.exists('Company', '_Test Company'):
+ frappe.get_doc({
+ 'doctype': 'Company',
+ 'company_name': '_Test Company',
+ 'country': 'India',
+ 'default_currency': 'INR'
+ }).insert()
+
+def create_customer():
+ if not frappe.db.exists('Customer', 'Bulk Customer'):
+ frappe.get_doc({
+ 'doctype': 'Customer',
+ 'customer_name': 'Bulk Customer'
+ }).insert()
+
+def create_item():
+ if not frappe.db.exists("Item", "MK"):
+ frappe.get_doc({
+ "doctype": "Item",
+ "item_code": "MK",
+ "item_name": "Milk",
+ "description": "Milk",
+ "item_group": "Products"
+ }).insert()
+
+def create_so(intent=None):
+ so = frappe.new_doc("Sales Order")
+ so.customer = "Bulk Customer"
+ so.company = "_Test Company"
+ so.transaction_date = date.today()
+
+ so.set_warehouse = "Finished Goods - _TC"
+ so.append("items", {
+ "item_code": "MK",
+ "delivery_date": date.today(),
+ "qty": 10,
+ "rate": 80,
+ })
+ so.insert()
+ so.submit()
+ return so.name
\ No newline at end of file
diff --git a/erpnext/regional/doctype/tax_exemption_80g_certificate_detail/__init__.py b/erpnext/bulk_transaction/doctype/bulk_transaction_log_detail/__init__.py
similarity index 100%
rename from erpnext/regional/doctype/tax_exemption_80g_certificate_detail/__init__.py
rename to erpnext/bulk_transaction/doctype/bulk_transaction_log_detail/__init__.py
diff --git a/erpnext/bulk_transaction/doctype/bulk_transaction_log_detail/bulk_transaction_log_detail.json b/erpnext/bulk_transaction/doctype/bulk_transaction_log_detail/bulk_transaction_log_detail.json
new file mode 100644
index 0000000..8262caa
--- /dev/null
+++ b/erpnext/bulk_transaction/doctype/bulk_transaction_log_detail/bulk_transaction_log_detail.json
@@ -0,0 +1,86 @@
+{
+ "actions": [],
+ "allow_rename": 1,
+ "creation": "2021-11-30 13:38:30.926047",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+ "transaction_name",
+ "date",
+ "time",
+ "transaction_status",
+ "error_description",
+ "from_doctype",
+ "to_doctype",
+ "retried"
+ ],
+ "fields": [
+ {
+ "fieldname": "transaction_name",
+ "fieldtype": "Dynamic Link",
+ "in_list_view": 1,
+ "label": "Name",
+ "options": "from_doctype"
+ },
+ {
+ "fieldname": "transaction_status",
+ "fieldtype": "Data",
+ "in_list_view": 1,
+ "label": "Status",
+ "read_only": 1
+ },
+ {
+ "fieldname": "error_description",
+ "fieldtype": "Long Text",
+ "label": "Error Description",
+ "read_only": 1
+ },
+ {
+ "fieldname": "from_doctype",
+ "fieldtype": "Link",
+ "label": "From Doctype",
+ "options": "DocType",
+ "read_only": 1
+ },
+ {
+ "fieldname": "to_doctype",
+ "fieldtype": "Link",
+ "label": "To Doctype",
+ "options": "DocType",
+ "read_only": 1
+ },
+ {
+ "fieldname": "date",
+ "fieldtype": "Date",
+ "in_list_view": 1,
+ "label": "Date ",
+ "read_only": 1
+ },
+ {
+ "fieldname": "time",
+ "fieldtype": "Time",
+ "label": "Time",
+ "read_only": 1
+ },
+ {
+ "fieldname": "retried",
+ "fieldtype": "Int",
+ "label": "Retried",
+ "read_only": 1
+ }
+ ],
+ "index_web_pages_for_search": 1,
+ "istable": 1,
+ "links": [],
+ "modified": "2022-02-03 19:57:31.650359",
+ "modified_by": "Administrator",
+ "module": "Bulk Transaction",
+ "name": "Bulk Transaction Log Detail",
+ "owner": "Administrator",
+ "permissions": [],
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "states": [],
+ "track_changes": 1
+}
\ No newline at end of file
diff --git a/erpnext/regional/doctype/tax_exemption_80g_certificate_detail/tax_exemption_80g_certificate_detail.py b/erpnext/bulk_transaction/doctype/bulk_transaction_log_detail/bulk_transaction_log_detail.py
similarity index 77%
rename from erpnext/regional/doctype/tax_exemption_80g_certificate_detail/tax_exemption_80g_certificate_detail.py
rename to erpnext/bulk_transaction/doctype/bulk_transaction_log_detail/bulk_transaction_log_detail.py
index bb7f07f..67795b9 100644
--- a/erpnext/regional/doctype/tax_exemption_80g_certificate_detail/tax_exemption_80g_certificate_detail.py
+++ b/erpnext/bulk_transaction/doctype/bulk_transaction_log_detail/bulk_transaction_log_detail.py
@@ -1,10 +1,9 @@
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
-
# import frappe
from frappe.model.document import Document
-class TaxExemption80GCertificateDetail(Document):
+class BulkTransactionLogDetail(Document):
pass
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.py b/erpnext/buying/doctype/purchase_order/purchase_order.py
index 1b5f35e..2e7d306 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.py
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.py
@@ -316,6 +316,16 @@
'target_ref_field': 'stock_qty',
'source_field': 'stock_qty'
})
+ self.status_updater.append({
+ 'source_dt': 'Purchase Order Item',
+ 'target_dt': 'Packed Item',
+ 'target_field': 'ordered_qty',
+ 'target_parent_dt': 'Sales Order',
+ 'target_parent_field': '',
+ 'join_field': 'sales_order_packed_item',
+ 'target_ref_field': 'qty',
+ 'source_field': 'stock_qty'
+ })
def update_delivered_qty_in_sales_order(self):
"""Update delivered qty in Sales Order for drop ship"""
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order_list.js b/erpnext/buying/doctype/purchase_order/purchase_order_list.js
index 8413eb6..d7907e4 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order_list.js
+++ b/erpnext/buying/doctype/purchase_order/purchase_order_list.js
@@ -29,8 +29,22 @@
listview.call_for_selected_items(method, { "status": "Closed" });
});
- listview.page.add_menu_item(__("Re-open"), function () {
+ listview.page.add_menu_item(__("Reopen"), function () {
listview.call_for_selected_items(method, { "status": "Submitted" });
});
+
+
+ listview.page.add_action_item(__("Purchase Invoice"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Purchase Order", "Purchase Invoice");
+ });
+
+ listview.page.add_action_item(__("Purchase Receipt"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Purchase Order", "Purchase Receipt");
+ });
+
+ listview.page.add_action_item(__("Advance Payment"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Purchase Order", "Advance Payment");
+ });
+
}
};
diff --git a/erpnext/buying/doctype/purchase_order/test_purchase_order.py b/erpnext/buying/doctype/purchase_order/test_purchase_order.py
index 9a63afc..efa2ab1 100644
--- a/erpnext/buying/doctype/purchase_order/test_purchase_order.py
+++ b/erpnext/buying/doctype/purchase_order/test_purchase_order.py
@@ -3,9 +3,9 @@
import json
-import unittest
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import add_days, flt, getdate, nowdate
from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
@@ -27,7 +27,7 @@
from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
-class TestPurchaseOrder(unittest.TestCase):
+class TestPurchaseOrder(FrappeTestCase):
def test_make_purchase_receipt(self):
po = create_purchase_order(do_not_submit=True)
self.assertRaises(frappe.ValidationError, make_purchase_receipt, po.name)
@@ -682,17 +682,18 @@
bin1 = frappe.db.get_value("Bin",
filters={"warehouse": "_Test Warehouse - _TC", "item_code": "_Test Item"},
- fieldname=["reserved_qty_for_sub_contract", "projected_qty"], as_dict=1)
+ fieldname=["reserved_qty_for_sub_contract", "projected_qty", "modified"], as_dict=1)
# Submit PO
po = create_purchase_order(item_code="_Test FG Item", is_subcontracted="Yes")
bin2 = frappe.db.get_value("Bin",
filters={"warehouse": "_Test Warehouse - _TC", "item_code": "_Test Item"},
- fieldname=["reserved_qty_for_sub_contract", "projected_qty"], as_dict=1)
+ fieldname=["reserved_qty_for_sub_contract", "projected_qty", "modified"], as_dict=1)
self.assertEqual(bin2.reserved_qty_for_sub_contract, bin1.reserved_qty_for_sub_contract + 10)
self.assertEqual(bin2.projected_qty, bin1.projected_qty - 10)
+ self.assertNotEqual(bin1.modified, bin2.modified)
# Create stock transfer
rm_item = [{"item_code":"_Test FG Item","rm_item_code":"_Test Item","item_name":"_Test Item",
diff --git a/erpnext/buying/doctype/purchase_order_item/purchase_order_item.json b/erpnext/buying/doctype/purchase_order_item/purchase_order_item.json
index 87cd575..a18c527 100644
--- a/erpnext/buying/doctype/purchase_order_item/purchase_order_item.json
+++ b/erpnext/buying/doctype/purchase_order_item/purchase_order_item.json
@@ -63,6 +63,7 @@
"material_request_item",
"sales_order",
"sales_order_item",
+ "sales_order_packed_item",
"supplier_quotation",
"supplier_quotation_item",
"col_break5",
@@ -837,21 +838,30 @@
"label": "Product Bundle",
"options": "Product Bundle",
"read_only": 1
+ },
+ {
+ "fieldname": "sales_order_packed_item",
+ "fieldtype": "Data",
+ "label": "Sales Order Packed Item",
+ "no_copy": 1,
+ "print_hide": 1
}
],
"idx": 1,
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
- "modified": "2021-08-30 20:06:26.712097",
+ "modified": "2022-02-02 13:10:18.398976",
"modified_by": "Administrator",
"module": "Buying",
"name": "Purchase Order Item",
+ "naming_rule": "Random",
"owner": "Administrator",
"permissions": [],
"quick_entry": 1,
"search_fields": "item_name",
"sort_field": "modified",
"sort_order": "DESC",
+ "states": [],
"track_changes": 1
}
\ No newline at end of file
diff --git a/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py b/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py
index 5190199..5b21124 100644
--- a/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py
+++ b/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py
@@ -1,9 +1,9 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
-import unittest
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import nowdate
from erpnext.buying.doctype.request_for_quotation.request_for_quotation import (
@@ -16,7 +16,7 @@
from erpnext.templates.pages.rfq import check_supplier_has_docname_access
-class TestRequestforQuotation(unittest.TestCase):
+class TestRequestforQuotation(FrappeTestCase):
def test_quote_status(self):
rfq = make_request_for_quotation()
diff --git a/erpnext/buying/doctype/supplier/test_supplier.py b/erpnext/buying/doctype/supplier/test_supplier.py
index 13fe9df..7358e2a 100644
--- a/erpnext/buying/doctype/supplier/test_supplier.py
+++ b/erpnext/buying/doctype/supplier/test_supplier.py
@@ -1,7 +1,6 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
-import unittest
import frappe
from frappe.test_runner import make_test_records
@@ -12,153 +11,154 @@
test_dependencies = ['Payment Term', 'Payment Terms Template']
test_records = frappe.get_test_records('Supplier')
+from frappe.tests.utils import FrappeTestCase
-class TestSupplier(unittest.TestCase):
- def test_get_supplier_group_details(self):
- doc = frappe.new_doc("Supplier Group")
- doc.supplier_group_name = "_Testing Supplier Group"
- doc.payment_terms = "_Test Payment Term Template 3"
- doc.accounts = []
- test_account_details = {
- "company": "_Test Company",
- "account": "Creditors - _TC",
- }
- doc.append("accounts", test_account_details)
- doc.save()
- s_doc = frappe.new_doc("Supplier")
- s_doc.supplier_name = "Testing Supplier"
- s_doc.supplier_group = "_Testing Supplier Group"
- s_doc.payment_terms = ""
- s_doc.accounts = []
- s_doc.insert()
- s_doc.get_supplier_group_details()
- self.assertEqual(s_doc.payment_terms, "_Test Payment Term Template 3")
- self.assertEqual(s_doc.accounts[0].company, "_Test Company")
- self.assertEqual(s_doc.accounts[0].account, "Creditors - _TC")
- s_doc.delete()
- doc.delete()
- def test_supplier_default_payment_terms(self):
- # Payment Term based on Days after invoice date
- frappe.db.set_value(
- "Supplier", "_Test Supplier With Template 1", "payment_terms", "_Test Payment Term Template 3")
+class TestSupplier(FrappeTestCase):
+ def test_get_supplier_group_details(self):
+ doc = frappe.new_doc("Supplier Group")
+ doc.supplier_group_name = "_Testing Supplier Group"
+ doc.payment_terms = "_Test Payment Term Template 3"
+ doc.accounts = []
+ test_account_details = {
+ "company": "_Test Company",
+ "account": "Creditors - _TC",
+ }
+ doc.append("accounts", test_account_details)
+ doc.save()
+ s_doc = frappe.new_doc("Supplier")
+ s_doc.supplier_name = "Testing Supplier"
+ s_doc.supplier_group = "_Testing Supplier Group"
+ s_doc.payment_terms = ""
+ s_doc.accounts = []
+ s_doc.insert()
+ s_doc.get_supplier_group_details()
+ self.assertEqual(s_doc.payment_terms, "_Test Payment Term Template 3")
+ self.assertEqual(s_doc.accounts[0].company, "_Test Company")
+ self.assertEqual(s_doc.accounts[0].account, "Creditors - _TC")
+ s_doc.delete()
+ doc.delete()
- due_date = get_due_date("2016-01-22", "Supplier", "_Test Supplier With Template 1")
- self.assertEqual(due_date, "2016-02-21")
+ def test_supplier_default_payment_terms(self):
+ # Payment Term based on Days after invoice date
+ frappe.db.set_value(
+ "Supplier", "_Test Supplier With Template 1", "payment_terms", "_Test Payment Term Template 3")
- due_date = get_due_date("2017-01-22", "Supplier", "_Test Supplier With Template 1")
- self.assertEqual(due_date, "2017-02-21")
+ due_date = get_due_date("2016-01-22", "Supplier", "_Test Supplier With Template 1")
+ self.assertEqual(due_date, "2016-02-21")
- # Payment Term based on last day of month
- frappe.db.set_value(
- "Supplier", "_Test Supplier With Template 1", "payment_terms", "_Test Payment Term Template 1")
+ due_date = get_due_date("2017-01-22", "Supplier", "_Test Supplier With Template 1")
+ self.assertEqual(due_date, "2017-02-21")
- due_date = get_due_date("2016-01-22", "Supplier", "_Test Supplier With Template 1")
- self.assertEqual(due_date, "2016-02-29")
+ # Payment Term based on last day of month
+ frappe.db.set_value(
+ "Supplier", "_Test Supplier With Template 1", "payment_terms", "_Test Payment Term Template 1")
- due_date = get_due_date("2017-01-22", "Supplier", "_Test Supplier With Template 1")
- self.assertEqual(due_date, "2017-02-28")
+ due_date = get_due_date("2016-01-22", "Supplier", "_Test Supplier With Template 1")
+ self.assertEqual(due_date, "2016-02-29")
- frappe.db.set_value("Supplier", "_Test Supplier With Template 1", "payment_terms", "")
+ due_date = get_due_date("2017-01-22", "Supplier", "_Test Supplier With Template 1")
+ self.assertEqual(due_date, "2017-02-28")
- # Set credit limit for the supplier group instead of supplier and evaluate the due date
- frappe.db.set_value("Supplier Group", "_Test Supplier Group", "payment_terms", "_Test Payment Term Template 3")
+ frappe.db.set_value("Supplier", "_Test Supplier With Template 1", "payment_terms", "")
- due_date = get_due_date("2016-01-22", "Supplier", "_Test Supplier With Template 1")
- self.assertEqual(due_date, "2016-02-21")
+ # Set credit limit for the supplier group instead of supplier and evaluate the due date
+ frappe.db.set_value("Supplier Group", "_Test Supplier Group", "payment_terms", "_Test Payment Term Template 3")
- # Payment terms for Supplier Group instead of supplier and evaluate the due date
- frappe.db.set_value("Supplier Group", "_Test Supplier Group", "payment_terms", "_Test Payment Term Template 1")
+ due_date = get_due_date("2016-01-22", "Supplier", "_Test Supplier With Template 1")
+ self.assertEqual(due_date, "2016-02-21")
- # Leap year
- due_date = get_due_date("2016-01-22", "Supplier", "_Test Supplier With Template 1")
- self.assertEqual(due_date, "2016-02-29")
- # # Non Leap year
- due_date = get_due_date("2017-01-22", "Supplier", "_Test Supplier With Template 1")
- self.assertEqual(due_date, "2017-02-28")
+ # Payment terms for Supplier Group instead of supplier and evaluate the due date
+ frappe.db.set_value("Supplier Group", "_Test Supplier Group", "payment_terms", "_Test Payment Term Template 1")
- # Supplier with no default Payment Terms Template
- frappe.db.set_value("Supplier Group", "_Test Supplier Group", "payment_terms", "")
- frappe.db.set_value("Supplier", "_Test Supplier", "payment_terms", "")
+ # Leap year
+ due_date = get_due_date("2016-01-22", "Supplier", "_Test Supplier With Template 1")
+ self.assertEqual(due_date, "2016-02-29")
+ # # Non Leap year
+ due_date = get_due_date("2017-01-22", "Supplier", "_Test Supplier With Template 1")
+ self.assertEqual(due_date, "2017-02-28")
- due_date = get_due_date("2016-01-22", "Supplier", "_Test Supplier")
- self.assertEqual(due_date, "2016-01-22")
- # # Non Leap year
- due_date = get_due_date("2017-01-22", "Supplier", "_Test Supplier")
- self.assertEqual(due_date, "2017-01-22")
+ # Supplier with no default Payment Terms Template
+ frappe.db.set_value("Supplier Group", "_Test Supplier Group", "payment_terms", "")
+ frappe.db.set_value("Supplier", "_Test Supplier", "payment_terms", "")
- def test_supplier_disabled(self):
- make_test_records("Item")
+ due_date = get_due_date("2016-01-22", "Supplier", "_Test Supplier")
+ self.assertEqual(due_date, "2016-01-22")
+ # # Non Leap year
+ due_date = get_due_date("2017-01-22", "Supplier", "_Test Supplier")
+ self.assertEqual(due_date, "2017-01-22")
- frappe.db.set_value("Supplier", "_Test Supplier", "disabled", 1)
+ def test_supplier_disabled(self):
+ make_test_records("Item")
- from erpnext.buying.doctype.purchase_order.test_purchase_order import create_purchase_order
+ frappe.db.set_value("Supplier", "_Test Supplier", "disabled", 1)
- po = create_purchase_order(do_not_save=True)
+ from erpnext.buying.doctype.purchase_order.test_purchase_order import create_purchase_order
- self.assertRaises(PartyDisabled, po.save)
+ po = create_purchase_order(do_not_save=True)
- frappe.db.set_value("Supplier", "_Test Supplier", "disabled", 0)
+ self.assertRaises(PartyDisabled, po.save)
- po.save()
+ frappe.db.set_value("Supplier", "_Test Supplier", "disabled", 0)
- def test_supplier_country(self):
- # Test that country field exists in Supplier DocType
- supplier = frappe.get_doc('Supplier', '_Test Supplier with Country')
- self.assertTrue('country' in supplier.as_dict())
+ po.save()
- # Test if test supplier field record is 'Greece'
- self.assertEqual(supplier.country, "Greece")
+ def test_supplier_country(self):
+ # Test that country field exists in Supplier DocType
+ supplier = frappe.get_doc('Supplier', '_Test Supplier with Country')
+ self.assertTrue('country' in supplier.as_dict())
- # Test update Supplier instance country value
- supplier = frappe.get_doc('Supplier', '_Test Supplier')
- supplier.country = 'Greece'
- supplier.save()
- self.assertEqual(supplier.country, "Greece")
+ # Test if test supplier field record is 'Greece'
+ self.assertEqual(supplier.country, "Greece")
- def test_party_details_tax_category(self):
- from erpnext.accounts.party import get_party_details
+ # Test update Supplier instance country value
+ supplier = frappe.get_doc('Supplier', '_Test Supplier')
+ supplier.country = 'Greece'
+ supplier.save()
+ self.assertEqual(supplier.country, "Greece")
- frappe.delete_doc_if_exists("Address", "_Test Address With Tax Category-Billing")
+ def test_party_details_tax_category(self):
+ from erpnext.accounts.party import get_party_details
- # Tax Category without Address
- details = get_party_details("_Test Supplier With Tax Category", party_type="Supplier")
- self.assertEqual(details.tax_category, "_Test Tax Category 1")
+ frappe.delete_doc_if_exists("Address", "_Test Address With Tax Category-Billing")
- address = frappe.get_doc(dict(
- doctype='Address',
- address_title='_Test Address With Tax Category',
- tax_category='_Test Tax Category 2',
- address_type='Billing',
- address_line1='Station Road',
- city='_Test City',
- country='India',
- links=[dict(
- link_doctype='Supplier',
- link_name='_Test Supplier With Tax Category'
- )]
- )).insert()
+ # Tax Category without Address
+ details = get_party_details("_Test Supplier With Tax Category", party_type="Supplier")
+ self.assertEqual(details.tax_category, "_Test Tax Category 1")
- # Tax Category with Address
- details = get_party_details("_Test Supplier With Tax Category", party_type="Supplier")
- self.assertEqual(details.tax_category, "_Test Tax Category 2")
+ address = frappe.get_doc(dict(
+ doctype='Address',
+ address_title='_Test Address With Tax Category',
+ tax_category='_Test Tax Category 2',
+ address_type='Billing',
+ address_line1='Station Road',
+ city='_Test City',
+ country='India',
+ links=[dict(
+ link_doctype='Supplier',
+ link_name='_Test Supplier With Tax Category'
+ )]
+ )).insert()
- # Rollback
- address.delete()
+ # Tax Category with Address
+ details = get_party_details("_Test Supplier With Tax Category", party_type="Supplier")
+ self.assertEqual(details.tax_category, "_Test Tax Category 2")
+
+ # Rollback
+ address.delete()
def create_supplier(**args):
- args = frappe._dict(args)
+ args = frappe._dict(args)
- try:
- doc = frappe.get_doc({
- "doctype": "Supplier",
- "supplier_name": args.supplier_name,
- "supplier_group": args.supplier_group or "Services",
- "supplier_type": args.supplier_type or "Company",
- "tax_withholding_category": args.tax_withholding_category
- }).insert()
+ if frappe.db.exists("Supplier", args.supplier_name):
+ return frappe.get_doc("Supplier", args.supplier_name)
- return doc
+ doc = frappe.get_doc({
+ "doctype": "Supplier",
+ "supplier_name": args.supplier_name,
+ "supplier_group": args.supplier_group or "Services",
+ "supplier_type": args.supplier_type or "Company",
+ "tax_withholding_category": args.tax_withholding_category
+ }).insert()
- except frappe.DuplicateEntryError:
- return frappe.get_doc("Supplier", args.supplier_name)
+ return doc
diff --git a/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py b/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py
index d65ab94..171de78 100644
--- a/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py
+++ b/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py
@@ -143,6 +143,26 @@
return doclist
@frappe.whitelist()
+def make_purchase_invoice(source_name, target_doc=None):
+ doc = get_mapped_doc("Supplier Quotation", source_name, {
+ "Supplier Quotation": {
+ "doctype": "Purchase Invoice",
+ "validation": {
+ "docstatus": ["=", 1],
+ }
+ },
+ "Supplier Quotation Item": {
+ "doctype": "Purchase Invoice Item"
+ },
+ "Purchase Taxes and Charges": {
+ "doctype": "Purchase Taxes and Charges"
+ }
+ }, target_doc)
+
+ return doc
+
+
+@frappe.whitelist()
def make_quotation(source_name, target_doc=None):
doclist = get_mapped_doc("Supplier Quotation", source_name, {
"Supplier Quotation": {
diff --git a/erpnext/buying/doctype/supplier_quotation/supplier_quotation_list.js b/erpnext/buying/doctype/supplier_quotation/supplier_quotation_list.js
index 5ab6c98..73685ca 100644
--- a/erpnext/buying/doctype/supplier_quotation/supplier_quotation_list.js
+++ b/erpnext/buying/doctype/supplier_quotation/supplier_quotation_list.js
@@ -8,5 +8,15 @@
} else if(doc.status==="Expired") {
return [__("Expired"), "gray", "status,=,Expired"];
}
+ },
+
+ onload: function(listview) {
+ listview.page.add_action_item(__("Purchase Order"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Supplier Quotation", "Purchase Order");
+ });
+
+ listview.page.add_action_item(__("Purchase Invoice"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Supplier Quotation", "Purchase Invoice");
+ });
}
};
diff --git a/erpnext/buying/doctype/supplier_quotation/test_supplier_quotation.py b/erpnext/buying/doctype/supplier_quotation/test_supplier_quotation.py
index d48ac7e..a4d4597 100644
--- a/erpnext/buying/doctype/supplier_quotation/test_supplier_quotation.py
+++ b/erpnext/buying/doctype/supplier_quotation/test_supplier_quotation.py
@@ -3,12 +3,12 @@
-import unittest
import frappe
+from frappe.tests.utils import FrappeTestCase
-class TestPurchaseOrder(unittest.TestCase):
+class TestPurchaseOrder(FrappeTestCase):
def test_make_purchase_order(self):
from erpnext.buying.doctype.supplier_quotation.supplier_quotation import make_purchase_order
diff --git a/erpnext/buying/doctype/supplier_scorecard/test_supplier_scorecard.py b/erpnext/buying/doctype/supplier_scorecard/test_supplier_scorecard.py
index 49e3351..8ecc2cd 100644
--- a/erpnext/buying/doctype/supplier_scorecard/test_supplier_scorecard.py
+++ b/erpnext/buying/doctype/supplier_scorecard/test_supplier_scorecard.py
@@ -1,12 +1,12 @@
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
-import unittest
import frappe
+from frappe.tests.utils import FrappeTestCase
-class TestSupplierScorecard(unittest.TestCase):
+class TestSupplierScorecard(FrappeTestCase):
def test_create_scorecard(self):
doc = make_supplier_scorecard().insert()
@@ -49,7 +49,7 @@
"min_grade":0.0,"name":"Very Poor",
"prevent_rfqs":1,
"notify_supplier":0,
- "doctype":"Supplier Scorecard Standing",
+ "doctype":"Supplier Scorecard Scoring Standing",
"max_grade":30.0,
"prevent_pos":1,
"warn_pos":0,
@@ -65,7 +65,7 @@
"name":"Poor",
"prevent_rfqs":1,
"notify_supplier":0,
- "doctype":"Supplier Scorecard Standing",
+ "doctype":"Supplier Scorecard Scoring Standing",
"max_grade":50.0,
"prevent_pos":0,
"warn_pos":0,
@@ -81,7 +81,7 @@
"name":"Average",
"prevent_rfqs":0,
"notify_supplier":0,
- "doctype":"Supplier Scorecard Standing",
+ "doctype":"Supplier Scorecard Scoring Standing",
"max_grade":80.0,
"prevent_pos":0,
"warn_pos":0,
@@ -97,7 +97,7 @@
"name":"Excellent",
"prevent_rfqs":0,
"notify_supplier":0,
- "doctype":"Supplier Scorecard Standing",
+ "doctype":"Supplier Scorecard Scoring Standing",
"max_grade":100.0,
"prevent_pos":0,
"warn_pos":0,
diff --git a/erpnext/buying/doctype/supplier_scorecard_criteria/test_supplier_scorecard_criteria.py b/erpnext/buying/doctype/supplier_scorecard_criteria/test_supplier_scorecard_criteria.py
index dacc982..7ff84c1 100644
--- a/erpnext/buying/doctype/supplier_scorecard_criteria/test_supplier_scorecard_criteria.py
+++ b/erpnext/buying/doctype/supplier_scorecard_criteria/test_supplier_scorecard_criteria.py
@@ -1,12 +1,12 @@
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
-import unittest
import frappe
+from frappe.tests.utils import FrappeTestCase
-class TestSupplierScorecardCriteria(unittest.TestCase):
+class TestSupplierScorecardCriteria(FrappeTestCase):
def test_variables_exist(self):
delete_test_scorecards()
for d in test_good_criteria:
diff --git a/erpnext/buying/doctype/supplier_scorecard_variable/test_supplier_scorecard_variable.py b/erpnext/buying/doctype/supplier_scorecard_variable/test_supplier_scorecard_variable.py
index 4d75981..32005a3 100644
--- a/erpnext/buying/doctype/supplier_scorecard_variable/test_supplier_scorecard_variable.py
+++ b/erpnext/buying/doctype/supplier_scorecard_variable/test_supplier_scorecard_variable.py
@@ -1,16 +1,16 @@
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
-import unittest
import frappe
+from frappe.tests.utils import FrappeTestCase
from erpnext.buying.doctype.supplier_scorecard_variable.supplier_scorecard_variable import (
VariablePathNotFound,
)
-class TestSupplierScorecardVariable(unittest.TestCase):
+class TestSupplierScorecardVariable(FrappeTestCase):
def test_variable_exist(self):
for d in test_existing_variables:
my_doc = frappe.get_doc("Supplier Scorecard Variable", d.get("name"))
diff --git a/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py b/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py
index 84de8c6..4452452 100644
--- a/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py
+++ b/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py
@@ -2,10 +2,10 @@
# For license information, please see license.txt
-import unittest
from datetime import datetime
import frappe
+from frappe.tests.utils import FrappeTestCase
from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt
from erpnext.buying.report.procurement_tracker.procurement_tracker import execute
@@ -14,7 +14,7 @@
from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
-class TestProcurementTracker(unittest.TestCase):
+class TestProcurementTracker(FrappeTestCase):
def test_result_for_procurement_tracker(self):
filters = {
'company': '_Test Procurement Company',
diff --git a/erpnext/buying/report/requested_items_to_order_and_receive/requested_items_to_order_and_receive.py b/erpnext/buying/report/requested_items_to_order_and_receive/requested_items_to_order_and_receive.py
index f98e5f1..60a8f92 100644
--- a/erpnext/buying/report/requested_items_to_order_and_receive/requested_items_to_order_and_receive.py
+++ b/erpnext/buying/report/requested_items_to_order_and_receive/requested_items_to_order_and_receive.py
@@ -6,6 +6,7 @@
import frappe
from frappe import _
+from frappe.query_builder.functions import Coalesce, Sum
from frappe.utils import date_diff, flt, getdate
@@ -16,12 +17,9 @@
validate_filters(filters)
columns = get_columns(filters)
- conditions = get_conditions(filters)
+ data = get_data(filters)
- #get queried data
- data = get_data(filters, conditions)
-
- #prepare data for report and chart views
+ # prepare data for report and chart views
data, chart_data = prepare_data(data, filters)
return columns, data, None, chart_data
@@ -34,53 +32,70 @@
elif date_diff(to_date, from_date) < 0:
frappe.throw(_("To Date cannot be before From Date."))
-def get_conditions(filters):
- conditions = ''
+def get_data(filters):
+ mr = frappe.qb.DocType("Material Request")
+ mr_item = frappe.qb.DocType("Material Request Item")
+ query = (
+ frappe.qb.from_(mr)
+ .join(mr_item).on(mr_item.parent == mr.name)
+ .select(
+ mr.name.as_("material_request"),
+ mr.transaction_date.as_("date"),
+ mr_item.schedule_date.as_("required_date"),
+ mr_item.item_code.as_("item_code"),
+ Sum(Coalesce(mr_item.stock_qty, 0)).as_("qty"),
+ Coalesce(mr_item.stock_uom, '').as_("uom"),
+ Sum(Coalesce(mr_item.ordered_qty, 0)).as_("ordered_qty"),
+ Sum(Coalesce(mr_item.received_qty, 0)).as_("received_qty"),
+ (
+ Sum(Coalesce(mr_item.stock_qty, 0)) - Sum(Coalesce(mr_item.received_qty, 0))
+ ).as_("qty_to_receive"),
+ Sum(Coalesce(mr_item.received_qty, 0)).as_("received_qty"),
+ (
+ Sum(Coalesce(mr_item.stock_qty, 0)) - Sum(Coalesce(mr_item.ordered_qty, 0))
+ ).as_("qty_to_order"),
+ mr_item.item_name,
+ mr_item.description,
+ mr.company
+ ).where(
+ (mr.material_request_type == "Purchase")
+ & (mr.docstatus == 1)
+ & (mr.status != "Stopped")
+ & (mr.per_received < 100)
+ )
+ )
+
+ query = get_conditions(filters, query, mr, mr_item) # add conditional conditions
+
+ query = (
+ query.groupby(
+ mr.name, mr_item.item_code
+ ).orderby(
+ mr.transaction_date, mr.schedule_date
+ )
+ )
+ data = query.run(as_dict=True)
+ return data
+
+def get_conditions(filters, query, mr, mr_item):
if filters.get("from_date") and filters.get("to_date"):
- conditions += " and mr.transaction_date between '{0}' and '{1}'".format(filters.get("from_date"),filters.get("to_date"))
-
+ query = (
+ query.where(
+ (mr.transaction_date >= filters.get("from_date"))
+ & (mr.transaction_date <= filters.get("to_date"))
+ )
+ )
if filters.get("company"):
- conditions += " and mr.company = '{0}'".format(filters.get("company"))
+ query = query.where(mr.company == filters.get("company"))
if filters.get("material_request"):
- conditions += " and mr.name = '{0}'".format(filters.get("material_request"))
+ query = query.where(mr.name == filters.get("material_request"))
if filters.get("item_code"):
- conditions += " and mr_item.item_code = '{0}'".format(filters.get("item_code"))
+ query = query.where(mr_item.item_code == filters.get("item_code"))
- return conditions
-
-def get_data(filters, conditions):
- data = frappe.db.sql("""
- select
- mr.name as material_request,
- mr.transaction_date as date,
- mr_item.schedule_date as required_date,
- mr_item.item_code as item_code,
- sum(ifnull(mr_item.stock_qty, 0)) as qty,
- ifnull(mr_item.stock_uom, '') as uom,
- sum(ifnull(mr_item.ordered_qty, 0)) as ordered_qty,
- sum(ifnull(mr_item.received_qty, 0)) as received_qty,
- (sum(ifnull(mr_item.stock_qty, 0)) - sum(ifnull(mr_item.received_qty, 0))) as qty_to_receive,
- (sum(ifnull(mr_item.stock_qty, 0)) - sum(ifnull(mr_item.ordered_qty, 0))) as qty_to_order,
- mr_item.item_name as item_name,
- mr_item.description as "description",
- mr.company as company
- from
- `tabMaterial Request` mr, `tabMaterial Request Item` mr_item
- where
- mr_item.parent = mr.name
- and mr.material_request_type = "Purchase"
- and mr.docstatus = 1
- and mr.status != "Stopped"
- {conditions}
- group by mr.name, mr_item.item_code
- having
- sum(ifnull(mr_item.ordered_qty, 0)) < sum(ifnull(mr_item.stock_qty, 0))
- order by mr.transaction_date, mr.schedule_date""".format(conditions=conditions), as_dict=1)
-
- return data
+ return query
def update_qty_columns(row_to_update, data_row):
fields = ["qty", "ordered_qty", "received_qty", "qty_to_receive", "qty_to_order"]
diff --git a/erpnext/buying/report/requested_items_to_order_and_receive/test_requested_items_to_order_and_receive.py b/erpnext/buying/report/requested_items_to_order_and_receive/test_requested_items_to_order_and_receive.py
new file mode 100644
index 0000000..f3c751c
--- /dev/null
+++ b/erpnext/buying/report/requested_items_to_order_and_receive/test_requested_items_to_order_and_receive.py
@@ -0,0 +1,69 @@
+# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
+# See license.txt
+
+import frappe
+from frappe.tests.utils import FrappeTestCase
+from frappe.utils import add_days, today
+
+from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt
+from erpnext.buying.report.requested_items_to_order_and_receive.requested_items_to_order_and_receive import (
+ get_data,
+)
+from erpnext.stock.doctype.item.test_item import create_item
+from erpnext.stock.doctype.material_request.material_request import make_purchase_order
+
+
+class TestRequestedItemsToOrderAndReceive(FrappeTestCase):
+ def setUp(self) -> None:
+ create_item("Test MR Report Item")
+ self.setup_material_request() # to order and receive
+ self.setup_material_request(order=True) # to receive (ordered)
+ self.setup_material_request(order=True, receive=True) # complete (ordered & received)
+
+ self.filters = frappe._dict(
+ company="_Test Company", from_date=today(), to_date=add_days(today(), 30),
+ item_code="Test MR Report Item"
+ )
+
+ def tearDown(self) -> None:
+ frappe.db.rollback()
+
+ def test_date_range(self):
+ data = get_data(self.filters)
+ self.assertEqual(len(data), 2) # MRs today should be fetched
+
+ self.filters.from_date = add_days(today(), 1)
+ data = get_data(self.filters)
+ self.assertEqual(len(data), 0) # MRs today should not be fetched as from date is tomorrow
+
+ def test_ordered_received_material_requests(self):
+ data = get_data(self.filters)
+
+ # from the 3 MRs made, only 2 (to receive) should be fetched
+ self.assertEqual(len(data), 2)
+ self.assertEqual(data[0].ordered_qty, 0.0)
+ self.assertEqual(data[1].ordered_qty, 57.0)
+
+ def setup_material_request(self, order=False, receive=False):
+ po = None
+ test_records = frappe.get_test_records('Material Request')
+
+ mr = frappe.copy_doc(test_records[0])
+ mr.transaction_date = today()
+ mr.schedule_date = add_days(today(), 1)
+ for row in mr.items:
+ row.item_code = "Test MR Report Item"
+ row.item_name = "Test MR Report Item"
+ row.description = "Test MR Report Item"
+ row.uom = "Nos"
+ row.schedule_date = add_days(today(), 1)
+ mr.submit()
+
+ if order or receive:
+ po = make_purchase_order(mr.name)
+ po.supplier = "_Test Supplier"
+ po.submit()
+ if receive:
+ pr = make_purchase_receipt(po.name)
+ pr.submit()
+
diff --git a/erpnext/buying/report/subcontracted_item_to_be_received/test_subcontracted_item_to_be_received.py b/erpnext/buying/report/subcontracted_item_to_be_received/test_subcontracted_item_to_be_received.py
index 144523a..c2b38d3 100644
--- a/erpnext/buying/report/subcontracted_item_to_be_received/test_subcontracted_item_to_be_received.py
+++ b/erpnext/buying/report/subcontracted_item_to_be_received/test_subcontracted_item_to_be_received.py
@@ -3,9 +3,9 @@
# Compiled at: 2019-05-06 09:51:46
# Decompiled by https://python-decompiler.com
-import unittest
import frappe
+from frappe.tests.utils import FrappeTestCase
from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt
from erpnext.buying.doctype.purchase_order.test_purchase_order import create_purchase_order
@@ -15,7 +15,7 @@
from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
-class TestSubcontractedItemToBeReceived(unittest.TestCase):
+class TestSubcontractedItemToBeReceived(FrappeTestCase):
def test_pending_and_received_qty(self):
po = create_purchase_order(item_code='_Test FG Item', is_subcontracted='Yes')
diff --git a/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/test_subcontracted_raw_materials_to_be_transferred.py b/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/test_subcontracted_raw_materials_to_be_transferred.py
index 3c203ac..fc9acab 100644
--- a/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/test_subcontracted_raw_materials_to_be_transferred.py
+++ b/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/test_subcontracted_raw_materials_to_be_transferred.py
@@ -4,9 +4,9 @@
# Decompiled by https://python-decompiler.com
import json
-import unittest
import frappe
+from frappe.tests.utils import FrappeTestCase
from erpnext.buying.doctype.purchase_order.purchase_order import make_rm_stock_entry
from erpnext.buying.doctype.purchase_order.test_purchase_order import create_purchase_order
@@ -16,7 +16,7 @@
from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
-class TestSubcontractedItemToBeTransferred(unittest.TestCase):
+class TestSubcontractedItemToBeTransferred(FrappeTestCase):
def test_pending_and_transferred_qty(self):
po = create_purchase_order(item_code='_Test FG Item', is_subcontracted='Yes', supplier_warehouse="_Test Warehouse 1 - _TC")
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index bab16a4..a94af10 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -407,6 +407,22 @@
if item_qty != len(get_serial_nos(item.get('serial_no'))):
item.set(fieldname, value)
+ elif (
+ ret.get("pricing_rule_removed")
+ and value is not None
+ and fieldname
+ in [
+ "discount_percentage",
+ "discount_amount",
+ "rate",
+ "margin_rate_or_amount",
+ "margin_type",
+ "remove_free_item",
+ ]
+ ):
+ # reset pricing rule fields if pricing_rule_removed
+ item.set(fieldname, value)
+
if self.doctype in ["Purchase Invoice", "Sales Invoice"] and item.meta.get_field('is_fixed_asset'):
item.set('is_fixed_asset', ret.get('is_fixed_asset', 0))
@@ -1318,6 +1334,9 @@
payment_schedule['discount_type'] = schedule.discount_type
payment_schedule['discount'] = schedule.discount
+ if not schedule.invoice_portion:
+ payment_schedule['payment_amount'] = schedule.payment_amount
+
self.append("payment_schedule", payment_schedule)
def set_due_date(self):
@@ -1547,13 +1566,12 @@
tax.rate = None
-def validate_account_head(tax, doc):
- company = frappe.get_cached_value('Account',
- tax.account_head, 'company')
+def validate_account_head(idx, account, company):
+ account_company = frappe.get_cached_value('Account', account, 'company')
- if company != doc.company:
+ if account_company != company:
frappe.throw(_('Row {0}: Account {1} does not belong to Company {2}')
- .format(tax.idx, frappe.bold(tax.account_head), frappe.bold(doc.company)), title=_('Invalid Account'))
+ .format(idx, frappe.bold(account), frappe.bold(company)), title=_('Invalid Account'))
def validate_cost_center(tax, doc):
@@ -1936,7 +1954,8 @@
qty_dict["ordered_qty"] = get_ordered_qty(row.item_code, row.warehouse)
- update_bin_qty(row.item_code, row.warehouse, qty_dict)
+ if row.warehouse:
+ update_bin_qty(row.item_code, row.warehouse, qty_dict)
def validate_and_delete_children(parent, data):
deleted_children = []
diff --git a/erpnext/controllers/buying_controller.py b/erpnext/controllers/buying_controller.py
index a181af7..b740476 100644
--- a/erpnext/controllers/buying_controller.py
+++ b/erpnext/controllers/buying_controller.py
@@ -249,6 +249,7 @@
"posting_time": self.get('posting_time'),
"qty": -1 * flt(d.get('stock_qty')),
"serial_no": d.get('serial_no'),
+ "batch_no": d.get("batch_no"),
"company": self.company,
"voucher_type": self.doctype,
"voucher_no": self.name,
@@ -278,7 +279,8 @@
"posting_date": self.posting_date,
"posting_time": self.posting_time,
"qty": -1 * d.consumed_qty,
- "serial_no": d.serial_no
+ "serial_no": d.serial_no,
+ "batch_no": d.batch_no,
})
if rate > 0:
diff --git a/erpnext/controllers/employee_boarding_controller.py b/erpnext/controllers/employee_boarding_controller.py
index ae2c737..dd02ce1 100644
--- a/erpnext/controllers/employee_boarding_controller.py
+++ b/erpnext/controllers/employee_boarding_controller.py
@@ -104,11 +104,11 @@
def get_task_dates(self, activity, holiday_list):
start_date = end_date = None
- if activity.begin_on:
+ if activity.begin_on is not None:
start_date = add_days(self.boarding_begins_on, activity.begin_on)
start_date = self.update_if_holiday(start_date, holiday_list)
- if activity.duration:
+ if activity.duration is not None:
end_date = add_days(self.boarding_begins_on, activity.begin_on + activity.duration)
end_date = self.update_if_holiday(end_date, holiday_list)
diff --git a/erpnext/controllers/sales_and_purchase_return.py b/erpnext/controllers/sales_and_purchase_return.py
index df3c5f1..8c3aab4 100644
--- a/erpnext/controllers/sales_and_purchase_return.py
+++ b/erpnext/controllers/sales_and_purchase_return.py
@@ -420,6 +420,7 @@
"posting_time": sle.get('posting_time'),
"qty": sle.actual_qty,
"serial_no": sle.get('serial_no'),
+ "batch_no": sle.get("batch_no"),
"company": sle.company,
"voucher_type": sle.voucher_type,
"voucher_no": sle.voucher_no
diff --git a/erpnext/controllers/selling_controller.py b/erpnext/controllers/selling_controller.py
index 31b2209..e918cde 100644
--- a/erpnext/controllers/selling_controller.py
+++ b/erpnext/controllers/selling_controller.py
@@ -394,6 +394,7 @@
"posting_time": self.get('posting_time') or nowtime(),
"qty": qty if cint(self.get("is_return")) else (-1 * qty),
"serial_no": d.get('serial_no'),
+ "batch_no": d.get("batch_no"),
"company": self.company,
"voucher_type": self.doctype,
"voucher_no": self.name,
diff --git a/erpnext/controllers/stock_controller.py b/erpnext/controllers/stock_controller.py
index 8d17683..8972c32 100644
--- a/erpnext/controllers/stock_controller.py
+++ b/erpnext/controllers/stock_controller.py
@@ -3,6 +3,7 @@
import json
from collections import defaultdict
+from typing import List, Tuple
import frappe
from frappe import _
@@ -181,33 +182,28 @@
return details
- def get_items_and_warehouses(self):
- items, warehouses = [], []
+ def get_items_and_warehouses(self) -> Tuple[List[str], List[str]]:
+ """Get list of items and warehouses affected by a transaction"""
- if hasattr(self, "items"):
- item_doclist = self.get("items")
- elif self.doctype == "Stock Reconciliation":
- item_doclist = []
- data = json.loads(self.reconciliation_json)
- for row in data[data.index(self.head_row)+1:]:
- d = frappe._dict(zip(["item_code", "warehouse", "qty", "valuation_rate"], row))
- item_doclist.append(d)
+ if not (hasattr(self, "items") or hasattr(self, "packed_items")):
+ return [], []
- if item_doclist:
- for d in item_doclist:
- if d.item_code and d.item_code not in items:
- items.append(d.item_code)
+ item_rows = (self.get("items") or []) + (self.get("packed_items") or [])
- if d.get("warehouse") and d.warehouse not in warehouses:
- warehouses.append(d.warehouse)
+ items = {d.item_code for d in item_rows if d.item_code}
- if self.doctype == "Stock Entry":
- if d.get("s_warehouse") and d.s_warehouse not in warehouses:
- warehouses.append(d.s_warehouse)
- if d.get("t_warehouse") and d.t_warehouse not in warehouses:
- warehouses.append(d.t_warehouse)
+ warehouses = set()
+ for d in item_rows:
+ if d.get("warehouse"):
+ warehouses.add(d.warehouse)
- return items, warehouses
+ if self.doctype == "Stock Entry":
+ if d.get("s_warehouse"):
+ warehouses.add(d.s_warehouse)
+ if d.get("t_warehouse"):
+ warehouses.add(d.t_warehouse)
+
+ return list(items), list(warehouses)
def get_stock_ledger_details(self):
stock_ledger = {}
@@ -219,7 +215,7 @@
from
`tabStock Ledger Entry`
where
- voucher_type=%s and voucher_no=%s
+ voucher_type=%s and voucher_no=%s and is_cancelled = 0
""", (self.doctype, self.name), as_dict=True)
for sle in stock_ledger_entries:
@@ -511,13 +507,41 @@
"voucher_no": self.name,
"company": self.company
})
- if future_sle_exists(args):
+
+ if future_sle_exists(args) or repost_required_for_queue(self):
item_based_reposting = cint(frappe.db.get_single_value("Stock Reposting Settings", "item_based_reposting"))
if item_based_reposting:
create_item_wise_repost_entries(voucher_type=self.doctype, voucher_no=self.name)
else:
create_repost_item_valuation_entry(args)
+def repost_required_for_queue(doc: StockController) -> bool:
+ """check if stock document contains repeated item-warehouse with queue based valuation.
+
+ if queue exists for repeated items then SLEs need to reprocessed in background again.
+ """
+
+ consuming_sles = frappe.db.get_all("Stock Ledger Entry",
+ filters={
+ "voucher_type": doc.doctype,
+ "voucher_no": doc.name,
+ "actual_qty": ("<", 0),
+ "is_cancelled": 0
+ },
+ fields=["item_code", "warehouse", "stock_queue"]
+ )
+ item_warehouses = [(sle.item_code, sle.warehouse) for sle in consuming_sles]
+
+ unique_item_warehouses = set(item_warehouses)
+
+ if len(unique_item_warehouses) == len(item_warehouses):
+ return False
+
+ for sle in consuming_sles:
+ if sle.stock_queue != "[]": # using FIFO/LIFO valuation
+ return True
+ return False
+
@frappe.whitelist()
def make_quality_inspections(doctype, docname, items):
diff --git a/erpnext/controllers/subcontracting.py b/erpnext/controllers/subcontracting.py
index 3addb91..c52c688 100644
--- a/erpnext/controllers/subcontracting.py
+++ b/erpnext/controllers/subcontracting.py
@@ -363,8 +363,6 @@
return
for row in self.get(self.raw_material_table):
- self.__validate_consumed_qty(row)
-
key = (row.rm_item_code, row.main_item_code, row.purchase_order)
if not self.__transferred_items or not self.__transferred_items.get(key):
return
@@ -372,12 +370,6 @@
self.__validate_batch_no(row, key)
self.__validate_serial_no(row, key)
- def __validate_consumed_qty(self, row):
- if self.backflush_based_on != 'BOM' and flt(row.consumed_qty) == 0.0:
- msg = f'Row {row.idx}: the consumed qty cannot be zero for the item {frappe.bold(row.rm_item_code)}'
-
- frappe.throw(_(msg),title=_('Consumed Items Qty Check'))
-
def __validate_batch_no(self, row, key):
if row.get('batch_no') and row.get('batch_no') not in self.__transferred_items.get(key).get('batch_no'):
link = get_link_to_form('Purchase Order', row.purchase_order)
diff --git a/erpnext/controllers/taxes_and_totals.py b/erpnext/controllers/taxes_and_totals.py
index 075e3e3..a1bb667 100644
--- a/erpnext/controllers/taxes_and_totals.py
+++ b/erpnext/controllers/taxes_and_totals.py
@@ -106,21 +106,31 @@
self.doc.conversion_rate = flt(self.doc.conversion_rate)
def calculate_item_values(self):
+ if self.doc.get('is_consolidated'):
+ return
+
if not self.discount_amount_applied:
for item in self.doc.get("items"):
self.doc.round_floats_in(item)
+ if not item.rate:
+ item.rate = item.price_list_rate
+
if item.discount_percentage == 100:
item.rate = 0.0
elif item.price_list_rate:
- if not item.rate or (item.pricing_rules and item.discount_percentage > 0):
+ if item.pricing_rules or abs(item.discount_percentage) > 0:
item.rate = flt(item.price_list_rate *
(1.0 - (item.discount_percentage / 100.0)), item.precision("rate"))
- item.discount_amount = item.price_list_rate * (item.discount_percentage / 100.0)
- elif item.discount_amount and item.pricing_rules:
+
+ if abs(item.discount_percentage) > 0:
+ item.discount_amount = item.price_list_rate * (item.discount_percentage / 100.0)
+
+ elif item.discount_amount or item.pricing_rules:
item.rate = item.price_list_rate - item.discount_amount
- if item.doctype in ['Quotation Item', 'Sales Order Item', 'Delivery Note Item', 'Sales Invoice Item', 'POS Invoice Item', 'Purchase Invoice Item', 'Purchase Order Item', 'Purchase Receipt Item']:
+ if item.doctype in ['Quotation Item', 'Sales Order Item', 'Delivery Note Item', 'Sales Invoice Item',
+ 'POS Invoice Item', 'Purchase Invoice Item', 'Purchase Order Item', 'Purchase Receipt Item']:
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"))
@@ -267,7 +277,8 @@
shipping_rule.apply(self.doc)
def calculate_taxes(self):
- if not self.doc.get('is_consolidated'):
+ rounding_adjustment_computed = self.doc.get('is_consolidated') and self.doc.get('rounding_adjustment')
+ if not rounding_adjustment_computed:
self.doc.rounding_adjustment = 0
# maintain actual tax rate based on idx
@@ -323,7 +334,7 @@
if i == (len(self.doc.get("taxes")) - 1) and self.discount_amount_applied \
and self.doc.discount_amount \
and self.doc.apply_discount_on == "Grand Total" \
- and not self.doc.get('is_consolidated'):
+ and not rounding_adjustment_computed:
self.doc.rounding_adjustment = flt(self.doc.grand_total
- flt(self.doc.discount_amount) - tax.total,
self.doc.precision("rounding_adjustment"))
@@ -462,20 +473,22 @@
self.doc.total_net_weight += d.total_weight
def set_rounded_total(self):
- if not self.doc.get('is_consolidated'):
- if self.doc.meta.get_field("rounded_total"):
- if self.doc.is_rounded_total_disabled():
- self.doc.rounded_total = self.doc.base_rounded_total = 0
- return
+ if self.doc.get('is_consolidated') and self.doc.get('rounding_adjustment'):
+ return
- self.doc.rounded_total = round_based_on_smallest_currency_fraction(self.doc.grand_total,
- self.doc.currency, self.doc.precision("rounded_total"))
+ if self.doc.meta.get_field("rounded_total"):
+ if self.doc.is_rounded_total_disabled():
+ self.doc.rounded_total = self.doc.base_rounded_total = 0
+ return
- #if print_in_rate is set, we would have already calculated rounding adjustment
- self.doc.rounding_adjustment += flt(self.doc.rounded_total - self.doc.grand_total,
- self.doc.precision("rounding_adjustment"))
+ self.doc.rounded_total = round_based_on_smallest_currency_fraction(self.doc.grand_total,
+ self.doc.currency, self.doc.precision("rounded_total"))
- self._set_in_company_currency(self.doc, ["rounding_adjustment", "rounded_total"])
+ #if print_in_rate is set, we would have already calculated rounding adjustment
+ self.doc.rounding_adjustment += flt(self.doc.rounded_total - self.doc.grand_total,
+ self.doc.precision("rounding_adjustment"))
+
+ self._set_in_company_currency(self.doc, ["rounding_adjustment", "rounded_total"])
def _cleanup(self):
if not self.doc.get('is_consolidated'):
@@ -647,12 +660,12 @@
def calculate_change_amount(self):
self.doc.change_amount = 0.0
self.doc.base_change_amount = 0.0
+ grand_total = self.doc.rounded_total or self.doc.grand_total
+ base_grand_total = self.doc.base_rounded_total or self.doc.base_grand_total
if self.doc.doctype == "Sales Invoice" \
- and self.doc.paid_amount > self.doc.grand_total and not self.doc.is_return \
+ and self.doc.paid_amount > grand_total and not self.doc.is_return \
and any(d.type == "Cash" for d in self.doc.payments):
- grand_total = self.doc.rounded_total or self.doc.grand_total
- base_grand_total = self.doc.base_rounded_total or self.doc.base_grand_total
self.doc.change_amount = flt(self.doc.paid_amount - grand_total +
self.doc.write_off_amount, self.doc.precision("change_amount"))
diff --git a/erpnext/crm/doctype/opportunity_lost_reason/opportunity_lost_reason.json b/erpnext/crm/doctype/opportunity_lost_reason/opportunity_lost_reason.json
index 8a8d425..0cfcf0e 100644
--- a/erpnext/crm/doctype/opportunity_lost_reason/opportunity_lost_reason.json
+++ b/erpnext/crm/doctype/opportunity_lost_reason/opportunity_lost_reason.json
@@ -3,7 +3,7 @@
"allow_events_in_timeline": 0,
"allow_guest_to_view": 0,
"allow_import": 0,
- "allow_rename": 0,
+ "allow_rename": 1,
"autoname": "field:lost_reason",
"beta": 0,
"creation": "2018-12-28 14:48:51.044975",
@@ -57,7 +57,7 @@
"issingle": 0,
"istable": 0,
"max_attachments": 0,
- "modified": "2018-12-28 14:49:43.336437",
+ "modified": "2022-02-16 10:49:43.336437",
"modified_by": "Administrator",
"module": "CRM",
"name": "Opportunity Lost Reason",
@@ -150,4 +150,4 @@
"track_changes": 0,
"track_seen": 0,
"track_views": 0
-}
\ No newline at end of file
+}
diff --git a/erpnext/domains/non_profit.py b/erpnext/domains/non_profit.py
deleted file mode 100644
index d9fc5e5..0000000
--- a/erpnext/domains/non_profit.py
+++ /dev/null
@@ -1,22 +0,0 @@
-data = {
- 'desktop_icons': [
- 'Non Profit',
- 'Member',
- 'Donor',
- 'Volunteer',
- 'Grant Application',
- 'Accounts',
- 'Buying',
- 'HR',
- 'ToDo'
- ],
- 'restricted_roles': [
- 'Non Profit Manager',
- 'Non Profit Member',
- 'Non Profit Portal User'
- ],
- 'modules': [
- 'Non Profit'
- ],
- 'default_portal_role': 'Non Profit Manager'
-}
diff --git a/erpnext/e_commerce/api.py b/erpnext/e_commerce/api.py
index 43cb36c..84554ae 100644
--- a/erpnext/e_commerce/api.py
+++ b/erpnext/e_commerce/api.py
@@ -48,7 +48,6 @@
sub_categories = []
if item_group:
- field_filters['item_group'] = item_group
sub_categories = get_child_groups_for_website(item_group, immediate=True)
engine = ProductQuery()
diff --git a/erpnext/e_commerce/product_data_engine/filters.py b/erpnext/e_commerce/product_data_engine/filters.py
index c4a3cb9..89d4ffd 100644
--- a/erpnext/e_commerce/product_data_engine/filters.py
+++ b/erpnext/e_commerce/product_data_engine/filters.py
@@ -14,6 +14,8 @@
self.item_group = item_group
def get_field_filters(self):
+ from erpnext.setup.doctype.item_group.item_group import get_child_groups_for_website
+
if not self.item_group and not self.doc.enable_field_filters:
return
@@ -25,18 +27,26 @@
fields = [item_meta.get_field(field) for field in filter_fields if item_meta.has_field(field)]
for df in fields:
- item_filters, item_or_filters = {}, []
+ item_filters, item_or_filters = {"published_in_website": 1}, []
link_doctype_values = self.get_filtered_link_doctype_records(df)
if df.fieldtype == "Link":
if self.item_group:
- item_or_filters.extend([
- ["item_group", "=", self.item_group],
- ["Website Item Group", "item_group", "=", self.item_group] # consider website item groups
- ])
+ include_child = frappe.db.get_value("Item Group", self.item_group, "include_descendants")
+ if include_child:
+ include_groups = get_child_groups_for_website(self.item_group, include_self=True)
+ include_groups = [x.name for x in include_groups]
+ item_or_filters.extend([
+ ["item_group", "in", include_groups],
+ ["Website Item Group", "item_group", "=", self.item_group] # consider website item groups
+ ])
+ else:
+ item_or_filters.extend([
+ ["item_group", "=", self.item_group],
+ ["Website Item Group", "item_group", "=", self.item_group] # consider website item groups
+ ])
# Get link field values attached to published items
- item_filters['published_in_website'] = 1
item_values = frappe.get_all(
"Item",
fields=[df.fieldname],
diff --git a/erpnext/e_commerce/product_data_engine/query.py b/erpnext/e_commerce/product_data_engine/query.py
index 007bf8b..5c92e3d 100644
--- a/erpnext/e_commerce/product_data_engine/query.py
+++ b/erpnext/e_commerce/product_data_engine/query.py
@@ -46,10 +46,10 @@
self.filter_with_discount = bool(fields.get("discount"))
result, discount_list, website_item_groups, cart_items, count = [], [], [], [], 0
- website_item_groups = self.get_website_item_group_results(item_group, website_item_groups)
-
if fields:
self.build_fields_filters(fields)
+ if item_group:
+ self.build_item_group_filters(item_group)
if search_term:
self.build_search_filters(search_term)
if self.settings.hide_variants:
@@ -61,8 +61,6 @@
else:
result, count = self.query_items(start=start)
- result = self.combine_web_item_group_results(item_group, result, website_item_groups)
-
# sort combined results by ranking
result = sorted(result, key=lambda x: x.get("ranking"), reverse=True)
@@ -167,6 +165,25 @@
# `=` will be faster than `IN` for most cases
self.filters.append([field, "=", values])
+ def build_item_group_filters(self, item_group):
+ "Add filters for Item group page and include Website Item Groups."
+ from erpnext.setup.doctype.item_group.item_group import get_child_groups_for_website
+ item_group_filters = []
+
+ item_group_filters.append(["Website Item", "item_group", "=", item_group])
+ # Consider Website Item Groups
+ item_group_filters.append(["Website Item Group", "item_group", "=", item_group])
+
+ if frappe.db.get_value("Item Group", item_group, "include_descendants"):
+ # include child item group's items as well
+ # eg. Group Node A, will show items of child 1 and child 2 as well
+ # on it's web page
+ include_groups = get_child_groups_for_website(item_group, include_self=True)
+ include_groups = [x.name for x in include_groups]
+ item_group_filters.append(["Website Item", "item_group", "in", include_groups])
+
+ self.or_filters.extend(item_group_filters)
+
def build_search_filters(self, search_term):
"""Query search term in specified fields
@@ -190,19 +207,6 @@
for field in search_fields:
self.or_filters.append([field, "like", search])
- def get_website_item_group_results(self, item_group, website_item_groups):
- """Get Web Items for Item Group Page via Website Item Groups."""
- if item_group:
- website_item_groups = frappe.db.get_all(
- "Website Item",
- fields=self.fields + ["`tabWebsite Item Group`.parent as wig_parent"],
- filters=[
- ["Website Item Group", "item_group", "=", item_group],
- ["published", "=", 1]
- ]
- )
- return website_item_groups
-
def add_display_details(self, result, discount_list, cart_items):
"""Add price and availability details in result."""
for item in result:
@@ -264,7 +268,7 @@
customer = get_customer(silent=True)
if customer:
quotation = frappe.get_all("Quotation", fields=["name"], filters=
- {"party_name": customer, "order_type": "Shopping Cart", "docstatus": 0},
+ {"party_name": customer, "contact_email": frappe.session.user, "order_type": "Shopping Cart", "docstatus": 0},
order_by="modified desc", limit_page_length=1)
if quotation:
items = frappe.get_all(
@@ -278,16 +282,6 @@
return []
- def combine_web_item_group_results(self, item_group, result, website_item_groups):
- """Combine results with context of website item groups into item results."""
- if item_group and website_item_groups:
- items_list = {row.name for row in result}
- for row in website_item_groups:
- if row.wig_parent not in items_list:
- result.append(row)
-
- return result
-
def filter_results_by_discount(self, fields, result):
if fields and fields.get("discount"):
discount_percent = frappe.utils.flt(fields["discount"][0])
@@ -298,4 +292,4 @@
# slice results manually
result[:self.page_length]
- return result
\ No newline at end of file
+ return result
diff --git a/erpnext/e_commerce/product_data_engine/test_item_group_product_data_engine.py b/erpnext/e_commerce/product_data_engine/test_item_group_product_data_engine.py
index f0f7918..6549ba6 100644
--- a/erpnext/e_commerce/product_data_engine/test_item_group_product_data_engine.py
+++ b/erpnext/e_commerce/product_data_engine/test_item_group_product_data_engine.py
@@ -13,8 +13,7 @@
class TestItemGroupProductDataEngine(unittest.TestCase):
"Test Products & Sub-Category Querying for Product Listing on Item Group Page."
- @classmethod
- def setUpClass(cls):
+ def setUp(self):
item_codes = [
("Test Mobile A", "_Test Item Group B"),
("Test Mobile B", "_Test Item Group B"),
@@ -28,8 +27,10 @@
if not frappe.db.exists("Website Item", {"item_code": item_code}):
create_regular_web_item(item_code, item_args=item_args)
- @classmethod
- def tearDownClass(cls):
+ frappe.db.set_value("Item Group", "_Test Item Group B - 1", "show_in_website", 1)
+ frappe.db.set_value("Item Group", "_Test Item Group B - 2", "show_in_website", 1)
+
+ def tearDown(self):
frappe.db.rollback()
def test_product_listing_in_item_group(self):
@@ -87,7 +88,6 @@
def test_item_group_with_sub_groups(self):
"Test Valid Sub Item Groups in Item Group Page."
- frappe.db.set_value("Item Group", "_Test Item Group B - 1", "show_in_website", 1)
frappe.db.set_value("Item Group", "_Test Item Group B - 2", "show_in_website", 0)
result = get_product_filter_data(query_args={
@@ -114,4 +114,45 @@
# check if child group is fetched if shown in website
self.assertIn("_Test Item Group B - 1", child_groups)
- self.assertIn("_Test Item Group B - 2", child_groups)
\ No newline at end of file
+ self.assertIn("_Test Item Group B - 2", child_groups)
+
+ def test_item_group_page_with_descendants_included(self):
+ """
+ Test if 'include_descendants' pulls Items belonging to descendant Item Groups (Level 2 & 3).
+ > _Test Item Group B [Level 1]
+ > _Test Item Group B - 1 [Level 2]
+ > _Test Item Group B - 1 - 1 [Level 3]
+ """
+ frappe.get_doc({ # create Level 3 nested child group
+ "doctype": "Item Group",
+ "is_group": 1,
+ "item_group_name": "_Test Item Group B - 1 - 1",
+ "parent_item_group": "_Test Item Group B - 1"
+ }).insert()
+
+ create_regular_web_item( # create an item belonging to level 3 item group
+ "Test Mobile F",
+ item_args={"item_group": "_Test Item Group B - 1 - 1"}
+ )
+
+ frappe.db.set_value("Item Group", "_Test Item Group B - 1 - 1", "show_in_website", 1)
+
+ # enable 'include descendants' in Level 1
+ frappe.db.set_value("Item Group", "_Test Item Group B", "include_descendants", 1)
+
+ result = get_product_filter_data(query_args={
+ "field_filters": {},
+ "attribute_filters": {},
+ "start": 0,
+ "item_group": "_Test Item Group B"
+ })
+
+ items = result.get("items")
+ item_codes = [item.get("item_code") for item in items]
+
+ # check if all sub groups' items are pulled
+ self.assertEqual(len(items), 6)
+ self.assertIn("Test Mobile A", item_codes)
+ self.assertIn("Test Mobile C", item_codes)
+ self.assertIn("Test Mobile E", item_codes)
+ self.assertIn("Test Mobile F", item_codes)
\ No newline at end of file
diff --git a/erpnext/e_commerce/shopping_cart/cart.py b/erpnext/e_commerce/shopping_cart/cart.py
index 458cf69..372aed0 100644
--- a/erpnext/e_commerce/shopping_cart/cart.py
+++ b/erpnext/e_commerce/shopping_cart/cart.py
@@ -310,7 +310,7 @@
party = get_party()
quotation = frappe.get_all("Quotation", fields=["name"], filters=
- {"party_name": party.name, "order_type": "Shopping Cart", "docstatus": 0},
+ {"party_name": party.name, "contact_email": frappe.session.user, "order_type": "Shopping Cart", "docstatus": 0},
order_by="modified desc", limit_page_length=1)
if quotation:
diff --git a/erpnext/e_commerce/shopping_cart/test_shopping_cart.py b/erpnext/e_commerce/shopping_cart/test_shopping_cart.py
index 8519e68..9c389d0 100644
--- a/erpnext/e_commerce/shopping_cart/test_shopping_cart.py
+++ b/erpnext/e_commerce/shopping_cart/test_shopping_cart.py
@@ -5,6 +5,7 @@
import unittest
import frappe
+from frappe.tests.utils import change_settings
from frappe.utils import add_months, nowdate
from erpnext.accounts.doctype.tax_rule.tax_rule import ConflictingTaxRule
@@ -15,7 +16,7 @@
get_party,
update_cart,
)
-from erpnext.tests.utils import change_settings, create_test_contact_and_address
+from erpnext.tests.utils import create_test_contact_and_address
# test_dependencies = ['Payment Terms Template']
@@ -57,13 +58,19 @@
return quotation
def test_get_cart_customer(self):
- self.login_as_customer()
+ def validate_quotation():
+ # test if quotation with customer is fetched
+ quotation = _get_cart_quotation()
+ self.assertEqual(quotation.quotation_to, "Customer")
+ self.assertEqual(quotation.party_name, "_Test Customer")
+ self.assertEqual(quotation.contact_email, frappe.session.user)
+ return quotation
- # test if quotation with customer is fetched
- quotation = _get_cart_quotation()
- self.assertEqual(quotation.quotation_to, "Customer")
- self.assertEqual(quotation.party_name, "_Test Customer")
- self.assertEqual(quotation.contact_email, frappe.session.user)
+ self.login_as_customer("test_contact_two_customer@example.com", "_Test Contact 2 For _Test Customer")
+ validate_quotation()
+
+ self.login_as_customer()
+ quotation = validate_quotation()
return quotation
@@ -175,7 +182,7 @@
def create_tax_rule(self):
tax_rule = frappe.get_test_records("Tax Rule")[0]
try:
- frappe.get_doc(tax_rule).insert()
+ frappe.get_doc(tax_rule).insert(ignore_if_duplicate=True)
except (frappe.DuplicateEntryError, ConflictingTaxRule):
pass
@@ -254,10 +261,9 @@
self.create_user_if_not_exists("test_cart_user@example.com")
frappe.set_user("test_cart_user@example.com")
- def login_as_customer(self):
- self.create_user_if_not_exists("test_contact_customer@example.com",
- "_Test Contact For _Test Customer")
- frappe.set_user("test_contact_customer@example.com")
+ def login_as_customer(self, email="test_contact_customer@example.com", name="_Test Contact For _Test Customer"):
+ self.create_user_if_not_exists(email, name)
+ frappe.set_user(email)
def clear_existing_quotations(self):
quotations = frappe.get_all("Quotation", filters={
diff --git a/erpnext/e_commerce/variant_selector/item_variants_cache.py b/erpnext/e_commerce/variant_selector/item_variants_cache.py
index bb6b3ef..3107c01 100644
--- a/erpnext/e_commerce/variant_selector/item_variants_cache.py
+++ b/erpnext/e_commerce/variant_selector/item_variants_cache.py
@@ -66,26 +66,24 @@
)
]
- # join with Website Item
- item_variants_data = frappe.get_all(
- 'Item Variant Attribute',
- {'variant_of': parent_item_code},
- ['parent', 'attribute', 'attribute_value'],
- order_by='name',
- as_list=1
+ # Get Variants and tehir Attributes that are not disabled
+ iva = frappe.qb.DocType("Item Variant Attribute")
+ item = frappe.qb.DocType("Item")
+ query = (
+ frappe.qb.from_(iva)
+ .join(item).on(item.name == iva.parent)
+ .select(
+ iva.parent, iva.attribute, iva.attribute_value
+ ).where(
+ (iva.variant_of == parent_item_code)
+ & (item.disabled == 0)
+ ).orderby(iva.name)
)
-
- disabled_items = set(
- [i.name for i in frappe.db.get_all('Item', {'disabled': 1})]
- )
+ item_variants_data = query.run()
attribute_value_item_map = frappe._dict()
item_attribute_value_map = frappe._dict()
- # dont consider variants that are disabled
- # pull all other variants
- item_variants_data = [r for r in item_variants_data if r[0] not in disabled_items]
-
for row in item_variants_data:
item_code, attribute, attribute_value = row
# (attr, value) => [item1, item2]
@@ -124,4 +122,7 @@
def enqueue_build_cache(item_code):
if frappe.cache().hget('item_cache_build_in_progress', item_code):
return
- frappe.enqueue(build_cache, item_code=item_code, queue='long')
+ frappe.enqueue(
+ "erpnext.e_commerce.variant_selector.item_variants_cache.build_cache",
+ item_code=item_code, queue='long'
+ )
diff --git a/erpnext/e_commerce/variant_selector/test_variant_selector.py b/erpnext/e_commerce/variant_selector/test_variant_selector.py
index b83961e..ee098e1 100644
--- a/erpnext/e_commerce/variant_selector/test_variant_selector.py
+++ b/erpnext/e_commerce/variant_selector/test_variant_selector.py
@@ -1,4 +1,5 @@
import frappe
+from frappe.tests.utils import FrappeTestCase
from erpnext.controllers.item_variant import create_variant
from erpnext.e_commerce.doctype.e_commerce_settings.test_e_commerce_settings import (
@@ -7,11 +8,10 @@
from erpnext.e_commerce.doctype.website_item.website_item import make_website_item
from erpnext.e_commerce.variant_selector.utils import get_next_attribute_and_values
from erpnext.stock.doctype.item.test_item import make_item
-from erpnext.tests.utils import ERPNextTestCase
test_dependencies = ["Item"]
-class TestVariantSelector(ERPNextTestCase):
+class TestVariantSelector(FrappeTestCase):
@classmethod
def setUpClass(cls):
@@ -104,6 +104,8 @@
})
make_web_item_price(item_code="Test-Tshirt-Temp-S-R", price_list_rate=100)
+
+ frappe.local.shopping_cart_settings = None # clear cached settings values
next_values = get_next_attribute_and_values(
"Test-Tshirt-Temp",
selected_attributes={"Test Size": "Small", "Test Colour": "Red"}
@@ -114,4 +116,4 @@
self.assertEqual(next_values["exact_match"][0],"Test-Tshirt-Temp-S-R")
self.assertEqual(next_values["exact_match"][0],"Test-Tshirt-Temp-S-R")
self.assertEqual(price_info["price_list_rate"], 100.0)
- self.assertEqual(price_info["formatted_price_sales_uom"], "₹ 100.00")
\ No newline at end of file
+ self.assertEqual(price_info["formatted_price_sales_uom"], "₹ 100.00")
diff --git a/erpnext/education/doctype/student_attendance_tool/student_attendance_tool.js b/erpnext/education/doctype/student_attendance_tool/student_attendance_tool.js
index 68e7780..4526585 100644
--- a/erpnext/education/doctype/student_attendance_tool/student_attendance_tool.js
+++ b/erpnext/education/doctype/student_attendance_tool/student_attendance_tool.js
@@ -3,6 +3,10 @@
frappe.provide("education");
frappe.ui.form.on('Student Attendance Tool', {
+ setup: (frm) => {
+ frm.students_area = $('<div>')
+ .appendTo(frm.fields_dict.students_html.wrapper);
+ },
onload: function(frm) {
frm.set_query("student_group", function() {
return {
@@ -34,6 +38,7 @@
student_group: function(frm) {
if ((frm.doc.student_group && frm.doc.date) || frm.doc.course_schedule) {
+ frm.students_area.find('.student-attendance-checks').html(`<div style='padding: 2rem 0'>Fetching...</div>`);
var method = "erpnext.education.doctype.student_attendance_tool.student_attendance_tool.get_student_attendance_records";
frappe.call({
@@ -62,10 +67,6 @@
},
get_students: function(frm, students) {
- if (!frm.students_area) {
- frm.students_area = $('<div>')
- .appendTo(frm.fields_dict.students_html.wrapper);
- }
students = students || [];
frm.students_editor = new education.StudentsEditor(frm, frm.students_area, students);
}
@@ -163,16 +164,26 @@
);
});
- var htmls = students.map(function(student) {
- return frappe.render_template("student_button", {
- student: student.student,
- student_name: student.student_name,
- group_roll_number: student.group_roll_number,
- status: student.status
- })
- });
+ // make html grid of students
+ let student_html = '';
+ for (let student of students) {
+ student_html += `<div class="col-sm-3">
+ <div class="checkbox">
+ <label>
+ <input
+ type="checkbox"
+ data-group_roll_number="${student.group_roll_number}"
+ data-student="${student.student}"
+ data-student-name="${student.student_name}"
+ class="students-check"
+ ${student.status==='Present' ? 'checked' : ''}>
+ ${student.group_roll_number} - ${student.student_name}
+ </label>
+ </div>
+ </div>`;
+ }
- $(htmls.join("")).appendTo(me.wrapper);
+ $(`<div class='student-attendance-checks'>${student_html}</div>`).appendTo(me.wrapper);
}
show_empty_state() {
diff --git a/erpnext/education/doctype/student_attendance_tool/student_attendance_tool.py b/erpnext/education/doctype/student_attendance_tool/student_attendance_tool.py
index 7deb6b1..92bb20c 100644
--- a/erpnext/education/doctype/student_attendance_tool/student_attendance_tool.py
+++ b/erpnext/education/doctype/student_attendance_tool/student_attendance_tool.py
@@ -24,24 +24,24 @@
student_list = frappe.get_all("Student Group Student", fields=["student", "student_name", "group_roll_number"],
filters={"parent": student_group, "active": 1}, order_by= "group_roll_number")
- table = frappe.qb.DocType("Student Attendance")
+ StudentAttendance = frappe.qb.DocType("Student Attendance")
if course_schedule:
student_attendance_list = (
- frappe.qb.from_(table)
- .select(table.student, table.status)
+ frappe.qb.from_(StudentAttendance)
+ .select(StudentAttendance.student, StudentAttendance.status)
.where(
- (table.course_schedule == course_schedule)
+ (StudentAttendance.course_schedule == course_schedule)
)
).run(as_dict=True)
else:
student_attendance_list = (
- frappe.qb.from_(table)
- .select(table.student, table.status)
+ frappe.qb.from_(StudentAttendance)
+ .select(StudentAttendance.student, StudentAttendance.status)
.where(
- (table.student_group == student_group)
- & (table.date == date)
- & (table.course_schedule == "") | (table.course_schedule.isnull())
+ (StudentAttendance.student_group == student_group)
+ & (StudentAttendance.date == date)
+ & ((StudentAttendance.course_schedule == "") | (StudentAttendance.course_schedule.isnull()))
)
).run(as_dict=True)
diff --git a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/__init__.py b/erpnext/erpnext_integrations/doctype/amazon_mws_settings/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/__init__.py
+++ /dev/null
diff --git a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_methods.py b/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_methods.py
deleted file mode 100644
index 29bc36f..0000000
--- a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_methods.py
+++ /dev/null
@@ -1,524 +0,0 @@
-# Copyright (c) 2018, Frappe Technologies and contributors
-# For license information, please see license.txt
-
-
-import csv
-import math
-import time
-from io import StringIO
-
-import dateutil
-import frappe
-from frappe import _
-
-import erpnext.erpnext_integrations.doctype.amazon_mws_settings.amazon_mws_api as mws
-
-
-#Get and Create Products
-def get_products_details():
- products = get_products_instance()
- reports = get_reports_instance()
-
- mws_settings = frappe.get_doc("Amazon MWS Settings")
- market_place_list = return_as_list(mws_settings.market_place_id)
-
- for marketplace in market_place_list:
- report_id = request_and_fetch_report_id("_GET_FLAT_FILE_OPEN_LISTINGS_DATA_", None, None, market_place_list)
-
- if report_id:
- listings_response = reports.get_report(report_id=report_id)
-
- #Get ASIN Codes
- string_io = StringIO(frappe.safe_decode(listings_response.original))
- csv_rows = list(csv.reader(string_io, delimiter='\t'))
- asin_list = list(set([row[1] for row in csv_rows[1:]]))
- #break into chunks of 10
- asin_chunked_list = list(chunks(asin_list, 10))
-
- #Map ASIN Codes to SKUs
- sku_asin = [{"asin":row[1],"sku":row[0]} for row in csv_rows[1:]]
-
- #Fetch Products List from ASIN
- for asin_list in asin_chunked_list:
- products_response = call_mws_method(products.get_matching_product,marketplaceid=marketplace,
- asins=asin_list)
-
- matching_products_list = products_response.parsed
- for product in matching_products_list:
- skus = [row["sku"] for row in sku_asin if row["asin"]==product.ASIN]
- for sku in skus:
- create_item_code(product, sku)
-
-def get_products_instance():
- mws_settings = frappe.get_doc("Amazon MWS Settings")
- products = mws.Products(
- account_id = mws_settings.seller_id,
- access_key = mws_settings.aws_access_key_id,
- secret_key = mws_settings.secret_key,
- region = mws_settings.region,
- domain = mws_settings.domain
- )
-
- return products
-
-def get_reports_instance():
- mws_settings = frappe.get_doc("Amazon MWS Settings")
- reports = mws.Reports(
- account_id = mws_settings.seller_id,
- access_key = mws_settings.aws_access_key_id,
- secret_key = mws_settings.secret_key,
- region = mws_settings.region,
- domain = mws_settings.domain
- )
-
- return reports
-
-#returns list as expected by amazon API
-def return_as_list(input_value):
- if isinstance(input_value, list):
- return input_value
- else:
- return [input_value]
-
-#function to chunk product data
-def chunks(l, n):
- for i in range(0, len(l), n):
- yield l[i:i+n]
-
-def request_and_fetch_report_id(report_type, start_date=None, end_date=None, marketplaceids=None):
- reports = get_reports_instance()
- report_response = reports.request_report(report_type=report_type,
- start_date=start_date,
- end_date=end_date,
- marketplaceids=marketplaceids)
-
- report_request_id = report_response.parsed["ReportRequestInfo"]["ReportRequestId"]["value"]
- generated_report_id = None
- #poll to get generated report
- for x in range(1,10):
- report_request_list_response = reports.get_report_request_list(requestids=[report_request_id])
- report_status = report_request_list_response.parsed["ReportRequestInfo"]["ReportProcessingStatus"]["value"]
-
- if report_status == "_SUBMITTED_" or report_status == "_IN_PROGRESS_":
- #add time delay to wait for amazon to generate report
- time.sleep(15)
- continue
- elif report_status == "_CANCELLED_":
- break
- elif report_status == "_DONE_NO_DATA_":
- break
- elif report_status == "_DONE_":
- generated_report_id = report_request_list_response.parsed["ReportRequestInfo"]["GeneratedReportId"]["value"]
- break
- return generated_report_id
-
-def call_mws_method(mws_method, *args, **kwargs):
-
- mws_settings = frappe.get_doc("Amazon MWS Settings")
- max_retries = mws_settings.max_retry_limit
-
- for x in range(0, max_retries):
- try:
- response = mws_method(*args, **kwargs)
- return response
- except Exception as e:
- delay = math.pow(4, x) * 125
- frappe.log_error(message=e, title=f'Method "{mws_method.__name__}" failed')
- time.sleep(delay)
- continue
-
- mws_settings.enable_sync = 0
- mws_settings.save()
-
- frappe.throw(_("Sync has been temporarily disabled because maximum retries have been exceeded"))
-
-def create_item_code(amazon_item_json, sku):
- if frappe.db.get_value("Item", sku):
- return
-
- item = frappe.new_doc("Item")
-
- new_manufacturer = create_manufacturer(amazon_item_json)
- new_brand = create_brand(amazon_item_json)
-
- mws_settings = frappe.get_doc("Amazon MWS Settings")
-
- item.item_code = sku
- item.amazon_item_code = amazon_item_json.ASIN
- item.item_group = mws_settings.item_group
- item.description = amazon_item_json.Product.AttributeSets.ItemAttributes.Title
- item.brand = new_brand
- item.manufacturer = new_manufacturer
-
- item.image = amazon_item_json.Product.AttributeSets.ItemAttributes.SmallImage.URL
-
- temp_item_group = amazon_item_json.Product.AttributeSets.ItemAttributes.ProductGroup
-
- item_group = frappe.db.get_value("Item Group",filters={"item_group_name": temp_item_group})
-
- if not item_group:
- igroup = frappe.new_doc("Item Group")
- igroup.item_group_name = temp_item_group
- igroup.parent_item_group = mws_settings.item_group
- igroup.insert()
-
- item.append("item_defaults", {'company':mws_settings.company})
-
- item.insert(ignore_permissions=True)
- create_item_price(amazon_item_json, item.item_code)
-
- return item.name
-
-def create_manufacturer(amazon_item_json):
- if not amazon_item_json.Product.AttributeSets.ItemAttributes.Manufacturer:
- return None
-
- existing_manufacturer = frappe.db.get_value("Manufacturer",
- filters={"short_name":amazon_item_json.Product.AttributeSets.ItemAttributes.Manufacturer})
-
- if not existing_manufacturer:
- manufacturer = frappe.new_doc("Manufacturer")
- manufacturer.short_name = amazon_item_json.Product.AttributeSets.ItemAttributes.Manufacturer
- manufacturer.insert()
- return manufacturer.short_name
- else:
- return existing_manufacturer
-
-def create_brand(amazon_item_json):
- if not amazon_item_json.Product.AttributeSets.ItemAttributes.Brand:
- return None
-
- existing_brand = frappe.db.get_value("Brand",
- filters={"brand":amazon_item_json.Product.AttributeSets.ItemAttributes.Brand})
- if not existing_brand:
- brand = frappe.new_doc("Brand")
- brand.brand = amazon_item_json.Product.AttributeSets.ItemAttributes.Brand
- brand.insert()
- return brand.brand
- else:
- return existing_brand
-
-def create_item_price(amazon_item_json, item_code):
- item_price = frappe.new_doc("Item Price")
- item_price.price_list = frappe.db.get_value("Amazon MWS Settings", "Amazon MWS Settings", "price_list")
- if not("ListPrice" in amazon_item_json.Product.AttributeSets.ItemAttributes):
- item_price.price_list_rate = 0
- else:
- item_price.price_list_rate = amazon_item_json.Product.AttributeSets.ItemAttributes.ListPrice.Amount
-
- item_price.item_code = item_code
- item_price.insert()
-
-#Get and create Orders
-def get_orders(after_date):
- try:
- orders = get_orders_instance()
- statuses = ["PartiallyShipped", "Unshipped", "Shipped", "Canceled"]
- mws_settings = frappe.get_doc("Amazon MWS Settings")
- market_place_list = return_as_list(mws_settings.market_place_id)
-
- orders_response = call_mws_method(orders.list_orders, marketplaceids=market_place_list,
- fulfillment_channels=["MFN", "AFN"],
- lastupdatedafter=after_date,
- orderstatus=statuses,
- max_results='50')
-
- while True:
- orders_list = []
-
- if "Order" in orders_response.parsed.Orders:
- orders_list = return_as_list(orders_response.parsed.Orders.Order)
-
- if len(orders_list) == 0:
- break
-
- for order in orders_list:
- create_sales_order(order, after_date)
-
- if not "NextToken" in orders_response.parsed:
- break
-
- next_token = orders_response.parsed.NextToken
- orders_response = call_mws_method(orders.list_orders_by_next_token, next_token)
-
- except Exception as e:
- frappe.log_error(title="get_orders", message=e)
-
-def get_orders_instance():
- mws_settings = frappe.get_doc("Amazon MWS Settings")
- orders = mws.Orders(
- account_id = mws_settings.seller_id,
- access_key = mws_settings.aws_access_key_id,
- secret_key = mws_settings.secret_key,
- region= mws_settings.region,
- domain= mws_settings.domain,
- version="2013-09-01"
- )
-
- return orders
-
-def create_sales_order(order_json,after_date):
- customer_name = create_customer(order_json)
- create_address(order_json, customer_name)
-
- market_place_order_id = order_json.AmazonOrderId
-
- so = frappe.db.get_value("Sales Order",
- filters={"amazon_order_id": market_place_order_id},
- fieldname="name")
-
- taxes_and_charges = frappe.db.get_value("Amazon MWS Settings", "Amazon MWS Settings", "taxes_charges")
-
- if so:
- return
-
- if not so:
- items = get_order_items(market_place_order_id)
- delivery_date = dateutil.parser.parse(order_json.LatestShipDate).strftime("%Y-%m-%d")
- transaction_date = dateutil.parser.parse(order_json.PurchaseDate).strftime("%Y-%m-%d")
-
- so = frappe.get_doc({
- "doctype": "Sales Order",
- "naming_series": "SO-",
- "amazon_order_id": market_place_order_id,
- "marketplace_id": order_json.MarketplaceId,
- "customer": customer_name,
- "delivery_date": delivery_date,
- "transaction_date": transaction_date,
- "items": items,
- "company": frappe.db.get_value("Amazon MWS Settings", "Amazon MWS Settings", "company")
- })
-
- try:
- if taxes_and_charges:
- charges_and_fees = get_charges_and_fees(market_place_order_id)
- for charge in charges_and_fees.get("charges"):
- so.append('taxes', charge)
-
- for fee in charges_and_fees.get("fees"):
- so.append('taxes', fee)
-
- so.insert(ignore_permissions=True)
- so.submit()
-
- except Exception as e:
- import traceback
- frappe.log_error(message=traceback.format_exc(), title="Create Sales Order")
-
-def create_customer(order_json):
- order_customer_name = ""
-
- if not("BuyerName" in order_json):
- order_customer_name = "Buyer - " + order_json.AmazonOrderId
- else:
- order_customer_name = order_json.BuyerName
-
- existing_customer_name = frappe.db.get_value("Customer",
- filters={"name": order_customer_name}, fieldname="name")
-
- if existing_customer_name:
- filters = [
- ["Dynamic Link", "link_doctype", "=", "Customer"],
- ["Dynamic Link", "link_name", "=", existing_customer_name],
- ["Dynamic Link", "parenttype", "=", "Contact"]
- ]
-
- existing_contacts = frappe.get_list("Contact", filters)
-
- if existing_contacts:
- pass
- else:
- new_contact = frappe.new_doc("Contact")
- new_contact.first_name = order_customer_name
- new_contact.append('links', {
- "link_doctype": "Customer",
- "link_name": existing_customer_name
- })
- new_contact.insert()
-
- return existing_customer_name
- else:
- mws_customer_settings = frappe.get_doc("Amazon MWS Settings")
- new_customer = frappe.new_doc("Customer")
- new_customer.customer_name = order_customer_name
- new_customer.customer_group = mws_customer_settings.customer_group
- new_customer.territory = mws_customer_settings.territory
- new_customer.customer_type = mws_customer_settings.customer_type
- new_customer.save()
-
- new_contact = frappe.new_doc("Contact")
- new_contact.first_name = order_customer_name
- new_contact.append('links', {
- "link_doctype": "Customer",
- "link_name": new_customer.name
- })
-
- new_contact.insert()
-
- return new_customer.name
-
-def create_address(amazon_order_item_json, customer_name):
-
- filters = [
- ["Dynamic Link", "link_doctype", "=", "Customer"],
- ["Dynamic Link", "link_name", "=", customer_name],
- ["Dynamic Link", "parenttype", "=", "Address"]
- ]
-
- existing_address = frappe.get_list("Address", filters)
-
- if not("ShippingAddress" in amazon_order_item_json):
- return None
- else:
- make_address = frappe.new_doc("Address")
-
- if "AddressLine1" in amazon_order_item_json.ShippingAddress:
- make_address.address_line1 = amazon_order_item_json.ShippingAddress.AddressLine1
- else:
- make_address.address_line1 = "Not Provided"
-
- if "City" in amazon_order_item_json.ShippingAddress:
- make_address.city = amazon_order_item_json.ShippingAddress.City
- else:
- make_address.city = "Not Provided"
-
- if "StateOrRegion" in amazon_order_item_json.ShippingAddress:
- make_address.state = amazon_order_item_json.ShippingAddress.StateOrRegion
-
- if "PostalCode" in amazon_order_item_json.ShippingAddress:
- make_address.pincode = amazon_order_item_json.ShippingAddress.PostalCode
-
- for address in existing_address:
- address_doc = frappe.get_doc("Address", address["name"])
- if (address_doc.address_line1 == make_address.address_line1 and
- address_doc.pincode == make_address.pincode):
- return address
-
- make_address.append("links", {
- "link_doctype": "Customer",
- "link_name": customer_name
- })
- make_address.address_type = "Shipping"
- make_address.insert()
-
-def get_order_items(market_place_order_id):
- mws_orders = get_orders_instance()
-
- order_items_response = call_mws_method(mws_orders.list_order_items, amazon_order_id=market_place_order_id)
- final_order_items = []
-
- order_items_list = return_as_list(order_items_response.parsed.OrderItems.OrderItem)
-
- warehouse = frappe.db.get_value("Amazon MWS Settings", "Amazon MWS Settings", "warehouse")
-
- while True:
- for order_item in order_items_list:
-
- if not "ItemPrice" in order_item:
- price = 0
- else:
- price = order_item.ItemPrice.Amount
-
- final_order_items.append({
- "item_code": get_item_code(order_item),
- "item_name": order_item.SellerSKU,
- "description": order_item.Title,
- "rate": price,
- "qty": order_item.QuantityOrdered,
- "stock_uom": "Nos",
- "warehouse": warehouse,
- "conversion_factor": "1.0"
- })
-
- if not "NextToken" in order_items_response.parsed:
- break
-
- next_token = order_items_response.parsed.NextToken
-
- order_items_response = call_mws_method(mws_orders.list_order_items_by_next_token, next_token)
- order_items_list = return_as_list(order_items_response.parsed.OrderItems.OrderItem)
-
- return final_order_items
-
-def get_item_code(order_item):
- sku = order_item.SellerSKU
- item_code = frappe.db.get_value("Item", {"item_code": sku}, "item_code")
- if item_code:
- return item_code
-
-def get_charges_and_fees(market_place_order_id):
- finances = get_finances_instance()
-
- charges_fees = {"charges":[], "fees":[]}
-
- response = call_mws_method(finances.list_financial_events, amazon_order_id=market_place_order_id)
-
- shipment_event_list = return_as_list(response.parsed.FinancialEvents.ShipmentEventList)
-
- for shipment_event in shipment_event_list:
- if shipment_event:
- shipment_item_list = return_as_list(shipment_event.ShipmentEvent.ShipmentItemList.ShipmentItem)
-
- for shipment_item in shipment_item_list:
- charges, fees = [], []
-
- if 'ItemChargeList' in shipment_item.keys():
- charges = return_as_list(shipment_item.ItemChargeList.ChargeComponent)
-
- if 'ItemFeeList' in shipment_item.keys():
- fees = return_as_list(shipment_item.ItemFeeList.FeeComponent)
-
- for charge in charges:
- if(charge.ChargeType != "Principal") and float(charge.ChargeAmount.CurrencyAmount) != 0:
- charge_account = get_account(charge.ChargeType)
- charges_fees.get("charges").append({
- "charge_type":"Actual",
- "account_head": charge_account,
- "tax_amount": charge.ChargeAmount.CurrencyAmount,
- "description": charge.ChargeType + " for " + shipment_item.SellerSKU
- })
-
- for fee in fees:
- if float(fee.FeeAmount.CurrencyAmount) != 0:
- fee_account = get_account(fee.FeeType)
- charges_fees.get("fees").append({
- "charge_type":"Actual",
- "account_head": fee_account,
- "tax_amount": fee.FeeAmount.CurrencyAmount,
- "description": fee.FeeType + " for " + shipment_item.SellerSKU
- })
-
- return charges_fees
-
-def get_finances_instance():
-
- mws_settings = frappe.get_doc("Amazon MWS Settings")
-
- finances = mws.Finances(
- account_id = mws_settings.seller_id,
- access_key = mws_settings.aws_access_key_id,
- secret_key = mws_settings.secret_key,
- region= mws_settings.region,
- domain= mws_settings.domain,
- version="2015-05-01"
- )
-
- return finances
-
-def get_account(name):
- existing_account = frappe.db.get_value("Account", {"account_name": "Amazon {0}".format(name)})
- account_name = existing_account
- mws_settings = frappe.get_doc("Amazon MWS Settings")
-
- if not existing_account:
- try:
- new_account = frappe.new_doc("Account")
- new_account.account_name = "Amazon {0}".format(name)
- new_account.company = mws_settings.company
- new_account.parent_account = mws_settings.market_place_account_group
- new_account.insert(ignore_permissions=True)
- account_name = new_account.name
- except Exception as e:
- frappe.log_error(message=e, title="Create Account")
-
- return account_name
diff --git a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_mws_api.py b/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_mws_api.py
deleted file mode 100755
index 4caf137..0000000
--- a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_mws_api.py
+++ /dev/null
@@ -1,651 +0,0 @@
-#!/usr/bin/env python
-#
-# Basic interface to Amazon MWS
-# Based on http://code.google.com/p/amazon-mws-python
-# Extended to include finances object
-
-import base64
-import hashlib
-import hmac
-import re
-from urllib.parse import quote
-
-from erpnext.erpnext_integrations.doctype.amazon_mws_settings import xml_utils
-
-try:
- from xml.etree.ElementTree import ParseError as XMLError
-except ImportError:
- from xml.parsers.expat import ExpatError as XMLError
-
-from time import gmtime, strftime
-
-from requests import request
-from requests.exceptions import HTTPError
-
-__all__ = [
- 'Feeds',
- 'Inventory',
- 'MWSError',
- 'Reports',
- 'Orders',
- 'Products',
- 'Recommendations',
- 'Sellers',
- 'Finances'
-]
-
-# See https://images-na.ssl-images-amazon.com/images/G/01/mwsportal/doc/en_US/bde/MWSDeveloperGuide._V357736853_.pdf page 8
-# for a list of the end points and marketplace IDs
-
-MARKETPLACES = {
- "CA": "https://mws.amazonservices.ca", #A2EUQ1WTGCTBG2
- "US": "https://mws.amazonservices.com", #ATVPDKIKX0DER",
- "DE": "https://mws-eu.amazonservices.com", #A1PA6795UKMFR9
- "ES": "https://mws-eu.amazonservices.com", #A1RKKUPIHCS9HS
- "FR": "https://mws-eu.amazonservices.com", #A13V1IB3VIYZZH
- "IN": "https://mws.amazonservices.in", #A21TJRUUN4KGV
- "IT": "https://mws-eu.amazonservices.com", #APJ6JRA9NG5V4
- "UK": "https://mws-eu.amazonservices.com", #A1F83G8C2ARO7P
- "JP": "https://mws.amazonservices.jp", #A1VC38T7YXB528
- "CN": "https://mws.amazonservices.com.cn", #AAHKV2X7AFYLW
- "AE": " https://mws.amazonservices.ae", #A2VIGQ35RCS4UG
- "MX": "https://mws.amazonservices.com.mx", #A1AM78C64UM0Y8
- "BR": "https://mws.amazonservices.com", #A2Q3Y263D00KWC
-}
-
-
-class MWSError(Exception):
- """
- Main MWS Exception class
- """
- # Allows quick access to the response object.
- # Do not rely on this attribute, always check if its not None.
- response = None
-
-def calc_md5(string):
- """Calculates the MD5 encryption for the given string
- """
- md = hashlib.md5()
- md.update(string)
- return base64.encodebytes(md.digest()).decode().strip()
-
-
-
-def remove_empty(d):
- """
- Helper function that removes all keys from a dictionary (d),
- that have an empty value.
- """
- for key in list(d):
- if not d[key]:
- del d[key]
- return d
-
-def remove_namespace(xml):
- xml = xml.decode('utf-8')
- regex = re.compile(' xmlns(:ns2)?="[^"]+"|(ns2:)|(xml:)')
- return regex.sub('', xml)
-
-class DictWrapper(object):
- def __init__(self, xml, rootkey=None):
- self.original = xml
- self._rootkey = rootkey
- self._mydict = xml_utils.xml2dict().fromstring(remove_namespace(xml))
- self._response_dict = self._mydict.get(list(self._mydict)[0], self._mydict)
-
- @property
- def parsed(self):
- if self._rootkey:
- return self._response_dict.get(self._rootkey)
- else:
- return self._response_dict
-
-class DataWrapper(object):
- """
- Text wrapper in charge of validating the hash sent by Amazon.
- """
- def __init__(self, data, header):
- self.original = data
- if 'content-md5' in header:
- hash_ = calc_md5(self.original)
- if header['content-md5'] != hash_:
- raise MWSError("Wrong Contentlength, maybe amazon error...")
-
- @property
- def parsed(self):
- return self.original
-
-class MWS(object):
- """ Base Amazon API class """
-
- # This is used to post/get to the different uris used by amazon per api
- # ie. /Orders/2011-01-01
- # All subclasses must define their own URI only if needed
- URI = "/"
-
- # The API version varies in most amazon APIs
- VERSION = "2009-01-01"
-
- # There seem to be some xml namespace issues. therefore every api subclass
- # is recommended to define its namespace, so that it can be referenced
- # like so AmazonAPISubclass.NS.
- # For more information see http://stackoverflow.com/a/8719461/389453
- NS = ''
-
- # Some APIs are available only to either a "Merchant" or "Seller"
- # the type of account needs to be sent in every call to the amazon MWS.
- # This constant defines the exact name of the parameter Amazon expects
- # for the specific API being used.
- # All subclasses need to define this if they require another account type
- # like "Merchant" in which case you define it like so.
- # ACCOUNT_TYPE = "Merchant"
- # Which is the name of the parameter for that specific account type.
- ACCOUNT_TYPE = "SellerId"
-
- def __init__(self, access_key, secret_key, account_id, region='US', domain='', uri="", version=""):
- self.access_key = access_key
- self.secret_key = secret_key
- self.account_id = account_id
- self.version = version or self.VERSION
- self.uri = uri or self.URI
-
- if domain:
- self.domain = domain
- elif region in MARKETPLACES:
- self.domain = MARKETPLACES[region]
- else:
- error_msg = "Incorrect region supplied ('%(region)s'). Must be one of the following: %(marketplaces)s" % {
- "marketplaces" : ', '.join(MARKETPLACES.keys()),
- "region" : region,
- }
- raise MWSError(error_msg)
-
- def make_request(self, extra_data, method="GET", **kwargs):
- """Make request to Amazon MWS API with these parameters
- """
-
- # Remove all keys with an empty value because
- # Amazon's MWS does not allow such a thing.
- extra_data = remove_empty(extra_data)
-
- params = {
- 'AWSAccessKeyId': self.access_key,
- self.ACCOUNT_TYPE: self.account_id,
- 'SignatureVersion': '2',
- 'Timestamp': self.get_timestamp(),
- 'Version': self.version,
- 'SignatureMethod': 'HmacSHA256',
- }
- params.update(extra_data)
- request_description = '&'.join(['%s=%s' % (k, quote(params[k], safe='-_.~')) for k in sorted(params)])
- signature = self.calc_signature(method, request_description)
- url = '%s%s?%s&Signature=%s' % (self.domain, self.uri, request_description, quote(signature))
- headers = {'User-Agent': 'python-amazon-mws/0.0.1 (Language=Python)'}
- headers.update(kwargs.get('extra_headers', {}))
-
- try:
- # Some might wonder as to why i don't pass the params dict as the params argument to request.
- # My answer is, here i have to get the url parsed string of params in order to sign it, so
- # if i pass the params dict as params to request, request will repeat that step because it will need
- # to convert the dict to a url parsed string, so why do it twice if i can just pass the full url :).
- response = request(method, url, data=kwargs.get('body', ''), headers=headers)
- response.raise_for_status()
- # When retrieving data from the response object,
- # be aware that response.content returns the content in bytes while response.text calls
- # response.content and converts it to unicode.
- data = response.content
-
- # I do not check the headers to decide which content structure to server simply because sometimes
- # Amazon's MWS API returns XML error responses with "text/plain" as the Content-Type.
- try:
- parsed_response = DictWrapper(data, extra_data.get("Action") + "Result")
- except XMLError:
- parsed_response = DataWrapper(data, response.headers)
-
- except HTTPError as e:
- error = MWSError(str(e))
- error.response = e.response
- raise error
-
- # Store the response object in the parsed_response for quick access
- parsed_response.response = response
- return parsed_response
-
- def get_service_status(self):
- """
- Returns a GREEN, GREEN_I, YELLOW or RED status.
- Depending on the status/availability of the API its being called from.
- """
-
- return self.make_request(extra_data=dict(Action='GetServiceStatus'))
-
- def calc_signature(self, method, request_description):
- """Calculate MWS signature to interface with Amazon
- """
- sig_data = method + '\n' + self.domain.replace('https://', '').lower() + '\n' + self.uri + '\n' + request_description
- sig_data = sig_data.encode('utf-8')
- secret_key = self.secret_key.encode('utf-8')
- digest = hmac.new(secret_key, sig_data, hashlib.sha256).digest()
- return base64.b64encode(digest).decode('utf-8')
-
- def get_timestamp(self):
- """
- Returns the current timestamp in proper format.
- """
- return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
-
- def enumerate_param(self, param, values):
- """
- Builds a dictionary of an enumerated parameter.
- Takes any iterable and returns a dictionary.
- ie.
- enumerate_param('MarketplaceIdList.Id', (123, 345, 4343))
- returns
- {
- MarketplaceIdList.Id.1: 123,
- MarketplaceIdList.Id.2: 345,
- MarketplaceIdList.Id.3: 4343
- }
- """
- params = {}
- if values is not None:
- if not param.endswith('.'):
- param = "%s." % param
- for num, value in enumerate(values):
- params['%s%d' % (param, (num + 1))] = value
- return params
-
-
-class Feeds(MWS):
- """ Amazon MWS Feeds API """
-
- ACCOUNT_TYPE = "Merchant"
-
- def submit_feed(self, feed, feed_type, marketplaceids=None,
- content_type="text/xml", purge='false'):
- """
- Uploads a feed ( xml or .tsv ) to the seller's inventory.
- Can be used for creating/updating products on Amazon.
- """
- data = dict(Action='SubmitFeed',
- FeedType=feed_type,
- PurgeAndReplace=purge)
- data.update(self.enumerate_param('MarketplaceIdList.Id.', marketplaceids))
- md = calc_md5(feed)
- return self.make_request(data, method="POST", body=feed,
- extra_headers={'Content-MD5': md, 'Content-Type': content_type})
-
- def get_feed_submission_list(self, feedids=None, max_count=None, feedtypes=None,
- processingstatuses=None, fromdate=None, todate=None):
- """
- Returns a list of all feed submissions submitted in the previous 90 days.
- That match the query parameters.
- """
-
- data = dict(Action='GetFeedSubmissionList',
- MaxCount=max_count,
- SubmittedFromDate=fromdate,
- SubmittedToDate=todate,)
- data.update(self.enumerate_param('FeedSubmissionIdList.Id', feedids))
- data.update(self.enumerate_param('FeedTypeList.Type.', feedtypes))
- data.update(self.enumerate_param('FeedProcessingStatusList.Status.', processingstatuses))
- return self.make_request(data)
-
- def get_submission_list_by_next_token(self, token):
- data = dict(Action='GetFeedSubmissionListByNextToken', NextToken=token)
- return self.make_request(data)
-
- def get_feed_submission_count(self, feedtypes=None, processingstatuses=None, fromdate=None, todate=None):
- data = dict(Action='GetFeedSubmissionCount',
- SubmittedFromDate=fromdate,
- SubmittedToDate=todate)
- data.update(self.enumerate_param('FeedTypeList.Type.', feedtypes))
- data.update(self.enumerate_param('FeedProcessingStatusList.Status.', processingstatuses))
- return self.make_request(data)
-
- def cancel_feed_submissions(self, feedids=None, feedtypes=None, fromdate=None, todate=None):
- data = dict(Action='CancelFeedSubmissions',
- SubmittedFromDate=fromdate,
- SubmittedToDate=todate)
- data.update(self.enumerate_param('FeedSubmissionIdList.Id.', feedids))
- data.update(self.enumerate_param('FeedTypeList.Type.', feedtypes))
- return self.make_request(data)
-
- def get_feed_submission_result(self, feedid):
- data = dict(Action='GetFeedSubmissionResult', FeedSubmissionId=feedid)
- return self.make_request(data)
-
-class Reports(MWS):
- """ Amazon MWS Reports API """
-
- ACCOUNT_TYPE = "Merchant"
-
- ## REPORTS ###
-
- def get_report(self, report_id):
- data = dict(Action='GetReport', ReportId=report_id)
- return self.make_request(data)
-
- def get_report_count(self, report_types=(), acknowledged=None, fromdate=None, todate=None):
- data = dict(Action='GetReportCount',
- Acknowledged=acknowledged,
- AvailableFromDate=fromdate,
- AvailableToDate=todate)
- data.update(self.enumerate_param('ReportTypeList.Type.', report_types))
- return self.make_request(data)
-
- def get_report_list(self, requestids=(), max_count=None, types=(), acknowledged=None,
- fromdate=None, todate=None):
- data = dict(Action='GetReportList',
- Acknowledged=acknowledged,
- AvailableFromDate=fromdate,
- AvailableToDate=todate,
- MaxCount=max_count)
- data.update(self.enumerate_param('ReportRequestIdList.Id.', requestids))
- data.update(self.enumerate_param('ReportTypeList.Type.', types))
- return self.make_request(data)
-
- def get_report_list_by_next_token(self, token):
- data = dict(Action='GetReportListByNextToken', NextToken=token)
- return self.make_request(data)
-
- def get_report_request_count(self, report_types=(), processingstatuses=(), fromdate=None, todate=None):
- data = dict(Action='GetReportRequestCount',
- RequestedFromDate=fromdate,
- RequestedToDate=todate)
- data.update(self.enumerate_param('ReportTypeList.Type.', report_types))
- data.update(self.enumerate_param('ReportProcessingStatusList.Status.', processingstatuses))
- return self.make_request(data)
-
- def get_report_request_list(self, requestids=(), types=(), processingstatuses=(),
- max_count=None, fromdate=None, todate=None):
- data = dict(Action='GetReportRequestList',
- MaxCount=max_count,
- RequestedFromDate=fromdate,
- RequestedToDate=todate)
- data.update(self.enumerate_param('ReportRequestIdList.Id.', requestids))
- data.update(self.enumerate_param('ReportTypeList.Type.', types))
- data.update(self.enumerate_param('ReportProcessingStatusList.Status.', processingstatuses))
- return self.make_request(data)
-
- def get_report_request_list_by_next_token(self, token):
- data = dict(Action='GetReportRequestListByNextToken', NextToken=token)
- return self.make_request(data)
-
- def request_report(self, report_type, start_date=None, end_date=None, marketplaceids=()):
- data = dict(Action='RequestReport',
- ReportType=report_type,
- StartDate=start_date,
- EndDate=end_date)
- data.update(self.enumerate_param('MarketplaceIdList.Id.', marketplaceids))
- return self.make_request(data)
-
- ### ReportSchedule ###
-
- def get_report_schedule_list(self, types=()):
- data = dict(Action='GetReportScheduleList')
- data.update(self.enumerate_param('ReportTypeList.Type.', types))
- return self.make_request(data)
-
- def get_report_schedule_count(self, types=()):
- data = dict(Action='GetReportScheduleCount')
- data.update(self.enumerate_param('ReportTypeList.Type.', types))
- return self.make_request(data)
-
-
-class Orders(MWS):
- """ Amazon Orders API """
-
- URI = "/Orders/2013-09-01"
- VERSION = "2013-09-01"
- NS = '{https://mws.amazonservices.com/Orders/2011-01-01}'
-
- def list_orders(self, marketplaceids, created_after=None, created_before=None, lastupdatedafter=None,
- lastupdatedbefore=None, orderstatus=(), fulfillment_channels=(),
- payment_methods=(), buyer_email=None, seller_orderid=None, max_results='100'):
-
- data = dict(Action='ListOrders',
- CreatedAfter=created_after,
- CreatedBefore=created_before,
- LastUpdatedAfter=lastupdatedafter,
- LastUpdatedBefore=lastupdatedbefore,
- BuyerEmail=buyer_email,
- SellerOrderId=seller_orderid,
- MaxResultsPerPage=max_results,
- )
- data.update(self.enumerate_param('OrderStatus.Status.', orderstatus))
- data.update(self.enumerate_param('MarketplaceId.Id.', marketplaceids))
- data.update(self.enumerate_param('FulfillmentChannel.Channel.', fulfillment_channels))
- data.update(self.enumerate_param('PaymentMethod.Method.', payment_methods))
- return self.make_request(data)
-
- def list_orders_by_next_token(self, token):
- data = dict(Action='ListOrdersByNextToken', NextToken=token)
- return self.make_request(data)
-
- def get_order(self, amazon_order_ids):
- data = dict(Action='GetOrder')
- data.update(self.enumerate_param('AmazonOrderId.Id.', amazon_order_ids))
- return self.make_request(data)
-
- def list_order_items(self, amazon_order_id):
- data = dict(Action='ListOrderItems', AmazonOrderId=amazon_order_id)
- return self.make_request(data)
-
- def list_order_items_by_next_token(self, token):
- data = dict(Action='ListOrderItemsByNextToken', NextToken=token)
- return self.make_request(data)
-
-
-class Products(MWS):
- """ Amazon MWS Products API """
-
- URI = '/Products/2011-10-01'
- VERSION = '2011-10-01'
- NS = '{http://mws.amazonservices.com/schema/Products/2011-10-01}'
-
- def list_matching_products(self, marketplaceid, query, contextid=None):
- """ Returns a list of products and their attributes, ordered by
- relevancy, based on a search query that you specify.
- Your search query can be a phrase that describes the product
- or it can be a product identifier such as a UPC, EAN, ISBN, or JAN.
- """
- data = dict(Action='ListMatchingProducts',
- MarketplaceId=marketplaceid,
- Query=query,
- QueryContextId=contextid)
- return self.make_request(data)
-
- def get_matching_product(self, marketplaceid, asins):
- """ Returns a list of products and their attributes, based on a list of
- ASIN values that you specify.
- """
- data = dict(Action='GetMatchingProduct', MarketplaceId=marketplaceid)
- data.update(self.enumerate_param('ASINList.ASIN.', asins))
- return self.make_request(data)
-
- def get_matching_product_for_id(self, marketplaceid, type, id):
- """ Returns a list of products and their attributes, based on a list of
- product identifier values (asin, sellersku, upc, ean, isbn and JAN)
- Added in Fourth Release, API version 2011-10-01
- """
- data = dict(Action='GetMatchingProductForId',
- MarketplaceId=marketplaceid,
- IdType=type)
- data.update(self.enumerate_param('IdList.Id', id))
- return self.make_request(data)
-
- def get_competitive_pricing_for_sku(self, marketplaceid, skus):
- """ Returns the current competitive pricing of a product,
- based on the SellerSKU and MarketplaceId that you specify.
- """
- data = dict(Action='GetCompetitivePricingForSKU', MarketplaceId=marketplaceid)
- data.update(self.enumerate_param('SellerSKUList.SellerSKU.', skus))
- return self.make_request(data)
-
- def get_competitive_pricing_for_asin(self, marketplaceid, asins):
- """ Returns the current competitive pricing of a product,
- based on the ASIN and MarketplaceId that you specify.
- """
- data = dict(Action='GetCompetitivePricingForASIN', MarketplaceId=marketplaceid)
- data.update(self.enumerate_param('ASINList.ASIN.', asins))
- return self.make_request(data)
-
- def get_lowest_offer_listings_for_sku(self, marketplaceid, skus, condition="Any", excludeme="False"):
- data = dict(Action='GetLowestOfferListingsForSKU',
- MarketplaceId=marketplaceid,
- ItemCondition=condition,
- ExcludeMe=excludeme)
- data.update(self.enumerate_param('SellerSKUList.SellerSKU.', skus))
- return self.make_request(data)
-
- def get_lowest_offer_listings_for_asin(self, marketplaceid, asins, condition="Any", excludeme="False"):
- data = dict(Action='GetLowestOfferListingsForASIN',
- MarketplaceId=marketplaceid,
- ItemCondition=condition,
- ExcludeMe=excludeme)
- data.update(self.enumerate_param('ASINList.ASIN.', asins))
- return self.make_request(data)
-
- def get_product_categories_for_sku(self, marketplaceid, sku):
- data = dict(Action='GetProductCategoriesForSKU',
- MarketplaceId=marketplaceid,
- SellerSKU=sku)
- return self.make_request(data)
-
- def get_product_categories_for_asin(self, marketplaceid, asin):
- data = dict(Action='GetProductCategoriesForASIN',
- MarketplaceId=marketplaceid,
- ASIN=asin)
- return self.make_request(data)
-
- def get_my_price_for_sku(self, marketplaceid, skus, condition=None):
- data = dict(Action='GetMyPriceForSKU',
- MarketplaceId=marketplaceid,
- ItemCondition=condition)
- data.update(self.enumerate_param('SellerSKUList.SellerSKU.', skus))
- return self.make_request(data)
-
- def get_my_price_for_asin(self, marketplaceid, asins, condition=None):
- data = dict(Action='GetMyPriceForASIN',
- MarketplaceId=marketplaceid,
- ItemCondition=condition)
- data.update(self.enumerate_param('ASINList.ASIN.', asins))
- return self.make_request(data)
-
-
-class Sellers(MWS):
- """ Amazon MWS Sellers API """
-
- URI = '/Sellers/2011-07-01'
- VERSION = '2011-07-01'
- NS = '{http://mws.amazonservices.com/schema/Sellers/2011-07-01}'
-
- def list_marketplace_participations(self):
- """
- Returns a list of marketplaces a seller can participate in and
- a list of participations that include seller-specific information in that marketplace.
- The operation returns only those marketplaces where the seller's account is in an active state.
- """
-
- data = dict(Action='ListMarketplaceParticipations')
- return self.make_request(data)
-
- def list_marketplace_participations_by_next_token(self, token):
- """
- Takes a "NextToken" and returns the same information as "list_marketplace_participations".
- Based on the "NextToken".
- """
- data = dict(Action='ListMarketplaceParticipations', NextToken=token)
- return self.make_request(data)
-
-#### Fulfillment APIs ####
-
-class InboundShipments(MWS):
- URI = "/FulfillmentInboundShipment/2010-10-01"
- VERSION = '2010-10-01'
-
- # To be completed
-
-
-class Inventory(MWS):
- """ Amazon MWS Inventory Fulfillment API """
-
- URI = '/FulfillmentInventory/2010-10-01'
- VERSION = '2010-10-01'
- NS = "{http://mws.amazonaws.com/FulfillmentInventory/2010-10-01}"
-
- def list_inventory_supply(self, skus=(), datetime=None, response_group='Basic'):
- """ Returns information on available inventory """
-
- data = dict(Action='ListInventorySupply',
- QueryStartDateTime=datetime,
- ResponseGroup=response_group,
- )
- data.update(self.enumerate_param('SellerSkus.member.', skus))
- return self.make_request(data, "POST")
-
- def list_inventory_supply_by_next_token(self, token):
- data = dict(Action='ListInventorySupplyByNextToken', NextToken=token)
- return self.make_request(data, "POST")
-
-
-class OutboundShipments(MWS):
- URI = "/FulfillmentOutboundShipment/2010-10-01"
- VERSION = "2010-10-01"
- # To be completed
-
-
-class Recommendations(MWS):
-
- """ Amazon MWS Recommendations API """
-
- URI = '/Recommendations/2013-04-01'
- VERSION = '2013-04-01'
- NS = "{https://mws.amazonservices.com/Recommendations/2013-04-01}"
-
- def get_last_updated_time_for_recommendations(self, marketplaceid):
- """
- Checks whether there are active recommendations for each category for the given marketplace, and if there are,
- returns the time when recommendations were last updated for each category.
- """
-
- data = dict(Action='GetLastUpdatedTimeForRecommendations',
- MarketplaceId=marketplaceid)
- return self.make_request(data, "POST")
-
- def list_recommendations(self, marketplaceid, recommendationcategory=None):
- """
- Returns your active recommendations for a specific category or for all categories for a specific marketplace.
- """
-
- data = dict(Action="ListRecommendations",
- MarketplaceId=marketplaceid,
- RecommendationCategory=recommendationcategory)
- return self.make_request(data, "POST")
-
- def list_recommendations_by_next_token(self, token):
- """
- Returns the next page of recommendations using the NextToken parameter.
- """
-
- data = dict(Action="ListRecommendationsByNextToken",
- NextToken=token)
- return self.make_request(data, "POST")
-
-class Finances(MWS):
- """ Amazon Finances API"""
- URI = '/Finances/2015-05-01'
- VERSION = '2015-05-01'
- NS = "{https://mws.amazonservices.com/Finances/2015-05-01}"
-
- def list_financial_events(self , posted_after=None, posted_before=None,
- amazon_order_id=None, max_results='100'):
-
- data = dict(Action='ListFinancialEvents',
- PostedAfter=posted_after,
- PostedBefore=posted_before,
- AmazonOrderId=amazon_order_id,
- MaxResultsPerPage=max_results,
- )
- return self.make_request(data)
diff --git a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_mws_settings.js b/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_mws_settings.js
deleted file mode 100644
index f5ea804..0000000
--- a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_mws_settings.js
+++ /dev/null
@@ -1,2 +0,0 @@
-// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
diff --git a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_mws_settings.json b/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_mws_settings.json
deleted file mode 100644
index 5a678e7..0000000
--- a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_mws_settings.json
+++ /dev/null
@@ -1,237 +0,0 @@
-{
- "actions": [],
- "creation": "2018-07-31 05:51:41.357047",
- "doctype": "DocType",
- "editable_grid": 1,
- "engine": "InnoDB",
- "field_order": [
- "enable_amazon",
- "mws_credentials",
- "seller_id",
- "aws_access_key_id",
- "mws_auth_token",
- "secret_key",
- "column_break_4",
- "market_place_id",
- "region",
- "domain",
- "section_break_13",
- "company",
- "warehouse",
- "item_group",
- "price_list",
- "column_break_17",
- "customer_group",
- "territory",
- "customer_type",
- "market_place_account_group",
- "section_break_12",
- "after_date",
- "taxes_charges",
- "sync_products",
- "sync_orders",
- "column_break_10",
- "enable_sync",
- "max_retry_limit"
- ],
- "fields": [
- {
- "default": "0",
- "fieldname": "enable_amazon",
- "fieldtype": "Check",
- "label": "Enable Amazon"
- },
- {
- "fieldname": "mws_credentials",
- "fieldtype": "Section Break",
- "label": "MWS Credentials"
- },
- {
- "fieldname": "seller_id",
- "fieldtype": "Data",
- "in_list_view": 1,
- "label": "Seller ID",
- "reqd": 1
- },
- {
- "fieldname": "aws_access_key_id",
- "fieldtype": "Data",
- "in_list_view": 1,
- "label": "AWS Access Key ID",
- "reqd": 1
- },
- {
- "fieldname": "mws_auth_token",
- "fieldtype": "Data",
- "in_list_view": 1,
- "label": "MWS Auth Token",
- "reqd": 1
- },
- {
- "fieldname": "secret_key",
- "fieldtype": "Data",
- "in_list_view": 1,
- "label": "Secret Key",
- "reqd": 1
- },
- {
- "fieldname": "column_break_4",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "market_place_id",
- "fieldtype": "Data",
- "label": "Market Place ID",
- "reqd": 1
- },
- {
- "fieldname": "region",
- "fieldtype": "Select",
- "label": "Region",
- "options": "\nAE\nAU\nBR\nCA\nCN\nDE\nES\nFR\nIN\nJP\nIT\nMX\nUK\nUS",
- "reqd": 1
- },
- {
- "fieldname": "domain",
- "fieldtype": "Data",
- "label": "Domain",
- "reqd": 1
- },
- {
- "fieldname": "section_break_13",
- "fieldtype": "Section Break"
- },
- {
- "fieldname": "company",
- "fieldtype": "Link",
- "label": "Company",
- "options": "Company",
- "reqd": 1
- },
- {
- "fieldname": "warehouse",
- "fieldtype": "Link",
- "label": "Warehouse",
- "options": "Warehouse",
- "reqd": 1
- },
- {
- "fieldname": "item_group",
- "fieldtype": "Link",
- "label": "Item Group",
- "options": "Item Group",
- "reqd": 1
- },
- {
- "fieldname": "price_list",
- "fieldtype": "Link",
- "label": "Price List",
- "options": "Price List",
- "reqd": 1
- },
- {
- "fieldname": "column_break_17",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "customer_group",
- "fieldtype": "Link",
- "label": "Customer Group",
- "options": "Customer Group",
- "reqd": 1
- },
- {
- "fieldname": "territory",
- "fieldtype": "Link",
- "label": "Territory",
- "options": "Territory",
- "reqd": 1
- },
- {
- "fieldname": "customer_type",
- "fieldtype": "Select",
- "label": "Customer Type",
- "options": "Individual\nCompany",
- "reqd": 1
- },
- {
- "fieldname": "market_place_account_group",
- "fieldtype": "Link",
- "label": "Market Place Account Group",
- "options": "Account",
- "reqd": 1
- },
- {
- "fieldname": "section_break_12",
- "fieldtype": "Section Break"
- },
- {
- "description": "Amazon will synch data updated after this date",
- "fieldname": "after_date",
- "fieldtype": "Datetime",
- "label": "After Date",
- "reqd": 1
- },
- {
- "default": "0",
- "description": "Get financial breakup of Taxes and charges data by Amazon ",
- "fieldname": "taxes_charges",
- "fieldtype": "Check",
- "label": "Sync Taxes and Charges"
- },
- {
- "fieldname": "column_break_10",
- "fieldtype": "Column Break"
- },
- {
- "default": "3",
- "fieldname": "max_retry_limit",
- "fieldtype": "Int",
- "label": "Max Retry Limit"
- },
- {
- "description": "Always sync your products from Amazon MWS before synching the Orders details",
- "fieldname": "sync_products",
- "fieldtype": "Button",
- "label": "Sync Products",
- "options": "get_products_details"
- },
- {
- "description": "Click this button to pull your Sales Order data from Amazon MWS.",
- "fieldname": "sync_orders",
- "fieldtype": "Button",
- "label": "Sync Orders",
- "options": "get_order_details"
- },
- {
- "default": "0",
- "description": "Check this to enable a scheduled Daily synchronization routine via scheduler",
- "fieldname": "enable_sync",
- "fieldtype": "Check",
- "label": "Enable Scheduled Sync"
- }
- ],
- "issingle": 1,
- "links": [],
- "modified": "2020-04-07 14:26:20.174848",
- "modified_by": "Administrator",
- "module": "ERPNext Integrations",
- "name": "Amazon MWS Settings",
- "owner": "Administrator",
- "permissions": [
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "print": 1,
- "read": 1,
- "role": "System Manager",
- "share": 1,
- "write": 1
- }
- ],
- "quick_entry": 1,
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_changes": 1
-}
\ No newline at end of file
diff --git a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_mws_settings.py b/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_mws_settings.py
deleted file mode 100644
index c1f460f..0000000
--- a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/amazon_mws_settings.py
+++ /dev/null
@@ -1,46 +0,0 @@
-# Copyright (c) 2018, Frappe Technologies and contributors
-# For license information, please see license.txt
-
-
-import dateutil
-import frappe
-from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
-from frappe.model.document import Document
-
-from erpnext.erpnext_integrations.doctype.amazon_mws_settings.amazon_methods import get_orders
-
-
-class AmazonMWSSettings(Document):
- def validate(self):
- if self.enable_amazon == 1:
- self.enable_sync = 1
- setup_custom_fields()
- else:
- self.enable_sync = 0
-
- @frappe.whitelist()
- def get_products_details(self):
- if self.enable_amazon == 1:
- frappe.enqueue('erpnext.erpnext_integrations.doctype.amazon_mws_settings.amazon_methods.get_products_details')
-
- @frappe.whitelist()
- def get_order_details(self):
- if self.enable_amazon == 1:
- after_date = dateutil.parser.parse(self.after_date).strftime("%Y-%m-%d")
- frappe.enqueue('erpnext.erpnext_integrations.doctype.amazon_mws_settings.amazon_methods.get_orders', after_date=after_date)
-
-def schedule_get_order_details():
- mws_settings = frappe.get_doc("Amazon MWS Settings")
- if mws_settings.enable_sync and mws_settings.enable_amazon:
- after_date = dateutil.parser.parse(mws_settings.after_date).strftime("%Y-%m-%d")
- get_orders(after_date = after_date)
-
-def setup_custom_fields():
- custom_fields = {
- "Item": [dict(fieldname='amazon_item_code', label='Amazon Item Code',
- fieldtype='Data', insert_after='series', read_only=1, print_hide=1)],
- "Sales Order": [dict(fieldname='amazon_order_id', label='Amazon Order ID',
- fieldtype='Data', insert_after='title', read_only=1, print_hide=1)]
- }
-
- create_custom_fields(custom_fields)
diff --git a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/test_amazon_mws_settings.py b/erpnext/erpnext_integrations/doctype/amazon_mws_settings/test_amazon_mws_settings.py
deleted file mode 100644
index 4be7960..0000000
--- a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/test_amazon_mws_settings.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-
-class TestAmazonMWSSettings(unittest.TestCase):
- pass
diff --git a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/xml_utils.py b/erpnext/erpnext_integrations/doctype/amazon_mws_settings/xml_utils.py
deleted file mode 100644
index d9dfc6f..0000000
--- a/erpnext/erpnext_integrations/doctype/amazon_mws_settings/xml_utils.py
+++ /dev/null
@@ -1,104 +0,0 @@
-"""
-Created on Tue Jun 26 15:42:07 2012
-
-Borrowed from https://github.com/timotheus/ebaysdk-python
-
-@author: pierre
-"""
-
-import re
-import xml.etree.ElementTree as ET
-
-
-class object_dict(dict):
- """object view of dict, you can
- >>> a = object_dict()
- >>> a.fish = 'fish'
- >>> a['fish']
- 'fish'
- >>> a['water'] = 'water'
- >>> a.water
- 'water'
- >>> a.test = {'value': 1}
- >>> a.test2 = object_dict({'name': 'test2', 'value': 2})
- >>> a.test, a.test2.name, a.test2.value
- (1, 'test2', 2)
- """
- def __init__(self, initd=None):
- if initd is None:
- initd = {}
- dict.__init__(self, initd)
-
- def __getattr__(self, item):
-
- try:
- d = self.__getitem__(item)
- except KeyError:
- return None
-
- if isinstance(d, dict) and 'value' in d and len(d) == 1:
- return d['value']
- else:
- return d
-
- # if value is the only key in object, you can omit it
- def __setstate__(self, item):
- return False
-
- def __setattr__(self, item, value):
- self.__setitem__(item, value)
-
- def getvalue(self, item, value=None):
- return self.get(item, {}).get('value', value)
-
-
-class xml2dict(object):
-
- def __init__(self):
- pass
-
- def _parse_node(self, node):
- node_tree = object_dict()
- # Save attrs and text, hope there will not be a child with same name
- if node.text:
- node_tree.value = node.text
- for (k, v) in node.attrib.items():
- k, v = self._namespace_split(k, object_dict({'value':v}))
- node_tree[k] = v
- #Save childrens
- for child in node.getchildren():
- tag, tree = self._namespace_split(child.tag,
- self._parse_node(child))
- if tag not in node_tree: # the first time, so store it in dict
- node_tree[tag] = tree
- continue
- old = node_tree[tag]
- if not isinstance(old, list):
- node_tree.pop(tag)
- node_tree[tag] = [old] # multi times, so change old dict to a list
- node_tree[tag].append(tree) # add the new one
-
- return node_tree
-
- def _namespace_split(self, tag, value):
- """
- Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients'
- ns = http://cs.sfsu.edu/csc867/myscheduler
- name = patients
- """
- result = re.compile(r"\{(.*)\}(.*)").search(tag)
- if result:
- value.namespace, tag = result.groups()
-
- return (tag, value)
-
- def parse(self, file):
- """parse a xml file to a dict"""
- f = open(file, 'r')
- return self.fromstring(f.read())
-
- def fromstring(self, s):
- """parse a string"""
- t = ET.fromstring(s)
- root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t))
- return object_dict({root_tag: root_tree})
diff --git a/erpnext/erpnext_integrations/doctype/gocardless_settings/gocardless_settings.py b/erpnext/erpnext_integrations/doctype/gocardless_settings/gocardless_settings.py
index a8119ac..f02f76e 100644
--- a/erpnext/erpnext_integrations/doctype/gocardless_settings/gocardless_settings.py
+++ b/erpnext/erpnext_integrations/doctype/gocardless_settings/gocardless_settings.py
@@ -13,7 +13,7 @@
class GoCardlessSettings(Document):
- supported_currencies = ["EUR", "DKK", "GBP", "SEK"]
+ supported_currencies = ["EUR", "DKK", "GBP", "SEK", "AUD", "NZD", "CAD", "USD"]
def validate(self):
self.initialize_client()
@@ -80,7 +80,7 @@
def validate_transaction_currency(self, currency):
if currency not in self.supported_currencies:
- frappe.throw(_("Please select another payment method. Stripe does not support transactions in currency '{0}'").format(currency))
+ frappe.throw(_("Please select another payment method. Go Cardless does not support transactions in currency '{0}'").format(currency))
def get_payment_url(self, **kwargs):
return get_url("./integrations/gocardless_checkout?{0}".format(urlencode(kwargs)))
diff --git a/erpnext/erpnext_integrations/doctype/tally_migration/tally_migration.py b/erpnext/erpnext_integrations/doctype/tally_migration/tally_migration.py
index 54ed6f7..26bd19f 100644
--- a/erpnext/erpnext_integrations/doctype/tally_migration/tally_migration.py
+++ b/erpnext/erpnext_integrations/doctype/tally_migration/tally_migration.py
@@ -82,7 +82,7 @@
"is_private": True
})
try:
- f.insert()
+ f.insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
setattr(self, key, f.file_url)
diff --git a/erpnext/erpnext_integrations/taxjar_integration.py b/erpnext/erpnext_integrations/taxjar_integration.py
index a4e2157..14c86d5 100644
--- a/erpnext/erpnext_integrations/taxjar_integration.py
+++ b/erpnext/erpnext_integrations/taxjar_integration.py
@@ -8,10 +8,6 @@
from erpnext import get_default_company, get_region
-TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head")
-SHIP_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "shipping_account_head")
-TAXJAR_CREATE_TRANSACTIONS = frappe.db.get_single_value("TaxJar Settings", "taxjar_create_transactions")
-TAXJAR_CALCULATE_TAX = frappe.db.get_single_value("TaxJar Settings", "taxjar_calculate_tax")
SUPPORTED_COUNTRY_CODES = ["AT", "AU", "BE", "BG", "CA", "CY", "CZ", "DE", "DK", "EE", "ES", "FI",
"FR", "GB", "GR", "HR", "HU", "IE", "IT", "LT", "LU", "LV", "MT", "NL", "PL", "PT", "RO",
"SE", "SI", "SK", "US"]
@@ -35,12 +31,14 @@
if api_key and api_url:
client = taxjar.Client(api_key=api_key, api_url=api_url)
client.set_api_config('headers', {
- 'x-api-version': '2020-08-07'
+ 'x-api-version': '2022-01-24'
})
return client
def create_transaction(doc, method):
+ TAXJAR_CREATE_TRANSACTIONS = frappe.db.get_single_value("TaxJar Settings", "taxjar_create_transactions")
+
"""Create an order transaction in TaxJar"""
if not TAXJAR_CREATE_TRANSACTIONS:
@@ -51,6 +49,7 @@
if not client:
return
+ TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head")
sales_tax = sum([tax.tax_amount for tax in doc.taxes if tax.account_head == TAX_ACCOUNT_HEAD])
if not sales_tax:
@@ -79,6 +78,7 @@
def delete_transaction(doc, method):
"""Delete an existing TaxJar order transaction"""
+ TAXJAR_CREATE_TRANSACTIONS = frappe.db.get_single_value("TaxJar Settings", "taxjar_create_transactions")
if not TAXJAR_CREATE_TRANSACTIONS:
return
@@ -92,6 +92,8 @@
def get_tax_data(doc):
+ SHIP_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "shipping_account_head")
+
from_address = get_company_address_details(doc)
from_shipping_state = from_address.get("state")
from_country_code = frappe.db.get_value("Country", from_address.country, "code")
@@ -113,20 +115,20 @@
to_shipping_state = get_state_code(to_address, 'Shipping')
tax_dict = {
- 'from_country': from_country_code,
- 'from_zip': from_address.pincode,
- 'from_state': from_shipping_state,
- 'from_city': from_address.city,
- 'from_street': from_address.address_line1,
- 'to_country': to_country_code,
- 'to_zip': to_address.pincode,
- 'to_city': to_address.city,
- 'to_street': to_address.address_line1,
- 'to_state': to_shipping_state,
- 'shipping': shipping,
- 'amount': doc.net_total,
- 'plugin': 'erpnext',
- 'line_items': line_items
+ "from_country": from_country_code,
+ "from_zip": from_address.pincode,
+ "from_state": from_shipping_state,
+ "from_city": from_address.city,
+ "from_street": from_address.address_line1,
+ "to_country": to_country_code,
+ "to_zip": to_address.pincode,
+ "to_city": to_address.city,
+ "to_street": to_address.address_line1,
+ "to_state": to_shipping_state,
+ "shipping": shipping,
+ "amount": doc.net_total,
+ "plugin": "erpnext",
+ "line_items": line_items
}
return tax_dict
@@ -156,6 +158,9 @@
return tax_dict
def set_sales_tax(doc, method):
+ TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head")
+ TAXJAR_CALCULATE_TAX = frappe.db.get_single_value("TaxJar Settings", "taxjar_calculate_tax")
+
if not TAXJAR_CALCULATE_TAX:
return
@@ -206,6 +211,7 @@
doc.run_method("calculate_taxes_and_totals")
def check_for_nexus(doc, tax_dict):
+ TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head")
if not frappe.db.get_value('TaxJar Nexus', {'region_code': tax_dict["to_state"]}):
for item in doc.get("items"):
item.tax_collectable = flt(0)
@@ -218,6 +224,8 @@
def check_sales_tax_exemption(doc):
# if the party is exempt from sales tax, then set all tax account heads to zero
+ TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head")
+
sales_tax_exempted = hasattr(doc, "exempt_from_sales_tax") and doc.exempt_from_sales_tax \
or frappe.db.has_column("Customer", "exempt_from_sales_tax") \
and frappe.db.get_value("Customer", doc.customer, "exempt_from_sales_tax")
diff --git a/erpnext/erpnext_integrations/workspace/erpnext_integrations/erpnext_integrations.json b/erpnext/erpnext_integrations/workspace/erpnext_integrations/erpnext_integrations.json
index 45077aa..1f2619b 100644
--- a/erpnext/erpnext_integrations/workspace/erpnext_integrations/erpnext_integrations.json
+++ b/erpnext/erpnext_integrations/workspace/erpnext_integrations/erpnext_integrations.json
@@ -30,17 +30,6 @@
"type": "Link"
},
{
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Amazon MWS Settings",
- "link_count": 0,
- "link_to": "Amazon MWS Settings",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
"hidden": 0,
"is_query_report": 0,
"label": "Payments",
diff --git a/erpnext/hooks.py b/erpnext/hooks.py
index 0e29038..f8c4288 100644
--- a/erpnext/hooks.py
+++ b/erpnext/hooks.py
@@ -68,7 +68,6 @@
'Distribution': 'erpnext.domains.distribution',
'Education': 'erpnext.domains.education',
'Manufacturing': 'erpnext.domains.manufacturing',
- 'Non Profit': 'erpnext.domains.non_profit',
'Retail': 'erpnext.domains.retail',
'Services': 'erpnext.domains.services',
}
@@ -175,7 +174,6 @@
{"title": _("Fees"), "route": "/fees", "reference_doctype": "Fees", "role":"Student"},
{"title": _("Newsletter"), "route": "/newsletters", "reference_doctype": "Newsletter"},
{"title": _("Admission"), "route": "/admissions", "reference_doctype": "Student Admission", "role": "Student"},
- {"title": _("Certification"), "route": "/certification", "reference_doctype": "Certification Application", "role": "Non Profit Portal User"},
{"title": _("Material Request"), "route": "/material-requests", "reference_doctype": "Material Request", "role": "Customer"},
{"title": _("Appointment Booking"), "route": "/book_appointment"},
]
@@ -333,7 +331,6 @@
"hourly": [
'erpnext.hr.doctype.daily_work_summary_group.daily_work_summary_group.trigger_emails',
"erpnext.accounts.doctype.subscription.subscription.process_all",
- "erpnext.erpnext_integrations.doctype.amazon_mws_settings.amazon_mws_settings.schedule_get_order_details",
"erpnext.accounts.doctype.gl_entry.gl_entry.rename_gle_sle_docs",
"erpnext.erpnext_integrations.doctype.plaid_settings.plaid_settings.automatic_synchronization",
"erpnext.projects.doctype.project.project.hourly_reminder",
@@ -341,7 +338,8 @@
"erpnext.hr.doctype.shift_type.shift_type.process_auto_attendance_for_all_shifts"
],
"hourly_long": [
- "erpnext.stock.doctype.repost_item_valuation.repost_item_valuation.repost_entries"
+ "erpnext.stock.doctype.repost_item_valuation.repost_item_valuation.repost_entries",
+ "erpnext.bulk_transaction.doctype.bulk_transaction_log.bulk_transaction_log.retry_failing_transaction"
],
"daily": [
"erpnext.stock.reorder_item.reorder_item",
@@ -369,7 +367,6 @@
"erpnext.selling.doctype.quotation.quotation.set_expired_status",
"erpnext.buying.doctype.supplier_quotation.supplier_quotation.set_expired_status",
"erpnext.accounts.doctype.process_statement_of_accounts.process_statement_of_accounts.send_auto_email",
- "erpnext.non_profit.doctype.membership.membership.set_expired_status",
"erpnext.hr.doctype.interview.interview.send_daily_feedback_reminder"
],
"daily_long": [
@@ -563,19 +560,6 @@
{'doctype': 'Assessment Code', 'index': 39},
{'doctype': 'Discussion', 'index': 40},
],
- "Non Profit": [
- {'doctype': 'Certified Consultant', 'index': 1},
- {'doctype': 'Certification Application', 'index': 2},
- {'doctype': 'Volunteer', 'index': 3},
- {'doctype': 'Membership', 'index': 4},
- {'doctype': 'Member', 'index': 5},
- {'doctype': 'Donor', 'index': 6},
- {'doctype': 'Chapter', 'index': 7},
- {'doctype': 'Grant Application', 'index': 8},
- {'doctype': 'Volunteer Type', 'index': 9},
- {'doctype': 'Donor Type', 'index': 10},
- {'doctype': 'Membership Type', 'index': 11}
- ],
}
additional_timeline_content = {
diff --git a/erpnext/hr/doctype/attendance/attendance.py b/erpnext/hr/doctype/attendance/attendance.py
index b1eaaf8..b1e373e 100644
--- a/erpnext/hr/doctype/attendance/attendance.py
+++ b/erpnext/hr/doctype/attendance/attendance.py
@@ -174,16 +174,22 @@
def get_unmarked_days(employee, month, exclude_holidays=0):
import calendar
month_map = get_month_map()
-
today = get_datetime()
- dates_of_month = ['{}-{}-{}'.format(today.year, month_map[month], r) for r in range(1, calendar.monthrange(today.year, month_map[month])[1] + 1)]
+ joining_date, relieving_date = frappe.get_cached_value("Employee", employee, ["date_of_joining", "relieving_date"])
+ start_day = 1
+ end_day = calendar.monthrange(today.year, month_map[month])[1] + 1
- length = len(dates_of_month)
- month_start, month_end = dates_of_month[0], dates_of_month[length-1]
+ if joining_date and joining_date.month == month_map[month]:
+ start_day = joining_date.day
+ if relieving_date and relieving_date.month == month_map[month]:
+ end_day = relieving_date.day + 1
- records = frappe.get_all("Attendance", fields = ['attendance_date', 'employee'] , filters = [
+ dates_of_month = ['{}-{}-{}'.format(today.year, month_map[month], r) for r in range(start_day, end_day)]
+ month_start, month_end = dates_of_month[0], dates_of_month[-1]
+
+ records = frappe.get_all("Attendance", fields=['attendance_date', 'employee'], filters=[
["attendance_date", ">=", month_start],
["attendance_date", "<=", month_end],
["employee", "=", employee],
@@ -200,7 +206,7 @@
for date in dates_of_month:
date_time = get_datetime(date)
- if today.day == date_time.day and today.month == date_time.month:
+ if today.day <= date_time.day and today.month <= date_time.month:
break
if date_time not in marked_days:
unmarked_days.append(date)
diff --git a/erpnext/hr/doctype/attendance/test_attendance.py b/erpnext/hr/doctype/attendance/test_attendance.py
index a770d70..c74967d 100644
--- a/erpnext/hr/doctype/attendance/test_attendance.py
+++ b/erpnext/hr/doctype/attendance/test_attendance.py
@@ -1,20 +1,108 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and Contributors
# See license.txt
-import unittest
-
import frappe
-from frappe.utils import nowdate
+from frappe.tests.utils import FrappeTestCase
+from frappe.utils import add_days, get_first_day, getdate, now_datetime, nowdate
+
+from erpnext.hr.doctype.attendance.attendance import (
+ get_month_map,
+ get_unmarked_days,
+ mark_attendance,
+)
+from erpnext.hr.doctype.employee.test_employee import make_employee
+from erpnext.hr.doctype.leave_application.test_leave_application import get_first_sunday
test_records = frappe.get_test_records('Attendance')
-class TestAttendance(unittest.TestCase):
+class TestAttendance(FrappeTestCase):
def test_mark_absent(self):
- from erpnext.hr.doctype.employee.test_employee import make_employee
employee = make_employee("test_mark_absent@example.com")
date = nowdate()
frappe.db.delete('Attendance', {'employee':employee, 'attendance_date':date})
- from erpnext.hr.doctype.attendance.attendance import mark_attendance
attendance = mark_attendance(employee, date, 'Absent')
fetch_attendance = frappe.get_value('Attendance', {'employee':employee, 'attendance_date':date, 'status':'Absent'})
self.assertEqual(attendance, fetch_attendance)
+
+ def test_unmarked_days(self):
+ first_day = get_first_day(getdate())
+
+ employee = make_employee('test_unmarked_days@example.com', date_of_joining=add_days(first_day, -1))
+ frappe.db.delete('Attendance', {'employee': employee})
+
+ from erpnext.payroll.doctype.salary_slip.test_salary_slip import make_holiday_list
+ holiday_list = make_holiday_list()
+ frappe.db.set_value('Employee', employee, 'holiday_list', holiday_list)
+
+ first_sunday = get_first_sunday(holiday_list)
+ mark_attendance(employee, first_day, 'Present')
+ month_name = get_month_name(first_day)
+
+ unmarked_days = get_unmarked_days(employee, month_name)
+ unmarked_days = [getdate(date) for date in unmarked_days]
+
+ # attendance already marked for the day
+ self.assertNotIn(first_day, unmarked_days)
+ # attendance unmarked
+ self.assertIn(getdate(add_days(first_day, 1)), unmarked_days)
+ # holiday considered in unmarked days
+ self.assertIn(first_sunday, unmarked_days)
+
+ def test_unmarked_days_excluding_holidays(self):
+ first_day = get_first_day(getdate())
+
+ employee = make_employee('test_unmarked_days@example.com', date_of_joining=add_days(first_day, -1))
+ frappe.db.delete('Attendance', {'employee': employee})
+
+ from erpnext.payroll.doctype.salary_slip.test_salary_slip import make_holiday_list
+ holiday_list = make_holiday_list()
+ frappe.db.set_value('Employee', employee, 'holiday_list', holiday_list)
+
+ first_sunday = get_first_sunday(holiday_list)
+ mark_attendance(employee, first_day, 'Present')
+ month_name = get_month_name(first_day)
+
+ unmarked_days = get_unmarked_days(employee, month_name, exclude_holidays=True)
+ unmarked_days = [getdate(date) for date in unmarked_days]
+
+ # attendance already marked for the day
+ self.assertNotIn(first_day, unmarked_days)
+ # attendance unmarked
+ self.assertIn(getdate(add_days(first_day, 1)), unmarked_days)
+ # holidays not considered in unmarked days
+ self.assertNotIn(first_sunday, unmarked_days)
+
+ def test_unmarked_days_as_per_joining_and_relieving_dates(self):
+ now = now_datetime()
+ previous_month = now.month - 1
+ first_day = now.replace(day=1).replace(month=previous_month).date()
+
+ doj = add_days(first_day, 1)
+ relieving_date = add_days(first_day, 5)
+ employee = make_employee('test_unmarked_days_as_per_doj@example.com', date_of_joining=doj,
+ relieving_date=relieving_date)
+ frappe.db.delete('Attendance', {'employee': employee})
+
+ attendance_date = add_days(first_day, 2)
+ mark_attendance(employee, attendance_date, 'Present')
+ month_name = get_month_name(first_day)
+
+ unmarked_days = get_unmarked_days(employee, month_name)
+ unmarked_days = [getdate(date) for date in unmarked_days]
+
+ # attendance already marked for the day
+ self.assertNotIn(attendance_date, unmarked_days)
+ # date before doj not in unmarked days
+ self.assertNotIn(add_days(doj, -1), unmarked_days)
+ # date after relieving not in unmarked days
+ self.assertNotIn(add_days(relieving_date, 1), unmarked_days)
+
+ def tearDown(self):
+ frappe.db.rollback()
+
+
+def get_month_name(date):
+ month_number = date.month
+ for month, number in get_month_map().items():
+ if number == month_number:
+ return month
diff --git a/erpnext/hr/doctype/department/department.py b/erpnext/hr/doctype/department/department.py
index ed0bfcf..71300c4 100644
--- a/erpnext/hr/doctype/department/department.py
+++ b/erpnext/hr/doctype/department/department.py
@@ -32,7 +32,7 @@
return new
def on_update(self):
- if not frappe.local.flags.ignore_update_nsm:
+ if not (frappe.local.flags.ignore_update_nsm or frappe.flags.in_setup_wizard):
super(Department, self).on_update()
def on_trash(self):
diff --git a/erpnext/hr/doctype/department/test_records.json b/erpnext/hr/doctype/department/test_records.json
index 654925e..e3421f2 100644
--- a/erpnext/hr/doctype/department/test_records.json
+++ b/erpnext/hr/doctype/department/test_records.json
@@ -1,4 +1,4 @@
[
- {"doctype":"Department", "department_name":"_Test Department", "company": "_Test Company"},
- {"doctype":"Department", "department_name":"_Test Department 1", "company": "_Test Company"}
+ {"doctype":"Department", "department_name":"_Test Department", "company": "_Test Company", "parent_department": "All Departments"},
+ {"doctype":"Department", "department_name":"_Test Department 1", "company": "_Test Company", "parent_department": "All Departments"}
]
\ No newline at end of file
diff --git a/erpnext/hr/doctype/employee/employee.py b/erpnext/hr/doctype/employee/employee.py
index a2df26c..6e52eb9 100755
--- a/erpnext/hr/doctype/employee/employee.py
+++ b/erpnext/hr/doctype/employee/employee.py
@@ -142,7 +142,7 @@
"file_url": self.image,
"attached_to_doctype": "User",
"attached_to_name": self.user_id
- }).insert()
+ }).insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
# already exists
pass
diff --git a/erpnext/hr/doctype/employee_advance/employee_advance.json b/erpnext/hr/doctype/employee_advance/employee_advance.json
index 0475453..b050183 100644
--- a/erpnext/hr/doctype/employee_advance/employee_advance.json
+++ b/erpnext/hr/doctype/employee_advance/employee_advance.json
@@ -2,7 +2,7 @@
"actions": [],
"allow_import": 1,
"autoname": "naming_series:",
- "creation": "2017-10-09 14:26:29.612365",
+ "creation": "2022-01-17 18:36:51.450395",
"doctype": "DocType",
"editable_grid": 1,
"engine": "InnoDB",
@@ -121,7 +121,7 @@
"fieldtype": "Select",
"label": "Status",
"no_copy": 1,
- "options": "Draft\nPaid\nUnpaid\nClaimed\nCancelled",
+ "options": "Draft\nPaid\nUnpaid\nClaimed\nReturned\nPartly Claimed and Returned\nCancelled",
"read_only": 1
},
{
@@ -200,7 +200,7 @@
],
"is_submittable": 1,
"links": [],
- "modified": "2021-09-11 18:38:38.617478",
+ "modified": "2022-01-17 19:33:52.345823",
"modified_by": "Administrator",
"module": "HR",
"name": "Employee Advance",
@@ -237,5 +237,41 @@
"search_fields": "employee,employee_name",
"sort_field": "modified",
"sort_order": "DESC",
+ "states": [
+ {
+ "color": "Red",
+ "custom": 1,
+ "title": "Draft"
+ },
+ {
+ "color": "Green",
+ "custom": 1,
+ "title": "Paid"
+ },
+ {
+ "color": "Orange",
+ "custom": 1,
+ "title": "Unpaid"
+ },
+ {
+ "color": "Blue",
+ "custom": 1,
+ "title": "Claimed"
+ },
+ {
+ "color": "Gray",
+ "title": "Returned"
+ },
+ {
+ "color": "Yellow",
+ "title": "Partly Claimed and Returned"
+ },
+ {
+ "color": "Red",
+ "custom": 1,
+ "title": "Cancelled"
+ }
+ ],
+ "title_field": "employee_name",
"track_changes": 1
}
\ No newline at end of file
diff --git a/erpnext/hr/doctype/employee_advance/employee_advance.py b/erpnext/hr/doctype/employee_advance/employee_advance.py
index 7aac2b6..79d389d 100644
--- a/erpnext/hr/doctype/employee_advance/employee_advance.py
+++ b/erpnext/hr/doctype/employee_advance/employee_advance.py
@@ -27,19 +27,33 @@
def on_cancel(self):
self.ignore_linked_doctypes = ('GL Entry')
+ self.set_status(update=True)
- def set_status(self):
+ def set_status(self, update=False):
+ precision = self.precision("paid_amount")
+ total_amount = flt(flt(self.claimed_amount) + flt(self.return_amount), precision)
+ status = None
+
if self.docstatus == 0:
- self.status = "Draft"
- if self.docstatus == 1:
- if self.claimed_amount and flt(self.claimed_amount) == flt(self.paid_amount):
- self.status = "Claimed"
- elif self.paid_amount and self.advance_amount == flt(self.paid_amount):
- self.status = "Paid"
+ status = "Draft"
+ elif self.docstatus == 1:
+ if flt(self.claimed_amount) > 0 and flt(self.claimed_amount, precision) == flt(self.paid_amount, precision):
+ status = "Claimed"
+ elif flt(self.return_amount) > 0 and flt(self.return_amount, precision) == flt(self.paid_amount, precision):
+ status = "Returned"
+ elif flt(self.claimed_amount) > 0 and (flt(self.return_amount) > 0) and total_amount == flt(self.paid_amount, precision):
+ status = "Partly Claimed and Returned"
+ elif flt(self.paid_amount) > 0 and flt(self.advance_amount, precision) == flt(self.paid_amount, precision):
+ status = "Paid"
else:
- self.status = "Unpaid"
+ status = "Unpaid"
elif self.docstatus == 2:
- self.status = "Cancelled"
+ status = "Cancelled"
+
+ if update:
+ self.db_set("status", status)
+ else:
+ self.status = status
def set_total_advance_paid(self):
gle = frappe.qb.DocType("GL Entry")
@@ -85,9 +99,7 @@
self.db_set("paid_amount", paid_amount)
self.db_set("return_amount", return_amount)
- self.set_status()
- frappe.db.set_value("Employee Advance", self.name , "status", self.status)
-
+ self.set_status(update=True)
def update_claimed_amount(self):
claimed_amount = frappe.db.sql("""
@@ -103,8 +115,8 @@
frappe.db.set_value("Employee Advance", self.name, "claimed_amount", flt(claimed_amount))
self.reload()
- self.set_status()
- frappe.db.set_value("Employee Advance", self.name, "status", self.status)
+ self.set_status(update=True)
+
@frappe.whitelist()
def get_pending_amount(employee, posting_date):
@@ -222,7 +234,8 @@
'reference_name': employee_advance_name,
'party_type': 'Employee',
'party': employee,
- 'is_advance': 'Yes'
+ 'is_advance': 'Yes',
+ 'cost_center': erpnext.get_default_cost_center(company)
})
bank_amount = flt(return_amount) if bank_cash_account.account_currency==currency \
@@ -233,7 +246,8 @@
"debit_in_account_currency": bank_amount,
"account_currency": bank_cash_account.account_currency,
"account_type": bank_cash_account.account_type,
- "exchange_rate": flt(exchange_rate) if bank_cash_account.account_currency == currency else 1
+ "exchange_rate": flt(exchange_rate) if bank_cash_account.account_currency == currency else 1,
+ "cost_center": erpnext.get_default_cost_center(company)
})
return je.as_dict()
diff --git a/erpnext/hr/doctype/employee_advance/test_employee_advance.py b/erpnext/hr/doctype/employee_advance/test_employee_advance.py
index 5f2e720..e3c1487 100644
--- a/erpnext/hr/doctype/employee_advance/test_employee_advance.py
+++ b/erpnext/hr/doctype/employee_advance/test_employee_advance.py
@@ -4,7 +4,7 @@
import unittest
import frappe
-from frappe.utils import nowdate
+from frappe.utils import flt, nowdate
import erpnext
from erpnext.hr.doctype.employee.test_employee import make_employee
@@ -12,12 +12,21 @@
EmployeeAdvanceOverPayment,
create_return_through_additional_salary,
make_bank_entry,
+ make_return_entry,
+)
+from erpnext.hr.doctype.expense_claim.expense_claim import get_advances
+from erpnext.hr.doctype.expense_claim.test_expense_claim import (
+ get_payable_account,
+ make_expense_claim,
)
from erpnext.payroll.doctype.salary_component.test_salary_component import create_salary_component
from erpnext.payroll.doctype.salary_structure.test_salary_structure import make_salary_structure
class TestEmployeeAdvance(unittest.TestCase):
+ def setUp(self):
+ frappe.db.delete("Employee Advance")
+
def test_paid_amount_and_status(self):
employee_name = make_employee("_T@employe.advance")
advance = make_employee_advance(employee_name)
@@ -52,9 +61,102 @@
self.assertEqual(advance.paid_amount, 0)
self.assertEqual(advance.status, "Unpaid")
+ advance.cancel()
+ advance.reload()
+ self.assertEqual(advance.status, "Cancelled")
+
+ def test_claimed_status(self):
+ # CLAIMED Status check, full amount claimed
+ payable_account = get_payable_account("_Test Company")
+ claim = make_expense_claim(payable_account, 1000, 1000, "_Test Company", "Travel Expenses - _TC", do_not_submit=True)
+
+ advance = make_employee_advance(claim.employee)
+ pe = make_payment_entry(advance)
+ pe.submit()
+
+ claim = get_advances_for_claim(claim, advance.name)
+ claim.save()
+ claim.submit()
+
+ advance.reload()
+ self.assertEqual(advance.claimed_amount, 1000)
+ self.assertEqual(advance.status, "Claimed")
+
+ # advance should not be shown in claims
+ advances = get_advances(claim.employee)
+ advances = [entry.name for entry in advances]
+ self.assertTrue(advance.name not in advances)
+
+ # cancel claim; status should be Paid
+ claim.cancel()
+ advance.reload()
+ self.assertEqual(advance.claimed_amount, 0)
+ self.assertEqual(advance.status, "Paid")
+
+ def test_partly_claimed_and_returned_status(self):
+ payable_account = get_payable_account("_Test Company")
+ claim = make_expense_claim(payable_account, 1000, 1000, "_Test Company", "Travel Expenses - _TC", do_not_submit=True)
+
+ advance = make_employee_advance(claim.employee)
+ pe = make_payment_entry(advance)
+ pe.submit()
+
+ # PARTLY CLAIMED AND RETURNED status check
+ # 500 Claimed, 500 Returned
+ claim = make_expense_claim(payable_account, 500, 500, "_Test Company", "Travel Expenses - _TC", do_not_submit=True)
+
+ advance = make_employee_advance(claim.employee)
+ pe = make_payment_entry(advance)
+ pe.submit()
+
+ claim = get_advances_for_claim(claim, advance.name, amount=500)
+ claim.save()
+ claim.submit()
+
+ advance.reload()
+ self.assertEqual(advance.claimed_amount, 500)
+ self.assertEqual(advance.status, "Paid")
+
+ entry = make_return_entry(
+ employee=advance.employee,
+ company=advance.company,
+ employee_advance_name=advance.name,
+ return_amount=flt(advance.paid_amount - advance.claimed_amount),
+ advance_account=advance.advance_account,
+ mode_of_payment=advance.mode_of_payment,
+ currency=advance.currency,
+ exchange_rate=advance.exchange_rate
+ )
+
+ entry = frappe.get_doc(entry)
+ entry.insert()
+ entry.submit()
+
+ advance.reload()
+ self.assertEqual(advance.return_amount, 500)
+ self.assertEqual(advance.status, "Partly Claimed and Returned")
+
+ # advance should not be shown in claims
+ advances = get_advances(claim.employee)
+ advances = [entry.name for entry in advances]
+ self.assertTrue(advance.name not in advances)
+
+ # Cancel return entry; status should change to PAID
+ entry.cancel()
+ advance.reload()
+ self.assertEqual(advance.return_amount, 0)
+ self.assertEqual(advance.status, "Paid")
+
+ # advance should be shown in claims
+ advances = get_advances(claim.employee)
+ advances = [entry.name for entry in advances]
+ self.assertTrue(advance.name in advances)
+
def test_repay_unclaimed_amount_from_salary(self):
employee_name = make_employee("_T@employe.advance")
advance = make_employee_advance(employee_name, {"repay_unclaimed_amount_from_salary": 1})
+ pe = make_payment_entry(advance)
+ pe.submit()
args = {"type": "Deduction"}
create_salary_component("Advance Salary - Deduction", **args)
@@ -82,11 +184,13 @@
advance.reload()
self.assertEqual(advance.return_amount, 1000)
+ self.assertEqual(advance.status, "Returned")
# update advance return amount on additional salary cancellation
additional_salary.cancel()
advance.reload()
self.assertEqual(advance.return_amount, 700)
+ self.assertEqual(advance.status, "Paid")
def tearDown(self):
frappe.db.rollback()
@@ -118,3 +222,24 @@
doc.submit()
return doc
+
+
+def get_advances_for_claim(claim, advance_name, amount=None):
+ advances = get_advances(claim.employee, advance_name)
+
+ for entry in advances:
+ if amount:
+ allocated_amount = amount
+ else:
+ allocated_amount = flt(entry.paid_amount) - flt(entry.claimed_amount)
+
+ claim.append("advances", {
+ "employee_advance": entry.name,
+ "posting_date": entry.posting_date,
+ "advance_account": entry.advance_account,
+ "advance_paid": entry.paid_amount,
+ "unclaimed_amount": allocated_amount,
+ "allocated_amount": allocated_amount
+ })
+
+ return claim
\ No newline at end of file
diff --git a/erpnext/hr/doctype/employee_group_table/employee_group_table.json b/erpnext/hr/doctype/employee_group_table/employee_group_table.json
index 4e0045c..54eb8c6 100644
--- a/erpnext/hr/doctype/employee_group_table/employee_group_table.json
+++ b/erpnext/hr/doctype/employee_group_table/employee_group_table.json
@@ -27,12 +27,13 @@
"fetch_from": "employee.user_id",
"fieldname": "user_id",
"fieldtype": "Data",
+ "in_list_view": 1,
"label": "ERPNext User ID",
"read_only": 1
}
],
"istable": 1,
- "modified": "2019-06-06 10:41:20.313756",
+ "modified": "2022-02-13 19:44:21.302938",
"modified_by": "Administrator",
"module": "HR",
"name": "Employee Group Table",
@@ -42,4 +43,4 @@
"sort_field": "modified",
"sort_order": "DESC",
"track_changes": 1
-}
\ No newline at end of file
+}
diff --git a/erpnext/hr/doctype/employee_onboarding/test_employee_onboarding.py b/erpnext/hr/doctype/employee_onboarding/test_employee_onboarding.py
index 2d129c8..0fb821d 100644
--- a/erpnext/hr/doctype/employee_onboarding/test_employee_onboarding.py
+++ b/erpnext/hr/doctype/employee_onboarding/test_employee_onboarding.py
@@ -4,7 +4,7 @@
import unittest
import frappe
-from frappe.utils import getdate
+from frappe.utils import add_days, getdate
from erpnext.hr.doctype.employee_onboarding.employee_onboarding import (
IncompleteTaskError,
@@ -35,6 +35,15 @@
# boarding status
self.assertEqual(onboarding.boarding_status, 'Pending')
+ # start and end dates
+ start_date, end_date = frappe.db.get_value('Task', onboarding.activities[0].task, ['exp_start_date', 'exp_end_date'])
+ self.assertEqual(getdate(start_date), getdate(onboarding.boarding_begins_on))
+ self.assertEqual(getdate(end_date), add_days(start_date, onboarding.activities[0].duration))
+
+ start_date, end_date = frappe.db.get_value('Task', onboarding.activities[1].task, ['exp_start_date', 'exp_end_date'])
+ self.assertEqual(getdate(start_date), add_days(onboarding.boarding_begins_on, onboarding.activities[0].duration))
+ self.assertEqual(getdate(end_date), add_days(start_date, onboarding.activities[1].duration))
+
# complete the task
project = frappe.get_doc('Project', onboarding.project)
for task in frappe.get_all('Task', dict(project=project.name)):
@@ -57,10 +66,7 @@
self.assertEqual(employee.employee_name, 'Test Researcher')
def tearDown(self):
- for entry in frappe.get_all('Employee Onboarding'):
- doc = frappe.get_doc('Employee Onboarding', entry.name)
- doc.cancel()
- doc.delete()
+ frappe.db.rollback()
def get_job_applicant():
@@ -87,23 +93,31 @@
def create_employee_onboarding():
applicant = get_job_applicant()
job_offer = get_job_offer(applicant.name)
- holiday_list = make_holiday_list()
+
+ holiday_list = make_holiday_list('_Test Employee Boarding')
+ holiday_list = frappe.get_doc('Holiday List', holiday_list)
+ holiday_list.holidays = []
+ holiday_list.save()
onboarding = frappe.new_doc('Employee Onboarding')
onboarding.job_applicant = applicant.name
onboarding.job_offer = job_offer.name
onboarding.date_of_joining = onboarding.boarding_begins_on = getdate()
onboarding.company = '_Test Company'
- onboarding.holiday_list = holiday_list
+ onboarding.holiday_list = holiday_list.name
onboarding.designation = 'Researcher'
onboarding.append('activities', {
'activity_name': 'Assign ID Card',
'role': 'HR User',
- 'required_for_employee_creation': 1
+ 'required_for_employee_creation': 1,
+ 'begin_on': 0,
+ 'duration': 1
})
onboarding.append('activities', {
'activity_name': 'Assign a laptop',
- 'role': 'HR User'
+ 'role': 'HR User',
+ 'begin_on': 1,
+ 'duration': 1
})
onboarding.status = 'Pending'
onboarding.insert()
diff --git a/erpnext/hr/doctype/exit_interview/exit_interview.py b/erpnext/hr/doctype/exit_interview/exit_interview.py
index 30e19f1..59fb2fd 100644
--- a/erpnext/hr/doctype/exit_interview/exit_interview.py
+++ b/erpnext/hr/doctype/exit_interview/exit_interview.py
@@ -128,4 +128,4 @@
message += _('{0} due to missing email information for employee(s): {1}').format(
frappe.bold('Sending Failed'), ', '.join(email_failure))
- frappe.msgprint(message, title=_('Exit Questionnaire'), indicator='blue', is_minimizable=True, wide=True)
\ No newline at end of file
+ frappe.msgprint(message, title=_('Exit Questionnaire'), indicator='blue', is_minimizable=True, wide=True)
diff --git a/erpnext/hr/doctype/expense_claim/expense_claim.js b/erpnext/hr/doctype/expense_claim/expense_claim.js
index 0479457..af80b63 100644
--- a/erpnext/hr/doctype/expense_claim/expense_claim.js
+++ b/erpnext/hr/doctype/expense_claim/expense_claim.js
@@ -171,7 +171,7 @@
['docstatus', '=', 1],
['employee', '=', frm.doc.employee],
['paid_amount', '>', 0],
- ['status', '!=', 'Claimed']
+ ['status', 'not in', ['Claimed', 'Returned', 'Partly Claimed and Returned']]
]
};
});
diff --git a/erpnext/hr/doctype/expense_claim/expense_claim.py b/erpnext/hr/doctype/expense_claim/expense_claim.py
index 7e3898b..fe04efb 100644
--- a/erpnext/hr/doctype/expense_claim/expense_claim.py
+++ b/erpnext/hr/doctype/expense_claim/expense_claim.py
@@ -23,10 +23,10 @@
def validate(self):
validate_active_employee(self.employee)
- self.validate_advances()
+ set_employee_name(self)
self.validate_sanctioned_amount()
self.calculate_total_amount()
- set_employee_name(self)
+ self.validate_advances()
self.set_expense_account(validate=True)
self.set_payable_account()
self.set_cost_center()
@@ -341,18 +341,27 @@
@frappe.whitelist()
def get_advances(employee, advance_id=None):
- if not advance_id:
- condition = 'docstatus=1 and employee={0} and paid_amount > 0 and paid_amount > claimed_amount + return_amount'.format(frappe.db.escape(employee))
- else:
- condition = 'name={0}'.format(frappe.db.escape(advance_id))
+ advance = frappe.qb.DocType("Employee Advance")
- return frappe.db.sql("""
- select
- name, posting_date, paid_amount, claimed_amount, advance_account
- from
- `tabEmployee Advance`
- where {0}
- """.format(condition), as_dict=1)
+ query = (
+ frappe.qb.from_(advance)
+ .select(
+ advance.name, advance.posting_date, advance.paid_amount,
+ advance.claimed_amount, advance.advance_account
+ )
+ )
+
+ if not advance_id:
+ query = query.where(
+ (advance.docstatus == 1)
+ & (advance.employee == employee)
+ & (advance.paid_amount > 0)
+ & (advance.status.notin(["Claimed", "Returned", "Partly Claimed and Returned"]))
+ )
+ else:
+ query = query.where(advance.name == advance_id)
+
+ return query.run(as_dict=True)
@frappe.whitelist()
diff --git a/erpnext/hr/doctype/leave_application/leave_application.py b/erpnext/hr/doctype/leave_application/leave_application.py
index 70250f5..ef5f4bc 100755
--- a/erpnext/hr/doctype/leave_application/leave_application.py
+++ b/erpnext/hr/doctype/leave_application/leave_application.py
@@ -4,6 +4,7 @@
import frappe
from frappe import _
+from frappe.query_builder.functions import Max, Min, Sum
from frappe.utils import (
add_days,
cint,
@@ -567,28 +568,39 @@
return get_remaining_leaves(allocation, leaves_taken, date, expiry)
def get_leave_allocation_records(employee, date, leave_type=None):
- ''' returns the total allocated leaves and carry forwarded leaves based on ledger entries '''
+ """Returns the total allocated leaves and carry forwarded leaves based on ledger entries"""
+ Ledger = frappe.qb.DocType("Leave Ledger Entry")
- conditions = ("and leave_type='%s'" % leave_type) if leave_type else ""
- allocation_details = frappe.db.sql("""
- SELECT
- SUM(CASE WHEN is_carry_forward = 1 THEN leaves ELSE 0 END) as cf_leaves,
- SUM(CASE WHEN is_carry_forward = 0 THEN leaves ELSE 0 END) as new_leaves,
- MIN(from_date) as from_date,
- MAX(to_date) as to_date,
- leave_type
- FROM `tabLeave Ledger Entry`
- WHERE
- from_date <= %(date)s
- AND to_date >= %(date)s
- AND docstatus=1
- AND transaction_type="Leave Allocation"
- AND employee=%(employee)s
- AND is_expired=0
- AND is_lwp=0
- {0}
- GROUP BY employee, leave_type
- """.format(conditions), dict(date=date, employee=employee), as_dict=1) #nosec
+ cf_leave_case = frappe.qb.terms.Case().when(Ledger.is_carry_forward == "1", Ledger.leaves).else_(0)
+ sum_cf_leaves = Sum(cf_leave_case).as_("cf_leaves")
+
+ new_leaves_case = frappe.qb.terms.Case().when(Ledger.is_carry_forward == "0", Ledger.leaves).else_(0)
+ sum_new_leaves = Sum(new_leaves_case).as_("new_leaves")
+
+ query = (
+ frappe.qb.from_(Ledger)
+ .select(
+ sum_cf_leaves,
+ sum_new_leaves,
+ Min(Ledger.from_date).as_("from_date"),
+ Max(Ledger.to_date).as_("to_date"),
+ Ledger.leave_type
+ ).where(
+ (Ledger.from_date <= date)
+ & (Ledger.to_date >= date)
+ & (Ledger.docstatus == 1)
+ & (Ledger.transaction_type == "Leave Allocation")
+ & (Ledger.employee == employee)
+ & (Ledger.is_expired == 0)
+ & (Ledger.is_lwp == 0)
+ )
+ )
+
+ if leave_type:
+ query = query.where((Ledger.leave_type == leave_type))
+ query = query.groupby(Ledger.employee, Ledger.leave_type)
+
+ allocation_details = query.run(as_dict=True)
allocated_leaves = frappe._dict()
for d in allocation_details:
diff --git a/erpnext/hr/doctype/leave_application/test_leave_application.py b/erpnext/hr/doctype/leave_application/test_leave_application.py
index 6b85927..7b3aa49 100644
--- a/erpnext/hr/doctype/leave_application/test_leave_application.py
+++ b/erpnext/hr/doctype/leave_application/test_leave_application.py
@@ -546,7 +546,7 @@
from erpnext.hr.utils import allocate_earned_leaves
i = 0
while(i<14):
- allocate_earned_leaves()
+ allocate_earned_leaves(ignore_duplicates=True)
i += 1
self.assertEqual(get_leave_balance_on(employee.name, leave_type, nowdate()), 6)
@@ -554,7 +554,7 @@
frappe.db.set_value('Leave Type', leave_type, 'max_leaves_allowed', 0)
i = 0
while(i<6):
- allocate_earned_leaves()
+ allocate_earned_leaves(ignore_duplicates=True)
i += 1
self.assertEqual(get_leave_balance_on(employee.name, leave_type, nowdate()), 9)
@@ -792,4 +792,4 @@
order by holiday_date
""", (holiday_list, month_start_date, month_end_date))[0][0]
- return first_sunday
\ No newline at end of file
+ return first_sunday
diff --git a/erpnext/hr/doctype/leave_policy_assignment/leave_policy_assignment.py b/erpnext/hr/doctype/leave_policy_assignment/leave_policy_assignment.py
index 355370f..c11a821 100644
--- a/erpnext/hr/doctype/leave_policy_assignment/leave_policy_assignment.py
+++ b/erpnext/hr/doctype/leave_policy_assignment/leave_policy_assignment.py
@@ -8,11 +8,10 @@
import frappe
from frappe import _, bold
from frappe.model.document import Document
-from frappe.utils import date_diff, flt, formatdate, get_datetime, getdate
+from frappe.utils import date_diff, flt, formatdate, get_last_day, getdate
class LeavePolicyAssignment(Document):
-
def validate(self):
self.validate_policy_assignment_overlap()
self.set_dates()
@@ -94,10 +93,12 @@
new_leaves_allocated = 0
elif leave_type_details.get(leave_type).is_earned_leave == 1:
- if self.assignment_based_on == "Leave Period":
- new_leaves_allocated = self.get_leaves_for_passed_months(leave_type, new_leaves_allocated, leave_type_details, date_of_joining)
- else:
+ if not self.assignment_based_on:
new_leaves_allocated = 0
+ else:
+ # get leaves for past months if assignment is based on Leave Period / Joining Date
+ new_leaves_allocated = self.get_leaves_for_passed_months(leave_type, new_leaves_allocated, leave_type_details, date_of_joining)
+
# Calculate leaves at pro-rata basis for employees joining after the beginning of the given leave period
elif getdate(date_of_joining) > getdate(self.effective_from):
remaining_period = ((date_diff(self.effective_to, date_of_joining) + 1) / (date_diff(self.effective_to, self.effective_from) + 1))
@@ -108,21 +109,24 @@
def get_leaves_for_passed_months(self, leave_type, new_leaves_allocated, leave_type_details, date_of_joining):
from erpnext.hr.utils import get_monthly_earned_leave
- current_month = get_datetime().month
- current_year = get_datetime().year
+ current_date = frappe.flags.current_date or getdate()
+ if current_date > getdate(self.effective_to):
+ current_date = getdate(self.effective_to)
- from_date = frappe.db.get_value("Leave Period", self.leave_period, "from_date")
- if getdate(date_of_joining) > getdate(from_date):
- from_date = date_of_joining
-
- from_date_month = get_datetime(from_date).month
- from_date_year = get_datetime(from_date).year
+ from_date = getdate(self.effective_from)
+ if getdate(date_of_joining) > from_date:
+ from_date = getdate(date_of_joining)
months_passed = 0
- if current_year == from_date_year and current_month > from_date_month:
- months_passed = current_month - from_date_month
- elif current_year > from_date_year:
- months_passed = (12 - from_date_month) + current_month
+ based_on_doj = leave_type_details.get(leave_type).based_on_date_of_joining
+
+ if current_date.year == from_date.year and current_date.month >= from_date.month:
+ months_passed = current_date.month - from_date.month
+ months_passed = add_current_month_if_applicable(months_passed, date_of_joining, based_on_doj)
+
+ elif current_date.year > from_date.year:
+ months_passed = (12 - from_date.month) + current_date.month
+ months_passed = add_current_month_if_applicable(months_passed, date_of_joining, based_on_doj)
if months_passed > 0:
monthly_earned_leave = get_monthly_earned_leave(new_leaves_allocated,
@@ -134,6 +138,23 @@
return new_leaves_allocated
+def add_current_month_if_applicable(months_passed, date_of_joining, based_on_doj):
+ date = getdate(frappe.flags.current_date) or getdate()
+
+ if based_on_doj:
+ # if leave type allocation is based on DOJ, and the date of assignment creation is same as DOJ,
+ # then the month should be considered
+ if date.day == date_of_joining.day:
+ months_passed += 1
+ else:
+ last_day_of_month = get_last_day(date)
+ # if its the last day of the month, then that month should be considered
+ if last_day_of_month == date:
+ months_passed += 1
+
+ return months_passed
+
+
@frappe.whitelist()
def create_assignment_for_multiple_employees(employees, data):
@@ -168,7 +189,7 @@
def get_leave_type_details():
leave_type_details = frappe._dict()
leave_types = frappe.get_all("Leave Type",
- fields=["name", "is_lwp", "is_earned_leave", "is_compensatory",
+ fields=["name", "is_lwp", "is_earned_leave", "is_compensatory", "based_on_date_of_joining",
"is_carry_forward", "expire_carry_forwarded_leaves_after_days", "earned_leave_frequency", "rounding"])
for d in leave_types:
leave_type_details.setdefault(d.name, d)
diff --git a/erpnext/hr/doctype/leave_policy_assignment/test_leave_policy_assignment.py b/erpnext/hr/doctype/leave_policy_assignment/test_leave_policy_assignment.py
index 3b7f8ec..a19ddce 100644
--- a/erpnext/hr/doctype/leave_policy_assignment/test_leave_policy_assignment.py
+++ b/erpnext/hr/doctype/leave_policy_assignment/test_leave_policy_assignment.py
@@ -4,7 +4,7 @@
import unittest
import frappe
-from frappe.utils import add_months, get_first_day, getdate
+from frappe.utils import add_months, get_first_day, get_last_day, getdate
from erpnext.hr.doctype.leave_application.test_leave_application import (
get_employee,
@@ -20,36 +20,31 @@
class TestLeavePolicyAssignment(unittest.TestCase):
def setUp(self):
for doctype in ["Leave Period", "Leave Application", "Leave Allocation", "Leave Policy Assignment", "Leave Ledger Entry"]:
- frappe.db.sql("delete from `tab{0}`".format(doctype)) #nosec
+ frappe.db.delete(doctype)
+
+ employee = get_employee()
+ self.original_doj = employee.date_of_joining
+ self.employee = employee
def test_grant_leaves(self):
leave_period = get_leave_period()
- employee = get_employee()
-
- # create the leave policy with leave type "_Test Leave Type", allocation = 10
+ # allocation = 10
leave_policy = create_leave_policy()
leave_policy.submit()
-
data = {
"assignment_based_on": "Leave Period",
"leave_policy": leave_policy.name,
"leave_period": leave_period.name
}
-
- leave_policy_assignments = create_assignment_for_multiple_employees([employee.name], frappe._dict(data))
-
- leave_policy_assignment_doc = frappe.get_doc("Leave Policy Assignment", leave_policy_assignments[0])
- leave_policy_assignment_doc.reload()
-
- self.assertEqual(leave_policy_assignment_doc.leaves_allocated, 1)
+ leave_policy_assignments = create_assignment_for_multiple_employees([self.employee.name], frappe._dict(data))
+ self.assertEqual(frappe.db.get_value("Leave Policy Assignment", leave_policy_assignments[0], "leaves_allocated"), 1)
leave_allocation = frappe.get_list("Leave Allocation", filters={
- "employee": employee.name,
+ "employee": self.employee.name,
"leave_policy":leave_policy.name,
"leave_policy_assignment": leave_policy_assignments[0],
"docstatus": 1})[0]
-
leave_alloc_doc = frappe.get_doc("Leave Allocation", leave_allocation)
self.assertEqual(leave_alloc_doc.new_leaves_allocated, 10)
@@ -61,63 +56,46 @@
def test_allow_to_grant_all_leave_after_cancellation_of_every_leave_allocation(self):
leave_period = get_leave_period()
- employee = get_employee()
-
# create the leave policy with leave type "_Test Leave Type", allocation = 10
leave_policy = create_leave_policy()
leave_policy.submit()
-
data = {
"assignment_based_on": "Leave Period",
"leave_policy": leave_policy.name,
"leave_period": leave_period.name
}
-
- leave_policy_assignments = create_assignment_for_multiple_employees([employee.name], frappe._dict(data))
-
- leave_policy_assignment_doc = frappe.get_doc("Leave Policy Assignment", leave_policy_assignments[0])
- leave_policy_assignment_doc.reload()
-
+ leave_policy_assignments = create_assignment_for_multiple_employees([self.employee.name], frappe._dict(data))
# every leave is allocated no more leave can be granted now
- self.assertEqual(leave_policy_assignment_doc.leaves_allocated, 1)
-
+ self.assertEqual(frappe.db.get_value("Leave Policy Assignment", leave_policy_assignments[0], "leaves_allocated"), 1)
leave_allocation = frappe.get_list("Leave Allocation", filters={
- "employee": employee.name,
+ "employee": self.employee.name,
"leave_policy":leave_policy.name,
"leave_policy_assignment": leave_policy_assignments[0],
"docstatus": 1})[0]
leave_alloc_doc = frappe.get_doc("Leave Allocation", leave_allocation)
-
- # User all allowed to grant leave when there is no allocation against assignment
leave_alloc_doc.cancel()
leave_alloc_doc.delete()
-
- leave_policy_assignment_doc.reload()
-
-
- # User are now allowed to grant leave
- self.assertEqual(leave_policy_assignment_doc.leaves_allocated, 0)
+ self.assertEqual(frappe.db.get_value("Leave Policy Assignment", leave_policy_assignments[0], "leaves_allocated"), 0)
def test_earned_leave_allocation(self):
leave_period = create_leave_period("Test Earned Leave Period")
- employee = get_employee()
leave_type = create_earned_leave_type("Test Earned Leave")
leave_policy = frappe.get_doc({
"doctype": "Leave Policy",
"title": "Test Leave Policy",
"leave_policy_details": [{"leave_type": leave_type.name, "annual_allocation": 6}]
- }).insert()
+ }).submit()
data = {
"assignment_based_on": "Leave Period",
"leave_policy": leave_policy.name,
"leave_period": leave_period.name
}
- leave_policy_assignments = create_assignment_for_multiple_employees([employee.name], frappe._dict(data))
+ leave_policy_assignments = create_assignment_for_multiple_employees([self.employee.name], frappe._dict(data))
# leaves allocated should be 0 since it is an earned leave and allocation happens via scheduler based on set frequency
leaves_allocated = frappe.db.get_value("Leave Allocation", {
@@ -125,11 +103,200 @@
}, "total_leaves_allocated")
self.assertEqual(leaves_allocated, 0)
+ def test_earned_leave_alloc_for_passed_months_based_on_leave_period(self):
+ leave_period, leave_policy = setup_leave_period_and_policy(get_first_day(add_months(getdate(), -1)))
+
+ # Case 1: assignment created one month after the leave period, should allocate 1 leave
+ frappe.flags.current_date = get_first_day(getdate())
+ data = {
+ "assignment_based_on": "Leave Period",
+ "leave_policy": leave_policy.name,
+ "leave_period": leave_period.name
+ }
+ leave_policy_assignments = create_assignment_for_multiple_employees([self.employee.name], frappe._dict(data))
+
+ leaves_allocated = frappe.db.get_value("Leave Allocation", {
+ "leave_policy_assignment": leave_policy_assignments[0]
+ }, "total_leaves_allocated")
+ self.assertEqual(leaves_allocated, 1)
+
+ def test_earned_leave_alloc_for_passed_months_on_month_end_based_on_leave_period(self):
+ leave_period, leave_policy = setup_leave_period_and_policy(get_first_day(add_months(getdate(), -2)))
+ # Case 2: assignment created on the last day of the leave period's latter month
+ # should allocate 1 leave for current month even though the month has not ended
+ # since the daily job might have already executed
+ frappe.flags.current_date = get_last_day(getdate())
+
+ data = {
+ "assignment_based_on": "Leave Period",
+ "leave_policy": leave_policy.name,
+ "leave_period": leave_period.name
+ }
+ leave_policy_assignments = create_assignment_for_multiple_employees([self.employee.name], frappe._dict(data))
+
+ leaves_allocated = frappe.db.get_value("Leave Allocation", {
+ "leave_policy_assignment": leave_policy_assignments[0]
+ }, "total_leaves_allocated")
+ self.assertEqual(leaves_allocated, 3)
+
+ # if the daily job is not completed yet, there is another check present
+ # to ensure leave is not already allocated to avoid duplication
+ from erpnext.hr.utils import allocate_earned_leaves
+ allocate_earned_leaves()
+
+ leaves_allocated = frappe.db.get_value("Leave Allocation", {
+ "leave_policy_assignment": leave_policy_assignments[0]
+ }, "total_leaves_allocated")
+ self.assertEqual(leaves_allocated, 3)
+
+ def test_earned_leave_alloc_for_passed_months_with_cf_leaves_based_on_leave_period(self):
+ from erpnext.hr.doctype.leave_allocation.test_leave_allocation import create_leave_allocation
+
+ leave_period, leave_policy = setup_leave_period_and_policy(get_first_day(add_months(getdate(), -2)))
+ # initial leave allocation = 5
+ leave_allocation = create_leave_allocation(employee=self.employee.name, employee_name=self.employee.employee_name, leave_type="Test Earned Leave",
+ from_date=add_months(getdate(), -12), to_date=add_months(getdate(), -3), new_leaves_allocated=5, carry_forward=0)
+ leave_allocation.submit()
+
+ # Case 3: assignment created on the last day of the leave period's latter month with carry forwarding
+ frappe.flags.current_date = get_last_day(add_months(getdate(), -1))
+ data = {
+ "assignment_based_on": "Leave Period",
+ "leave_policy": leave_policy.name,
+ "leave_period": leave_period.name,
+ "carry_forward": 1
+ }
+ # carry forwarded leaves = 5, 3 leaves allocated for passed months
+ leave_policy_assignments = create_assignment_for_multiple_employees([self.employee.name], frappe._dict(data))
+
+ details = frappe.db.get_value("Leave Allocation", {
+ "leave_policy_assignment": leave_policy_assignments[0]
+ }, ["total_leaves_allocated", "new_leaves_allocated", "unused_leaves", "name"], as_dict=True)
+ self.assertEqual(details.new_leaves_allocated, 2)
+ self.assertEqual(details.unused_leaves, 5)
+ self.assertEqual(details.total_leaves_allocated, 7)
+
+ # if the daily job is not completed yet, there is another check present
+ # to ensure leave is not already allocated to avoid duplication
+ from erpnext.hr.utils import is_earned_leave_already_allocated
+ frappe.flags.current_date = get_last_day(getdate())
+
+ allocation = frappe.get_doc("Leave Allocation", details.name)
+ # 1 leave is still pending to be allocated, irrespective of carry forwarded leaves
+ self.assertFalse(is_earned_leave_already_allocated(allocation, leave_policy.leave_policy_details[0].annual_allocation))
+
+ def test_earned_leave_alloc_for_passed_months_based_on_joining_date(self):
+ # tests leave alloc for earned leaves for assignment based on joining date in policy assignment
+ leave_type = create_earned_leave_type("Test Earned Leave")
+ leave_policy = frappe.get_doc({
+ "doctype": "Leave Policy",
+ "title": "Test Leave Policy",
+ "leave_policy_details": [{"leave_type": leave_type.name, "annual_allocation": 12}]
+ }).submit()
+
+ # joining date set to 2 months back
+ self.employee.date_of_joining = get_first_day(add_months(getdate(), -2))
+ self.employee.save()
+
+ # assignment created on the last day of the current month
+ frappe.flags.current_date = get_last_day(getdate())
+ data = {
+ "assignment_based_on": "Joining Date",
+ "leave_policy": leave_policy.name
+ }
+ leave_policy_assignments = create_assignment_for_multiple_employees([self.employee.name], frappe._dict(data))
+ leaves_allocated = frappe.db.get_value("Leave Allocation", {"leave_policy_assignment": leave_policy_assignments[0]},
+ "total_leaves_allocated")
+ effective_from = frappe.db.get_value("Leave Policy Assignment", leave_policy_assignments[0], "effective_from")
+ self.assertEqual(effective_from, self.employee.date_of_joining)
+ self.assertEqual(leaves_allocated, 3)
+
+ # to ensure leave is not already allocated to avoid duplication
+ from erpnext.hr.utils import allocate_earned_leaves
+ frappe.flags.current_date = get_last_day(getdate())
+ allocate_earned_leaves()
+
+ leaves_allocated = frappe.db.get_value("Leave Allocation", {"leave_policy_assignment": leave_policy_assignments[0]},
+ "total_leaves_allocated")
+ self.assertEqual(leaves_allocated, 3)
+
+ def test_grant_leaves_on_doj_for_earned_leaves_based_on_leave_period(self):
+ # tests leave alloc based on leave period for earned leaves with "based on doj" configuration in leave type
+ leave_period, leave_policy = setup_leave_period_and_policy(get_first_day(add_months(getdate(), -2)), based_on_doj=True)
+
+ # joining date set to 2 months back
+ self.employee.date_of_joining = get_first_day(add_months(getdate(), -2))
+ self.employee.save()
+
+ # assignment created on the same day of the current month, should allocate leaves including the current month
+ frappe.flags.current_date = get_first_day(getdate())
+
+ data = {
+ "assignment_based_on": "Leave Period",
+ "leave_policy": leave_policy.name,
+ "leave_period": leave_period.name
+ }
+ leave_policy_assignments = create_assignment_for_multiple_employees([self.employee.name], frappe._dict(data))
+
+ leaves_allocated = frappe.db.get_value("Leave Allocation", {
+ "leave_policy_assignment": leave_policy_assignments[0]
+ }, "total_leaves_allocated")
+ self.assertEqual(leaves_allocated, 3)
+
+ # if the daily job is not completed yet, there is another check present
+ # to ensure leave is not already allocated to avoid duplication
+ from erpnext.hr.utils import allocate_earned_leaves
+ frappe.flags.current_date = get_first_day(getdate())
+ allocate_earned_leaves()
+
+ leaves_allocated = frappe.db.get_value("Leave Allocation", {
+ "leave_policy_assignment": leave_policy_assignments[0]
+ }, "total_leaves_allocated")
+ self.assertEqual(leaves_allocated, 3)
+
+ def test_grant_leaves_on_doj_for_earned_leaves_based_on_joining_date(self):
+ # tests leave alloc based on joining date for earned leaves with "based on doj" configuration in leave type
+ leave_type = create_earned_leave_type("Test Earned Leave", based_on_doj=True)
+ leave_policy = frappe.get_doc({
+ "doctype": "Leave Policy",
+ "title": "Test Leave Policy",
+ "leave_policy_details": [{"leave_type": leave_type.name, "annual_allocation": 12}]
+ }).submit()
+
+ # joining date set to 2 months back
+ # leave should be allocated for current month too since this day is same as the joining day
+ self.employee.date_of_joining = get_first_day(add_months(getdate(), -2))
+ self.employee.save()
+
+ # assignment created on the first day of the current month
+ frappe.flags.current_date = get_first_day(getdate())
+ data = {
+ "assignment_based_on": "Joining Date",
+ "leave_policy": leave_policy.name
+ }
+ leave_policy_assignments = create_assignment_for_multiple_employees([self.employee.name], frappe._dict(data))
+ leaves_allocated = frappe.db.get_value("Leave Allocation", {"leave_policy_assignment": leave_policy_assignments[0]},
+ "total_leaves_allocated")
+ effective_from = frappe.db.get_value("Leave Policy Assignment", leave_policy_assignments[0], "effective_from")
+ self.assertEqual(effective_from, self.employee.date_of_joining)
+ self.assertEqual(leaves_allocated, 3)
+
+ # to ensure leave is not already allocated to avoid duplication
+ from erpnext.hr.utils import allocate_earned_leaves
+ frappe.flags.current_date = get_first_day(getdate())
+ allocate_earned_leaves()
+
+ leaves_allocated = frappe.db.get_value("Leave Allocation", {"leave_policy_assignment": leave_policy_assignments[0]},
+ "total_leaves_allocated")
+ self.assertEqual(leaves_allocated, 3)
+
def tearDown(self):
frappe.db.rollback()
+ frappe.db.set_value("Employee", self.employee.name, "date_of_joining", self.original_doj)
+ frappe.flags.current_date = None
-def create_earned_leave_type(leave_type):
+def create_earned_leave_type(leave_type, based_on_doj=False):
frappe.delete_doc_if_exists("Leave Type", leave_type, force=1)
return frappe.get_doc(dict(
@@ -138,13 +305,15 @@
is_earned_leave=1,
earned_leave_frequency="Monthly",
rounding=0.5,
- max_leaves_allowed=6
+ is_carry_forward=1,
+ based_on_date_of_joining=based_on_doj
)).insert()
-def create_leave_period(name):
+def create_leave_period(name, start_date=None):
frappe.delete_doc_if_exists("Leave Period", name, force=1)
- start_date = get_first_day(getdate())
+ if not start_date:
+ start_date = get_first_day(getdate())
return frappe.get_doc(dict(
name=name,
@@ -153,4 +322,17 @@
to_date=add_months(start_date, 12),
company="_Test Company",
is_active=1
- )).insert()
\ No newline at end of file
+ )).insert()
+
+
+def setup_leave_period_and_policy(start_date, based_on_doj=False):
+ leave_type = create_earned_leave_type("Test Earned Leave", based_on_doj)
+ leave_period = create_leave_period("Test Earned Leave Period",
+ start_date=start_date)
+ leave_policy = frappe.get_doc({
+ "doctype": "Leave Policy",
+ "title": "Test Leave Policy",
+ "leave_policy_details": [{"leave_type": leave_type.name, "annual_allocation": 12}]
+ }).insert()
+
+ return leave_period, leave_policy
\ No newline at end of file
diff --git a/erpnext/hr/doctype/vehicle_log/test_vehicle_log.py b/erpnext/hr/doctype/vehicle_log/test_vehicle_log.py
index acd50f2..abb2887 100644
--- a/erpnext/hr/doctype/vehicle_log/test_vehicle_log.py
+++ b/erpnext/hr/doctype/vehicle_log/test_vehicle_log.py
@@ -82,7 +82,7 @@
"vehicle_value": flt(500000)
})
try:
- vehicle.insert()
+ vehicle.insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
return license_plate
diff --git a/erpnext/hr/utils.py b/erpnext/hr/utils.py
index 0febce1..c174047 100644
--- a/erpnext/hr/utils.py
+++ b/erpnext/hr/utils.py
@@ -237,7 +237,7 @@
create_leave_encashment(leave_allocation=leave_allocation)
-def allocate_earned_leaves():
+def allocate_earned_leaves(ignore_duplicates=False):
'''Allocate earned leaves to Employees'''
e_leave_types = get_earned_leaves()
today = getdate()
@@ -261,13 +261,13 @@
from_date=allocation.from_date
- if e_leave_type.based_on_date_of_joining_date:
+ if e_leave_type.based_on_date_of_joining:
from_date = frappe.db.get_value("Employee", allocation.employee, "date_of_joining")
- if check_effective_date(from_date, today, e_leave_type.earned_leave_frequency, e_leave_type.based_on_date_of_joining_date):
- update_previous_leave_allocation(allocation, annual_allocation, e_leave_type)
+ if check_effective_date(from_date, today, e_leave_type.earned_leave_frequency, e_leave_type.based_on_date_of_joining):
+ update_previous_leave_allocation(allocation, annual_allocation, e_leave_type, ignore_duplicates)
-def update_previous_leave_allocation(allocation, annual_allocation, e_leave_type):
+def update_previous_leave_allocation(allocation, annual_allocation, e_leave_type, ignore_duplicates=False):
earned_leaves = get_monthly_earned_leave(annual_allocation, e_leave_type.earned_leave_frequency, e_leave_type.rounding)
allocation = frappe.get_doc('Leave Allocation', allocation.name)
@@ -277,9 +277,12 @@
new_allocation = e_leave_type.max_leaves_allowed
if new_allocation != allocation.total_leaves_allocated:
- allocation.db_set("total_leaves_allocated", new_allocation, update_modified=False)
today_date = today()
- create_additional_leave_ledger_entry(allocation, earned_leaves, today_date)
+
+ if ignore_duplicates or not is_earned_leave_already_allocated(allocation, annual_allocation):
+ allocation.db_set("total_leaves_allocated", new_allocation, update_modified=False)
+ create_additional_leave_ledger_entry(allocation, earned_leaves, today_date)
+
def get_monthly_earned_leave(annual_leaves, frequency, rounding):
earned_leaves = 0.0
@@ -297,6 +300,28 @@
return earned_leaves
+def is_earned_leave_already_allocated(allocation, annual_allocation):
+ from erpnext.hr.doctype.leave_policy_assignment.leave_policy_assignment import (
+ get_leave_type_details,
+ )
+
+ leave_type_details = get_leave_type_details()
+ date_of_joining = frappe.db.get_value("Employee", allocation.employee, "date_of_joining")
+
+ assignment = frappe.get_doc("Leave Policy Assignment", allocation.leave_policy_assignment)
+ leaves_for_passed_months = assignment.get_leaves_for_passed_months(allocation.leave_type,
+ annual_allocation, leave_type_details, date_of_joining)
+
+ # exclude carry-forwarded leaves while checking for leave allocation for passed months
+ num_allocations = allocation.total_leaves_allocated
+ if allocation.unused_leaves:
+ num_allocations -= allocation.unused_leaves
+
+ if num_allocations >= leaves_for_passed_months:
+ return True
+ return False
+
+
def get_leave_allocations(date, leave_type):
return frappe.db.sql("""select name, employee, from_date, to_date, leave_policy_assignment, leave_policy
from `tabLeave Allocation`
@@ -318,7 +343,7 @@
allocation.unused_leaves = 0
allocation.create_leave_ledger_entry()
-def check_effective_date(from_date, to_date, frequency, based_on_date_of_joining_date):
+def check_effective_date(from_date, to_date, frequency, based_on_date_of_joining):
import calendar
from dateutil import relativedelta
@@ -329,7 +354,7 @@
#last day of month
last_day = calendar.monthrange(to_date.year, to_date.month)[1]
- if (from_date.day == to_date.day and based_on_date_of_joining_date) or (not based_on_date_of_joining_date and to_date.day == last_day):
+ if (from_date.day == to_date.day and based_on_date_of_joining) or (not based_on_date_of_joining and to_date.day == last_day):
if frequency == "Monthly":
return True
elif frequency == "Quarterly" and rd.months % 3:
diff --git a/erpnext/loan_management/doctype/loan_disbursement/loan_disbursement.json b/erpnext/loan_management/doctype/loan_disbursement/loan_disbursement.json
index 7811d56..50926d7 100644
--- a/erpnext/loan_management/doctype/loan_disbursement/loan_disbursement.json
+++ b/erpnext/loan_management/doctype/loan_disbursement/loan_disbursement.json
@@ -14,11 +14,15 @@
"applicant",
"section_break_7",
"disbursement_date",
+ "clearance_date",
"column_break_8",
"disbursed_amount",
"accounting_dimensions_section",
"cost_center",
- "customer_details_section",
+ "accounting_details",
+ "disbursement_account",
+ "column_break_16",
+ "loan_account",
"bank_account",
"disbursement_references_section",
"reference_date",
@@ -107,11 +111,6 @@
"label": "Disbursement Details"
},
{
- "fieldname": "customer_details_section",
- "fieldtype": "Section Break",
- "label": "Customer Details"
- },
- {
"fetch_from": "against_loan.applicant_type",
"fieldname": "applicant_type",
"fieldtype": "Select",
@@ -149,15 +148,48 @@
"fieldname": "reference_number",
"fieldtype": "Data",
"label": "Reference Number"
+ },
+ {
+ "fieldname": "clearance_date",
+ "fieldtype": "Date",
+ "label": "Clearance Date",
+ "no_copy": 1,
+ "read_only": 1
+ },
+ {
+ "fieldname": "accounting_details",
+ "fieldtype": "Section Break",
+ "label": "Accounting Details"
+ },
+ {
+ "fetch_from": "against_loan.disbursement_account",
+ "fieldname": "disbursement_account",
+ "fieldtype": "Link",
+ "label": "Disbursement Account",
+ "options": "Account",
+ "read_only": 1
+ },
+ {
+ "fieldname": "column_break_16",
+ "fieldtype": "Column Break"
+ },
+ {
+ "fetch_from": "against_loan.loan_account",
+ "fieldname": "loan_account",
+ "fieldtype": "Link",
+ "label": "Loan Account",
+ "options": "Account",
+ "read_only": 1
}
],
"index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [],
- "modified": "2021-04-19 18:09:32.175355",
+ "modified": "2022-02-17 18:23:44.157598",
"modified_by": "Administrator",
"module": "Loan Management",
"name": "Loan Disbursement",
+ "naming_rule": "Expression (old style)",
"owner": "Administrator",
"permissions": [
{
@@ -194,5 +226,6 @@
"quick_entry": 1,
"sort_field": "modified",
"sort_order": "DESC",
+ "states": [],
"track_changes": 1
}
\ No newline at end of file
diff --git a/erpnext/loan_management/doctype/loan_disbursement/loan_disbursement.py b/erpnext/loan_management/doctype/loan_disbursement/loan_disbursement.py
index df3aadf..54a03b9 100644
--- a/erpnext/loan_management/doctype/loan_disbursement/loan_disbursement.py
+++ b/erpnext/loan_management/doctype/loan_disbursement/loan_disbursement.py
@@ -42,9 +42,6 @@
if not self.posting_date:
self.posting_date = self.disbursement_date or nowdate()
- if not self.bank_account and self.applicant_type == "Customer":
- self.bank_account = frappe.db.get_value("Customer", self.applicant, "default_bank_account")
-
def validate_disbursal_amount(self):
possible_disbursal_amount = get_disbursal_amount(self.against_loan)
@@ -117,12 +114,11 @@
def make_gl_entries(self, cancel=0, adv_adj=0):
gle_map = []
- loan_details = frappe.get_doc("Loan", self.against_loan)
gle_map.append(
self.get_gl_dict({
- "account": loan_details.loan_account,
- "against": loan_details.disbursement_account,
+ "account": self.loan_account,
+ "against": self.disbursement_account,
"debit": self.disbursed_amount,
"debit_in_account_currency": self.disbursed_amount,
"against_voucher_type": "Loan",
@@ -137,8 +133,8 @@
gle_map.append(
self.get_gl_dict({
- "account": loan_details.disbursement_account,
- "against": loan_details.loan_account,
+ "account": self.disbursement_account,
+ "against": self.loan_account,
"credit": self.disbursed_amount,
"credit_in_account_currency": self.disbursed_amount,
"against_voucher_type": "Loan",
diff --git a/erpnext/loan_management/doctype/loan_interest_accrual/loan_interest_accrual.py b/erpnext/loan_management/doctype/loan_interest_accrual/loan_interest_accrual.py
index 0de073f..1c800a0 100644
--- a/erpnext/loan_management/doctype/loan_interest_accrual/loan_interest_accrual.py
+++ b/erpnext/loan_management/doctype/loan_interest_accrual/loan_interest_accrual.py
@@ -74,39 +74,6 @@
})
)
- if self.payable_principal_amount:
- gle_map.append(
- self.get_gl_dict({
- "account": self.loan_account,
- "party_type": self.applicant_type,
- "party": self.applicant,
- "against": self.interest_income_account,
- "debit": self.payable_principal_amount,
- "debit_in_account_currency": self.interest_amount,
- "against_voucher_type": "Loan",
- "against_voucher": self.loan,
- "remarks": _("Interest accrued from {0} to {1} against loan: {2}").format(
- self.last_accrual_date, self.posting_date, self.loan),
- "cost_center": erpnext.get_default_cost_center(self.company),
- "posting_date": self.posting_date
- })
- )
-
- gle_map.append(
- self.get_gl_dict({
- "account": self.interest_income_account,
- "against": self.loan_account,
- "credit": self.payable_principal_amount,
- "credit_in_account_currency": self.interest_amount,
- "against_voucher_type": "Loan",
- "against_voucher": self.loan,
- "remarks": ("Interest accrued from {0} to {1} against loan: {2}").format(
- self.last_accrual_date, self.posting_date, self.loan),
- "cost_center": erpnext.get_default_cost_center(self.company),
- "posting_date": self.posting_date
- })
- )
-
if gle_map:
make_gl_entries(gle_map, cancel=cancel, adv_adj=adv_adj)
diff --git a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.json b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.json
index 93ef217..480e010 100644
--- a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.json
+++ b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.json
@@ -1,7 +1,7 @@
{
"actions": [],
"autoname": "LM-REP-.####",
- "creation": "2019-09-03 14:44:39.977266",
+ "creation": "2022-01-25 10:30:02.767941",
"doctype": "DocType",
"editable_grid": 1,
"engine": "InnoDB",
@@ -13,6 +13,7 @@
"column_break_3",
"company",
"posting_date",
+ "clearance_date",
"rate_of_interest",
"payroll_payable_account",
"is_term_loan",
@@ -37,7 +38,12 @@
"total_penalty_paid",
"total_interest_paid",
"repayment_details",
- "amended_from"
+ "amended_from",
+ "accounting_details_section",
+ "payment_account",
+ "penalty_income_account",
+ "column_break_36",
+ "loan_account"
],
"fields": [
{
@@ -260,12 +266,52 @@
"fieldname": "repay_from_salary",
"fieldtype": "Check",
"label": "Repay From Salary"
+ },
+ {
+ "fieldname": "clearance_date",
+ "fieldtype": "Date",
+ "label": "Clearance Date",
+ "no_copy": 1,
+ "read_only": 1
+ },
+ {
+ "fieldname": "accounting_details_section",
+ "fieldtype": "Section Break",
+ "label": "Accounting Details"
+ },
+ {
+ "fetch_from": "against_loan.payment_account",
+ "fieldname": "payment_account",
+ "fieldtype": "Link",
+ "label": "Repayment Account",
+ "options": "Account",
+ "read_only": 1
+ },
+ {
+ "fieldname": "column_break_36",
+ "fieldtype": "Column Break"
+ },
+ {
+ "fetch_from": "against_loan.loan_account",
+ "fieldname": "loan_account",
+ "fieldtype": "Link",
+ "label": "Loan Account",
+ "options": "Account",
+ "read_only": 1
+ },
+ {
+ "fetch_from": "against_loan.penalty_income_account",
+ "fieldname": "penalty_income_account",
+ "fieldtype": "Link",
+ "hidden": 1,
+ "label": "Penalty Income Account",
+ "options": "Account"
}
],
"index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [],
- "modified": "2022-01-06 01:51:06.707782",
+ "modified": "2022-02-18 19:10:07.742298",
"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 acf3a65..67c2b1e 100644
--- a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
+++ b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
@@ -310,7 +310,6 @@
def make_gl_entries(self, cancel=0, adv_adj=0):
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,
@@ -323,13 +322,13 @@
if self.repay_from_salary:
payment_account = self.payroll_payable_account
else:
- payment_account = loan_details.payment_account
+ payment_account = self.payment_account
if self.total_penalty_paid:
gle_map.append(
self.get_gl_dict({
- "account": loan_details.loan_account,
- "against": loan_details.payment_account,
+ "account": self.loan_account,
+ "against": payment_account,
"debit": self.total_penalty_paid,
"debit_in_account_currency": self.total_penalty_paid,
"against_voucher_type": "Loan",
@@ -344,8 +343,8 @@
gle_map.append(
self.get_gl_dict({
- "account": loan_details.penalty_income_account,
- "against": payment_account,
+ "account": self.penalty_income_account,
+ "against": self.loan_account,
"credit": self.total_penalty_paid,
"credit_in_account_currency": self.total_penalty_paid,
"against_voucher_type": "Loan",
@@ -359,23 +358,24 @@
gle_map.append(
self.get_gl_dict({
"account": payment_account,
- "against": loan_details.loan_account + ", " + loan_details.interest_income_account
- + ", " + loan_details.penalty_income_account,
+ "against": self.loan_account + ", " + self.penalty_income_account,
"debit": self.amount_paid,
"debit_in_account_currency": self.amount_paid,
"against_voucher_type": "Loan",
"against_voucher": self.against_loan,
"remarks": remarks,
"cost_center": self.cost_center,
- "posting_date": getdate(self.posting_date)
+ "posting_date": getdate(self.posting_date),
+ "party_type": self.applicant_type if self.repay_from_salary else '',
+ "party": self.applicant if self.repay_from_salary else ''
})
)
gle_map.append(
self.get_gl_dict({
- "account": loan_details.loan_account,
- "party_type": loan_details.applicant_type,
- "party": loan_details.applicant,
+ "account": self.loan_account,
+ "party_type": self.applicant_type,
+ "party": self.applicant,
"against": payment_account,
"credit": self.amount_paid,
"credit_in_account_currency": self.amount_paid,
diff --git a/erpnext/manufacturing/doctype/blanket_order/test_blanket_order.py b/erpnext/manufacturing/doctype/blanket_order/test_blanket_order.py
index eff2344..d4d337d 100644
--- a/erpnext/manufacturing/doctype/blanket_order/test_blanket_order.py
+++ b/erpnext/manufacturing/doctype/blanket_order/test_blanket_order.py
@@ -1,15 +1,15 @@
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import add_months, today
from erpnext import get_company_currency
-from erpnext.tests.utils import ERPNextTestCase
from .blanket_order import make_order
-class TestBlanketOrder(ERPNextTestCase):
+class TestBlanketOrder(FrappeTestCase):
def setUp(self):
frappe.flags.args = frappe._dict()
diff --git a/erpnext/manufacturing/doctype/bom/bom.py b/erpnext/manufacturing/doctype/bom/bom.py
index d640f3f..37d2b9f 100644
--- a/erpnext/manufacturing/doctype/bom/bom.py
+++ b/erpnext/manufacturing/doctype/bom/bom.py
@@ -918,7 +918,7 @@
frappe.throw(_("BOM {0} does not belong to Item {1}").format(bom_no, item))
@frappe.whitelist()
-def get_children(doctype, parent=None, is_root=False, **filters):
+def get_children(parent=None, is_root=False, **filters):
if not parent or parent=="BOM":
frappe.msgprint(_('Please select a BOM'))
return
diff --git a/erpnext/manufacturing/doctype/bom/test_bom.py b/erpnext/manufacturing/doctype/bom/test_bom.py
index 53437c8..3cc91b3 100644
--- a/erpnext/manufacturing/doctype/bom/test_bom.py
+++ b/erpnext/manufacturing/doctype/bom/test_bom.py
@@ -7,6 +7,7 @@
import frappe
from frappe.test_runner import make_test_records
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import cstr, flt
from erpnext.buying.doctype.purchase_order.test_purchase_order import create_purchase_order
@@ -17,11 +18,10 @@
create_stock_reconciliation,
)
from erpnext.tests.test_subcontracting import set_backflush_based_on
-from erpnext.tests.utils import ERPNextTestCase
test_records = frappe.get_test_records('BOM')
-class TestBOM(ERPNextTestCase):
+class TestBOM(FrappeTestCase):
def setUp(self):
if not frappe.get_value('Item', '_Test Item'):
make_test_records('Item')
diff --git a/erpnext/manufacturing/doctype/bom_update_tool/test_bom_update_tool.py b/erpnext/manufacturing/doctype/bom_update_tool/test_bom_update_tool.py
index 12576cb..b4c625d 100644
--- a/erpnext/manufacturing/doctype/bom_update_tool/test_bom_update_tool.py
+++ b/erpnext/manufacturing/doctype/bom_update_tool/test_bom_update_tool.py
@@ -2,15 +2,15 @@
# License: GNU General Public License v3. See license.txt
import frappe
+from frappe.tests.utils import FrappeTestCase
from erpnext.manufacturing.doctype.bom_update_tool.bom_update_tool import update_cost
from erpnext.manufacturing.doctype.production_plan.test_production_plan import make_bom
from erpnext.stock.doctype.item.test_item import create_item
-from erpnext.tests.utils import ERPNextTestCase
test_records = frappe.get_test_records('BOM')
-class TestBOMUpdateTool(ERPNextTestCase):
+class TestBOMUpdateTool(FrappeTestCase):
def test_replace_bom(self):
current_bom = "BOM-_Test Item Home Desktop Manufactured-001"
diff --git a/erpnext/manufacturing/doctype/job_card/job_card.py b/erpnext/manufacturing/doctype/job_card/job_card.py
index 8d00019..9f4ace2 100644
--- a/erpnext/manufacturing/doctype/job_card/job_card.py
+++ b/erpnext/manufacturing/doctype/job_card/job_card.py
@@ -62,7 +62,7 @@
if self.get('time_logs'):
for d in self.get('time_logs'):
- if get_datetime(d.from_time) > get_datetime(d.to_time):
+ if d.to_time and get_datetime(d.from_time) > get_datetime(d.to_time):
frappe.throw(_("Row {0}: From time must be less than to time").format(d.idx))
data = self.get_overlap_for(d)
diff --git a/erpnext/manufacturing/doctype/job_card/test_job_card.py b/erpnext/manufacturing/doctype/job_card/test_job_card.py
index bb5004b..33425d2 100644
--- a/erpnext/manufacturing/doctype/job_card/test_job_card.py
+++ b/erpnext/manufacturing/doctype/job_card/test_job_card.py
@@ -2,6 +2,7 @@
# See license.txt
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import random_string
from erpnext.manufacturing.doctype.job_card.job_card import OperationMismatchError, OverlapError
@@ -11,10 +12,9 @@
from erpnext.manufacturing.doctype.work_order.test_work_order import make_wo_order_test_record
from erpnext.manufacturing.doctype.workstation.test_workstation import make_workstation
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
-from erpnext.tests.utils import ERPNextTestCase
-class TestJobCard(ERPNextTestCase):
+class TestJobCard(FrappeTestCase):
def setUp(self):
make_bom_for_jc_tests()
diff --git a/erpnext/manufacturing/doctype/operation/operation_dashboard.py b/erpnext/manufacturing/doctype/operation/operation_dashboard.py
index 4fbcf49..9f7efa2 100644
--- a/erpnext/manufacturing/doctype/operation/operation_dashboard.py
+++ b/erpnext/manufacturing/doctype/operation/operation_dashboard.py
@@ -7,7 +7,7 @@
'transactions': [
{
'label': _('Manufacture'),
- 'items': ['BOM', 'Work Order', 'Job Card', 'Timesheet']
+ 'items': ['BOM', 'Work Order', 'Job Card']
}
]
}
diff --git a/erpnext/manufacturing/doctype/production_plan/production_plan.js b/erpnext/manufacturing/doctype/production_plan/production_plan.js
index 0babf87..e8759f5 100644
--- a/erpnext/manufacturing/doctype/production_plan/production_plan.js
+++ b/erpnext/manufacturing/doctype/production_plan/production_plan.js
@@ -49,7 +49,7 @@
if (d.item_code) {
return {
query: "erpnext.controllers.queries.bom",
- filters:{'item': cstr(d.item_code)}
+ filters:{'item': cstr(d.item_code), 'docstatus': 1}
}
} else frappe.msgprint(__("Please enter Item first"));
}
@@ -232,7 +232,7 @@
});
},
combine_items: function (frm) {
- frm.clear_table('prod_plan_references');
+ frm.clear_table("prod_plan_references");
frappe.call({
method: "get_items",
@@ -247,6 +247,13 @@
});
},
+ combine_sub_items: (frm) => {
+ if (frm.doc.sub_assembly_items.length > 0) {
+ frm.clear_table("sub_assembly_items");
+ frm.trigger("get_sub_assembly_items");
+ }
+ },
+
get_sub_assembly_items: function(frm) {
frm.dirty();
diff --git a/erpnext/manufacturing/doctype/production_plan/production_plan.json b/erpnext/manufacturing/doctype/production_plan/production_plan.json
index 56cf2b4..3bfb764 100644
--- a/erpnext/manufacturing/doctype/production_plan/production_plan.json
+++ b/erpnext/manufacturing/doctype/production_plan/production_plan.json
@@ -36,6 +36,7 @@
"prod_plan_references",
"section_break_24",
"get_sub_assembly_items",
+ "combine_sub_items",
"sub_assembly_items",
"material_request_planning",
"include_non_stock_items",
@@ -340,7 +341,6 @@
{
"fieldname": "prod_plan_references",
"fieldtype": "Table",
- "hidden": 1,
"label": "Production Plan Item Reference",
"options": "Production Plan Item Reference"
},
@@ -370,16 +370,23 @@
"fieldname": "to_delivery_date",
"fieldtype": "Date",
"label": "To Delivery Date"
+ },
+ {
+ "default": "0",
+ "fieldname": "combine_sub_items",
+ "fieldtype": "Check",
+ "label": "Consolidate Sub Assembly Items"
}
],
"icon": "fa fa-calendar",
"index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [],
- "modified": "2021-09-06 18:35:59.642232",
+ "modified": "2022-02-23 17:16:10.629378",
"modified_by": "Administrator",
"module": "Manufacturing",
"name": "Production Plan",
+ "naming_rule": "By \"Naming Series\" field",
"owner": "Administrator",
"permissions": [
{
diff --git a/erpnext/manufacturing/doctype/production_plan/production_plan.py b/erpnext/manufacturing/doctype/production_plan/production_plan.py
index 4290ca3..48cd753 100644
--- a/erpnext/manufacturing/doctype/production_plan/production_plan.py
+++ b/erpnext/manufacturing/doctype/production_plan/production_plan.py
@@ -21,16 +21,32 @@
)
from frappe.utils.csvutils import build_csv_response
-from erpnext.manufacturing.doctype.bom.bom import get_children, validate_bom_no
+from erpnext.manufacturing.doctype.bom.bom import get_children as get_bom_children
+from erpnext.manufacturing.doctype.bom.bom import validate_bom_no
from erpnext.manufacturing.doctype.work_order.work_order import get_item_details
from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults
class ProductionPlan(Document):
def validate(self):
+ self.set_pending_qty_in_row_without_reference()
self.calculate_total_planned_qty()
self.set_status()
+ def set_pending_qty_in_row_without_reference(self):
+ "Set Pending Qty in independent rows (not from SO or MR)."
+ if self.docstatus > 0: # set only to initialise value before submit
+ return
+
+ for item in self.po_items:
+ if not item.get("sales_order") or not item.get("material_request"):
+ item.pending_qty = item.planned_qty
+
+ def calculate_total_planned_qty(self):
+ self.total_planned_qty = 0
+ for d in self.po_items:
+ self.total_planned_qty += flt(d.planned_qty)
+
def validate_data(self):
for d in self.get('po_items'):
if not d.bom_no:
@@ -263,11 +279,6 @@
'qty': so_detail['qty']
})
- def calculate_total_planned_qty(self):
- self.total_planned_qty = 0
- for d in self.po_items:
- self.total_planned_qty += flt(d.planned_qty)
-
def calculate_total_produced_qty(self):
self.total_produced_qty = 0
for d in self.po_items:
@@ -275,10 +286,11 @@
self.db_set("total_produced_qty", self.total_produced_qty, update_modified=False)
- def update_produced_qty(self, produced_qty, production_plan_item):
+ def update_produced_pending_qty(self, produced_qty, production_plan_item):
for data in self.po_items:
if data.name == production_plan_item:
data.produced_qty = produced_qty
+ data.pending_qty = flt(data.planned_qty - produced_qty)
data.db_update()
self.calculate_total_produced_qty()
@@ -308,7 +320,7 @@
if self.total_produced_qty > 0:
self.status = "In Process"
- if self.check_have_work_orders_completed():
+ if self.all_items_completed():
self.status = "Completed"
if self.status != 'Completed':
@@ -341,6 +353,7 @@
def get_production_items(self):
item_dict = {}
+
for d in self.po_items:
item_details = {
"production_item" : d.item_code,
@@ -357,12 +370,12 @@
"production_plan" : self.name,
"production_plan_item" : d.name,
"product_bundle_item" : d.product_bundle_item,
- "planned_start_date" : d.planned_start_date
+ "planned_start_date" : d.planned_start_date,
+ "project" : self.project
}
- item_details.update({
- "project": self.project or frappe.db.get_value("Sales Order", d.sales_order, "project")
- })
+ if not item_details['project'] and d.sales_order:
+ item_details['project'] = frappe.get_cached_value("Sales Order", d.sales_order, "project")
if self.get_items_from == "Material Request":
item_details.update({
@@ -380,39 +393,59 @@
@frappe.whitelist()
def make_work_order(self):
+ from erpnext.manufacturing.doctype.work_order.work_order import get_default_warehouse
+
wo_list, po_list = [], []
subcontracted_po = {}
+ default_warehouses = get_default_warehouse()
- self.validate_data()
- self.make_work_order_for_finished_goods(wo_list)
- self.make_work_order_for_subassembly_items(wo_list, subcontracted_po)
+ self.make_work_order_for_finished_goods(wo_list, default_warehouses)
+ self.make_work_order_for_subassembly_items(wo_list, subcontracted_po, default_warehouses)
self.make_subcontracted_purchase_order(subcontracted_po, po_list)
self.show_list_created_message('Work Order', wo_list)
self.show_list_created_message('Purchase Order', po_list)
- def make_work_order_for_finished_goods(self, wo_list):
+ def make_work_order_for_finished_goods(self, wo_list, default_warehouses):
items_data = self.get_production_items()
for key, item in items_data.items():
if self.sub_assembly_items:
item['use_multi_level_bom'] = 0
+ set_default_warehouses(item, default_warehouses)
work_order = self.create_work_order(item)
if work_order:
wo_list.append(work_order)
- def make_work_order_for_subassembly_items(self, wo_list, subcontracted_po):
+ def make_work_order_for_subassembly_items(self, wo_list, subcontracted_po, default_warehouses):
for row in self.sub_assembly_items:
if row.type_of_manufacturing == 'Subcontract':
subcontracted_po.setdefault(row.supplier, []).append(row)
continue
- args = {}
- self.prepare_args_for_sub_assembly_items(row, args)
- work_order = self.create_work_order(args)
+ work_order_data = {
+ 'wip_warehouse': default_warehouses.get('wip_warehouse'),
+ 'fg_warehouse': default_warehouses.get('fg_warehouse')
+ }
+
+ self.prepare_data_for_sub_assembly_items(row, work_order_data)
+ work_order = self.create_work_order(work_order_data)
if work_order:
wo_list.append(work_order)
+ def prepare_data_for_sub_assembly_items(self, row, wo_data):
+ for field in ["production_item", "item_name", "qty", "fg_warehouse",
+ "description", "bom_no", "stock_uom", "bom_level",
+ "production_plan_item", "schedule_date"]:
+ if row.get(field):
+ wo_data[field] = row.get(field)
+
+ wo_data.update({
+ "use_multi_level_bom": 0,
+ "production_plan": self.name,
+ "production_plan_sub_assembly_item": row.name
+ })
+
def make_subcontracted_purchase_order(self, subcontracted_po, purchase_orders):
if not subcontracted_po:
return
@@ -423,7 +456,7 @@
po.schedule_date = getdate(po_list[0].schedule_date) if po_list[0].schedule_date else nowdate()
po.is_subcontracted = 'Yes'
for row in po_list:
- args = {
+ po_data = {
'item_code': row.production_item,
'warehouse': row.fg_warehouse,
'production_plan_sub_assembly_item': row.name,
@@ -433,9 +466,9 @@
for field in ['schedule_date', 'qty', 'uom', 'stock_uom', 'item_name',
'description', 'production_plan_item']:
- args[field] = row.get(field)
+ po_data[field] = row.get(field)
- po.append('items', args)
+ po.append('items', po_data)
po.set_missing_values()
po.flags.ignore_mandatory = True
@@ -452,24 +485,9 @@
doc_list = [get_link_to_form(doctype, p) for p in doc_list]
msgprint(_("{0} created").format(comma_and(doc_list)))
- def prepare_args_for_sub_assembly_items(self, row, args):
- for field in ["production_item", "item_name", "qty", "fg_warehouse",
- "description", "bom_no", "stock_uom", "bom_level",
- "production_plan_item", "schedule_date"]:
- args[field] = row.get(field)
-
- args.update({
- "use_multi_level_bom": 0,
- "production_plan": self.name,
- "production_plan_sub_assembly_item": row.name
- })
-
def create_work_order(self, item):
- from erpnext.manufacturing.doctype.work_order.work_order import (
- OverProductionError,
- get_default_warehouse,
- )
- warehouse = get_default_warehouse()
+ from erpnext.manufacturing.doctype.work_order.work_order import OverProductionError
+
wo = frappe.new_doc("Work Order")
wo.update(item)
wo.planned_start_date = item.get('planned_start_date') or item.get('schedule_date')
@@ -478,11 +496,11 @@
wo.fg_warehouse = item.get("warehouse")
wo.set_work_order_operations()
+ wo.set_required_items()
- if not wo.fg_warehouse:
- wo.fg_warehouse = warehouse.get('fg_warehouse')
try:
wo.flags.ignore_mandatory = True
+ wo.flags.ignore_validate = True
wo.insert()
return wo.name
except OverProductionError:
@@ -553,17 +571,28 @@
@frappe.whitelist()
def get_sub_assembly_items(self, manufacturing_type=None):
+ "Fetch sub assembly items and optionally combine them."
self.sub_assembly_items = []
+ sub_assembly_items_store = [] # temporary store to process all subassembly items
+
for row in self.po_items:
bom_data = []
get_sub_assembly_items(row.bom_no, bom_data, row.planned_qty)
self.set_sub_assembly_items_based_on_level(row, bom_data, manufacturing_type)
+ sub_assembly_items_store.extend(bom_data)
- self.sub_assembly_items.sort(key= lambda d: d.bom_level, reverse=True)
- for idx, row in enumerate(self.sub_assembly_items, start=1):
- row.idx = idx
+ if self.combine_sub_items:
+ # Combine subassembly items
+ sub_assembly_items_store = self.combine_subassembly_items(sub_assembly_items_store)
+
+ sub_assembly_items_store.sort(key= lambda d: d.bom_level, reverse=True) # sort by bom level
+
+ for idx, row in enumerate(sub_assembly_items_store):
+ row.idx = idx + 1
+ self.append("sub_assembly_items", row)
def set_sub_assembly_items_based_on_level(self, row, bom_data, manufacturing_type=None):
+ "Modify bom_data, set additional details."
for data in bom_data:
data.qty = data.stock_qty
data.production_plan_item = row.name
@@ -572,23 +601,59 @@
data.type_of_manufacturing = manufacturing_type or ("Subcontract" if data.is_sub_contracted_item
else "In House")
- self.append("sub_assembly_items", data)
+ def combine_subassembly_items(self, sub_assembly_items_store):
+ "Aggregate if same: Item, Warehouse, Inhouse/Outhouse Manu.g, BOM No."
+ key_wise_data = {}
+ for row in sub_assembly_items_store:
+ key = (
+ row.get("production_item"), row.get("fg_warehouse"),
+ row.get("bom_no"), row.get("type_of_manufacturing")
+ )
+ if key not in key_wise_data:
+ # intialise (item, wh, bom no, man.g type) wise dict
+ key_wise_data[key] = row
+ continue
- def check_have_work_orders_completed(self):
- wo_status = frappe.db.get_list(
+ existing_row = key_wise_data[key]
+ if existing_row:
+ # if row with same (item, wh, bom no, man.g type) key, merge
+ existing_row.qty += flt(row.qty)
+ existing_row.stock_qty += flt(row.stock_qty)
+ existing_row.bom_level = max(existing_row.bom_level, row.bom_level)
+ continue
+ else:
+ # add row with key
+ key_wise_data[key] = row
+
+ sub_assembly_items_store = [key_wise_data[key] for key in key_wise_data] # unpack into single level list
+ return sub_assembly_items_store
+
+ def all_items_completed(self):
+ all_items_produced = all(flt(d.planned_qty) - flt(d.produced_qty) < 0.000001
+ for d in self.po_items)
+ if not all_items_produced:
+ return False
+
+ wo_status = frappe.get_all(
"Work Order",
- filters={"production_plan": self.name},
+ filters={
+ "production_plan": self.name,
+ "status": ("not in", ["Closed", "Stopped"]),
+ "docstatus": ("<", 2),
+ },
fields="status",
- pluck="status"
+ pluck="status",
)
- return all(s == "Completed" for s in wo_status)
+ all_work_orders_completed = all(s == "Completed" for s in wo_status)
+ return all_work_orders_completed
@frappe.whitelist()
def download_raw_materials(doc, warehouses=None):
if isinstance(doc, str):
doc = frappe._dict(json.loads(doc))
- item_list = [['Item Code', 'Description', 'Stock UOM', 'Warehouse', 'Required Qty as per BOM',
+ item_list = [['Item Code', 'Item Name', 'Description',
+ 'Stock UOM', 'Warehouse', 'Required Qty as per BOM',
'Projected Qty', 'Available Qty In Hand', 'Ordered Qty', 'Planned Qty',
'Reserved Qty for Production', 'Safety Stock', 'Required Qty']]
@@ -597,7 +662,8 @@
items = get_items_for_material_requests(doc, warehouses=warehouses, get_parent_warehouse_data=True)
for d in items:
- item_list.append([d.get('item_code'), d.get('description'), d.get('stock_uom'), d.get('warehouse'),
+ item_list.append([d.get('item_code'), d.get('item_name'),
+ d.get('description'), d.get('stock_uom'), d.get('warehouse'),
d.get('required_bom_qty'), d.get('projected_qty'), d.get('actual_qty'), d.get('ordered_qty'),
d.get('planned_qty'), d.get('reserved_qty_for_production'), d.get('safety_stock'), d.get('quantity')])
@@ -1002,7 +1068,7 @@
}
def get_sub_assembly_items(bom_no, bom_data, to_produce_qty, indent=0):
- data = get_children('BOM', parent = bom_no)
+ data = get_bom_children(parent=bom_no)
for d in data:
if d.expandable:
parent_item_code = frappe.get_cached_value("BOM", bom_no, "item")
@@ -1023,3 +1089,8 @@
if d.value:
get_sub_assembly_items(d.value, bom_data, stock_qty, indent=indent+1)
+
+def set_default_warehouses(row, default_warehouses):
+ for field in ['wip_warehouse', 'fg_warehouse']:
+ if not row.get(field):
+ row[field] = default_warehouses.get(field)
diff --git a/erpnext/manufacturing/doctype/production_plan/test_production_plan.py b/erpnext/manufacturing/doctype/production_plan/test_production_plan.py
index 276e708..eeab788 100644
--- a/erpnext/manufacturing/doctype/production_plan/test_production_plan.py
+++ b/erpnext/manufacturing/doctype/production_plan/test_production_plan.py
@@ -1,6 +1,7 @@
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import add_to_date, flt, now_datetime, nowdate
from erpnext.controllers.item_variant import create_variant
@@ -9,15 +10,16 @@
get_sales_orders,
get_warehouse_list,
)
+from erpnext.manufacturing.doctype.work_order.work_order import OverProductionError
from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
from erpnext.stock.doctype.item.test_item import create_item
+from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
from erpnext.stock.doctype.stock_reconciliation.test_stock_reconciliation import (
create_stock_reconciliation,
)
-from erpnext.tests.utils import ERPNextTestCase
-class TestProductionPlan(ERPNextTestCase):
+class TestProductionPlan(FrappeTestCase):
def setUp(self):
for item in ['Test Production Item 1', 'Subassembly Item 1',
'Raw Material Item 1', 'Raw Material Item 2']:
@@ -36,15 +38,24 @@
if not frappe.db.get_value('BOM', {'item': item}):
make_bom(item = item, raw_materials = raw_materials)
- def test_production_plan(self):
+ def tearDown(self) -> None:
+ frappe.db.rollback()
+
+ def test_production_plan_mr_creation(self):
+ "Test if MRs are created for unavailable raw materials."
pln = create_production_plan(item_code='Test Production Item 1')
self.assertTrue(len(pln.mr_items), 2)
- pln.make_material_request()
- pln = frappe.get_doc('Production Plan', pln.name)
+ pln.make_material_request()
+ pln.reload()
self.assertTrue(pln.status, 'Material Requested')
- material_requests = frappe.get_all('Material Request Item', fields = ['distinct parent'],
- filters = {'production_plan': pln.name}, as_list=1)
+
+ material_requests = frappe.get_all(
+ 'Material Request Item',
+ fields = ['distinct parent'],
+ filters = {'production_plan': pln.name},
+ as_list=1
+ )
self.assertTrue(len(material_requests), 2)
@@ -66,28 +77,43 @@
pln.cancel()
def test_production_plan_start_date(self):
+ "Test if Work Order has same Planned Start Date as Prod Plan."
planned_date = add_to_date(date=None, days=3)
- plan = create_production_plan(item_code='Test Production Item 1', planned_start_date=planned_date)
+ plan = create_production_plan(
+ item_code='Test Production Item 1',
+ planned_start_date=planned_date
+ )
plan.make_work_order()
- work_orders = frappe.get_all('Work Order', fields = ['name', 'planned_start_date'],
- filters = {'production_plan': plan.name})
+ work_orders = frappe.get_all(
+ 'Work Order',
+ fields = ['name', 'planned_start_date'],
+ filters = {'production_plan': plan.name}
+ )
self.assertEqual(work_orders[0].planned_start_date, planned_date)
for wo in work_orders:
frappe.delete_doc('Work Order', wo.name)
- frappe.get_doc('Production Plan', plan.name).cancel()
+ plan.reload()
+ plan.cancel()
def test_production_plan_for_existing_ordered_qty(self):
+ """
+ - Enable 'ignore_existing_ordered_qty'.
+ - Test if MR Planning table pulls Raw Material Qty even if it is in stock.
+ """
sr1 = create_stock_reconciliation(item_code="Raw Material Item 1",
target="_Test Warehouse - _TC", qty=1, rate=110)
sr2 = create_stock_reconciliation(item_code="Raw Material Item 2",
target="_Test Warehouse - _TC", qty=1, rate=120)
- pln = create_production_plan(item_code='Test Production Item 1', ignore_existing_ordered_qty=0)
- self.assertTrue(len(pln.mr_items), 1)
+ pln = create_production_plan(
+ item_code='Test Production Item 1',
+ ignore_existing_ordered_qty=1
+ )
+ self.assertTrue(len(pln.mr_items))
self.assertTrue(flt(pln.mr_items[0].quantity), 1.0)
sr1.cancel()
@@ -95,30 +121,47 @@
pln.cancel()
def test_production_plan_with_non_stock_item(self):
- pln = create_production_plan(item_code='Test Production Item 1', include_non_stock_items=0)
+ "Test if MR Planning table includes Non Stock RM."
+ pln = create_production_plan(
+ item_code='Test Production Item 1',
+ include_non_stock_items=1
+ )
self.assertTrue(len(pln.mr_items), 3)
pln.cancel()
def test_production_plan_without_multi_level(self):
- pln = create_production_plan(item_code='Test Production Item 1', use_multi_level_bom=0)
+ "Test MR Planning table for non exploded BOM."
+ pln = create_production_plan(
+ item_code='Test Production Item 1',
+ use_multi_level_bom=0
+ )
self.assertTrue(len(pln.mr_items), 2)
pln.cancel()
def test_production_plan_without_multi_level_for_existing_ordered_qty(self):
+ """
+ - Disable 'ignore_existing_ordered_qty'.
+ - Test if MR Planning table avoids pulling Raw Material Qty as it is in stock for
+ non exploded BOM.
+ """
sr1 = create_stock_reconciliation(item_code="Raw Material Item 1",
target="_Test Warehouse - _TC", qty=1, rate=130)
sr2 = create_stock_reconciliation(item_code="Subassembly Item 1",
target="_Test Warehouse - _TC", qty=1, rate=140)
- pln = create_production_plan(item_code='Test Production Item 1',
- use_multi_level_bom=0, ignore_existing_ordered_qty=0)
- self.assertTrue(len(pln.mr_items), 0)
+ pln = create_production_plan(
+ item_code='Test Production Item 1',
+ use_multi_level_bom=0,
+ ignore_existing_ordered_qty=0
+ )
+ self.assertFalse(len(pln.mr_items))
sr1.cancel()
sr2.cancel()
pln.cancel()
def test_production_plan_sales_orders(self):
+ "Test if previously fulfilled SO (with WO) is pulled into Prod Plan."
item = 'Test Production Item 1'
so = make_sales_order(item_code=item, qty=1)
sales_order = so.name
@@ -166,24 +209,25 @@
self.assertEqual(sales_orders, [])
def test_production_plan_combine_items(self):
+ "Test combining FG items in Production Plan."
item = 'Test Production Item 1'
- so = make_sales_order(item_code=item, qty=1)
+ so1 = make_sales_order(item_code=item, qty=1)
pln = frappe.new_doc('Production Plan')
- pln.company = so.company
+ pln.company = so1.company
pln.get_items_from = 'Sales Order'
pln.append('sales_orders', {
- 'sales_order': so.name,
- 'sales_order_date': so.transaction_date,
- 'customer': so.customer,
- 'grand_total': so.grand_total
+ 'sales_order': so1.name,
+ 'sales_order_date': so1.transaction_date,
+ 'customer': so1.customer,
+ 'grand_total': so1.grand_total
})
- so = make_sales_order(item_code=item, qty=2)
+ so2 = make_sales_order(item_code=item, qty=2)
pln.append('sales_orders', {
- 'sales_order': so.name,
- 'sales_order_date': so.transaction_date,
- 'customer': so.customer,
- 'grand_total': so.grand_total
+ 'sales_order': so2.name,
+ 'sales_order_date': so2.transaction_date,
+ 'customer': so2.customer,
+ 'grand_total': so2.grand_total
})
pln.combine_items = 1
pln.get_items()
@@ -214,28 +258,82 @@
so_wo_qty = frappe.db.get_value('Sales Order Item', so_item, 'work_order_qty')
self.assertEqual(so_wo_qty, 0.0)
- latest_plan = frappe.get_doc('Production Plan', pln.name)
- latest_plan.cancel()
+ pln.reload()
+ pln.cancel()
+
+ def test_production_plan_combine_subassembly(self):
+ """
+ Test combining Sub assembly items belonging to the same BOM in Prod Plan.
+ 1) Red-Car -> Wheel (sub assembly) > BOM-WHEEL-001
+ 2) Green-Car -> Wheel (sub assembly) > BOM-WHEEL-001
+ """
+ from erpnext.manufacturing.doctype.bom.test_bom import create_nested_bom
+
+ bom_tree_1 = {
+ "Red-Car": {"Wheel": {"Rubber": {}}}
+ }
+ bom_tree_2 = {
+ "Green-Car": {"Wheel": {"Rubber": {}}}
+ }
+
+ parent_bom_1 = create_nested_bom(bom_tree_1, prefix="")
+ parent_bom_2 = create_nested_bom(bom_tree_2, prefix="")
+
+ # make sure both boms use same subassembly bom
+ subassembly_bom = parent_bom_1.items[0].bom_no
+ frappe.db.set_value("BOM Item", parent_bom_2.items[0].name, "bom_no", subassembly_bom)
+
+ plan = create_production_plan(item_code="Red-Car", use_multi_level_bom=1, do_not_save=True)
+ plan.append("po_items", { # Add Green-Car to Prod Plan
+ 'use_multi_level_bom': 1,
+ 'item_code': "Green-Car",
+ 'bom_no': frappe.db.get_value('Item', "Green-Car", 'default_bom'),
+ 'planned_qty': 1,
+ 'planned_start_date': now_datetime()
+ })
+ plan.get_sub_assembly_items()
+ self.assertTrue(len(plan.sub_assembly_items), 2)
+
+ plan.combine_sub_items = 1
+ plan.get_sub_assembly_items()
+
+ self.assertTrue(len(plan.sub_assembly_items), 1) # check if sub-assembly items merged
+ self.assertEqual(plan.sub_assembly_items[0].qty, 2.0)
+ self.assertEqual(plan.sub_assembly_items[0].stock_qty, 2.0)
+
+ # change warehouse in one row, sub-assemblies should not merge
+ plan.po_items[0].warehouse = "Finished Goods - _TC"
+ plan.get_sub_assembly_items()
+ self.assertTrue(len(plan.sub_assembly_items), 2)
def test_pp_to_mr_customer_provided(self):
- #Material Request from Production Plan for Customer Provided
+ " Test Material Request from Production Plan for Customer Provided Item."
create_item('CUST-0987', is_customer_provided_item = 1, customer = '_Test Customer', is_purchase_item = 0)
create_item('Production Item CUST')
+
for item, raw_materials in {'Production Item CUST': ['Raw Material Item 1', 'CUST-0987']}.items():
if not frappe.db.get_value('BOM', {'item': item}):
make_bom(item = item, raw_materials = raw_materials)
production_plan = create_production_plan(item_code = 'Production Item CUST')
production_plan.make_material_request()
- material_request = frappe.db.get_value('Material Request Item', {'production_plan': production_plan.name, 'item_code': 'CUST-0987'}, 'parent')
+
+ material_request = frappe.db.get_value(
+ 'Material Request Item',
+ {'production_plan': production_plan.name, 'item_code': 'CUST-0987'},
+ 'parent'
+ )
mr = frappe.get_doc('Material Request', material_request)
+
self.assertTrue(mr.material_request_type, 'Customer Provided')
self.assertTrue(mr.customer, '_Test Customer')
def test_production_plan_with_multi_level_bom(self):
- #|Item Code | Qty |
- #|Test BOM 1 | 1 |
- #| Test BOM 2 | 2 |
- #| Test BOM 3 | 3 |
+ """
+ Item Code | Qty |
+ |Test BOM 1 | 1 |
+ |Test BOM 2 | 2 |
+ |Test BOM 3 | 3 |
+ """
for item_code in ["Test BOM 1", "Test BOM 2", "Test BOM 3", "Test RM BOM 1"]:
create_item(item_code, is_stock_item=1)
@@ -264,15 +362,18 @@
pln.make_work_order()
#last level sub-assembly work order produce qty
- to_produce_qty = frappe.db.get_value("Work Order",
- {"production_plan": pln.name, "production_item": "Test BOM 3"}, "qty")
+ to_produce_qty = frappe.db.get_value(
+ "Work Order",
+ {"production_plan": pln.name, "production_item": "Test BOM 3"},
+ "qty"
+ )
self.assertEqual(to_produce_qty, 18.0)
pln.cancel()
frappe.delete_doc("Production Plan", pln.name)
def test_get_warehouse_list_group(self):
- """Check if required warehouses are returned"""
+ "Check if required child warehouses are returned."
warehouse_json = '[{\"warehouse\":\"_Test Warehouse Group - _TC\"}]'
warehouses = set(get_warehouse_list(warehouse_json))
@@ -284,6 +385,7 @@
msg=f"Following warehouses were expected {', '.join(missing_warehouse)}")
def test_get_warehouse_list_single(self):
+ "Check if same warehouse is returned in absence of child warehouses."
warehouse_json = '[{\"warehouse\":\"_Test Scrap Warehouse - _TC\"}]'
warehouses = set(get_warehouse_list(warehouse_json))
@@ -292,6 +394,7 @@
self.assertEqual(warehouses, expected_warehouses)
def test_get_sales_order_with_variant(self):
+ "Check if Template BOM is fetched in absence of Variant BOM."
rm_item = create_item('PIV_RM', valuation_rate = 100)
if not frappe.db.exists('Item', {"item_code": 'PIV'}):
item = create_item('PIV', valuation_rate = 100)
@@ -348,16 +451,13 @@
frappe.db.rollback()
def test_subassmebly_sorting(self):
- """ Test subassembly sorting in case of multiple items with nested BOMs"""
+ "Test subassembly sorting in case of multiple items with nested BOMs."
from erpnext.manufacturing.doctype.bom.test_bom import create_nested_bom
prefix = "_TestLevel_"
boms = {
"Assembly": {
"SubAssembly1": {"ChildPart1": {}, "ChildPart2": {},},
- "SubAssembly2": {"ChildPart3": {}},
- "SubAssembly3": {"SubSubAssy1": {"ChildPart4": {}}},
- "ChildPart5": {},
"ChildPart6": {},
"SubAssembly4": {"SubSubAssy2": {"ChildPart7": {}}},
},
@@ -386,6 +486,7 @@
self.assertIn("SuperSecret", plan.sub_assembly_items[0].production_item)
def test_multiple_work_order_for_production_plan_item(self):
+ "Test producing Prod Plan (making WO) in parts."
def create_work_order(item, pln, qty):
# Get Production Items
items_data = pln.get_production_items()
@@ -414,26 +515,29 @@
bom = make_bom(item=item, raw_materials=raw_materials)
# Create Production Plan
- pln = create_production_plan(item_code=bom.item, planned_qty=10)
+ pln = create_production_plan(item_code=bom.item, planned_qty=5)
# All the created Work Orders
wo_list = []
- # Create and Submit 1st Work Order for 5 qty
- create_work_order(item, pln, 5)
+ # Create and Submit 1st Work Order for 3 qty
+ create_work_order(item, pln, 3)
+ pln.reload()
+ self.assertEqual(pln.po_items[0].ordered_qty, 3)
+
+ # Create and Submit 2nd Work Order for 2 qty
+ create_work_order(item, pln, 2)
pln.reload()
self.assertEqual(pln.po_items[0].ordered_qty, 5)
- # Create and Submit 2nd Work Order for 3 qty
- create_work_order(item, pln, 3)
- pln.reload()
- self.assertEqual(pln.po_items[0].ordered_qty, 8)
+ # Overproduction
+ self.assertRaises(OverProductionError, create_work_order, item=item, pln=pln, qty=2)
# Cancel 1st Work Order
wo1 = frappe.get_doc("Work Order", wo_list[0])
wo1.cancel()
pln.reload()
- self.assertEqual(pln.po_items[0].ordered_qty, 3)
+ self.assertEqual(pln.po_items[0].ordered_qty, 2)
# Cancel 2nd Work Order
wo2 = frappe.get_doc("Work Order", wo_list[1])
@@ -441,7 +545,123 @@
pln.reload()
self.assertEqual(pln.po_items[0].ordered_qty, 0)
+ def test_production_plan_pending_qty_with_sales_order(self):
+ """
+ Test Prod Plan impact via: SO -> Prod Plan -> WO -> SE -> SE (cancel)
+ """
+ from erpnext.manufacturing.doctype.work_order.test_work_order import make_wo_order_test_record
+ from erpnext.manufacturing.doctype.work_order.work_order import (
+ make_stock_entry as make_se_from_wo,
+ )
+
+ make_stock_entry(item_code="Raw Material Item 1",
+ target="Work In Progress - _TC",
+ qty=2, basic_rate=100
+ )
+ make_stock_entry(item_code="Raw Material Item 2",
+ target="Work In Progress - _TC",
+ qty=2, basic_rate=100
+ )
+
+ item = 'Test Production Item 1'
+ so = make_sales_order(item_code=item, qty=1)
+
+ pln = create_production_plan(
+ company=so.company,
+ get_items_from="Sales Order",
+ sales_order=so,
+ skip_getting_mr_items=True
+ )
+ self.assertEqual(pln.po_items[0].pending_qty, 1)
+
+ wo = make_wo_order_test_record(
+ item_code=item, qty=1,
+ company=so.company,
+ wip_warehouse='Work In Progress - _TC',
+ fg_warehouse='Finished Goods - _TC',
+ skip_transfer=1,
+ use_multi_level_bom=1,
+ do_not_submit=True
+ )
+ wo.production_plan = pln.name
+ wo.production_plan_item = pln.po_items[0].name
+ wo.submit()
+
+ se = frappe.get_doc(make_se_from_wo(wo.name, "Manufacture", 1))
+ se.submit()
+
+ pln.reload()
+ self.assertEqual(pln.po_items[0].pending_qty, 0)
+
+ se.cancel()
+ pln.reload()
+ self.assertEqual(pln.po_items[0].pending_qty, 1)
+
+ def test_production_plan_pending_qty_independent_items(self):
+ "Test Prod Plan impact if items are added independently (no from SO or MR)."
+ from erpnext.manufacturing.doctype.work_order.test_work_order import make_wo_order_test_record
+ from erpnext.manufacturing.doctype.work_order.work_order import (
+ make_stock_entry as make_se_from_wo,
+ )
+
+ make_stock_entry(item_code="Raw Material Item 1",
+ target="Work In Progress - _TC",
+ qty=2, basic_rate=100
+ )
+ make_stock_entry(item_code="Raw Material Item 2",
+ target="Work In Progress - _TC",
+ qty=2, basic_rate=100
+ )
+
+ pln = create_production_plan(
+ item_code='Test Production Item 1',
+ skip_getting_mr_items=True
+ )
+ self.assertEqual(pln.po_items[0].pending_qty, 1)
+
+ wo = make_wo_order_test_record(
+ item_code='Test Production Item 1', qty=1,
+ company=pln.company,
+ wip_warehouse='Work In Progress - _TC',
+ fg_warehouse='Finished Goods - _TC',
+ skip_transfer=1,
+ use_multi_level_bom=1,
+ do_not_submit=True
+ )
+ wo.production_plan = pln.name
+ wo.production_plan_item = pln.po_items[0].name
+ wo.submit()
+
+ se = frappe.get_doc(make_se_from_wo(wo.name, "Manufacture", 1))
+ se.submit()
+
+ pln.reload()
+ self.assertEqual(pln.po_items[0].pending_qty, 0)
+
+ se.cancel()
+ pln.reload()
+ self.assertEqual(pln.po_items[0].pending_qty, 1)
+
+ def test_qty_based_status(self):
+ pp = frappe.new_doc("Production Plan")
+ pp.po_items = [
+ frappe._dict(planned_qty=5, produce_qty=4)
+ ]
+ self.assertFalse(pp.all_items_completed())
+
+ pp.po_items = [
+ frappe._dict(planned_qty=5, produce_qty=10),
+ frappe._dict(planned_qty=5, produce_qty=4)
+ ]
+ self.assertFalse(pp.all_items_completed())
+
+
def create_production_plan(**args):
+ """
+ sales_order (obj): Sales Order Doc Object
+ get_items_from (str): Sales Order/Material Request
+ skip_getting_mr_items (bool): Whether or not to plan for new MRs
+ """
args = frappe._dict(args)
pln = frappe.get_doc({
@@ -449,20 +669,35 @@
'company': args.company or '_Test Company',
'customer': args.customer or '_Test Customer',
'posting_date': nowdate(),
- 'include_non_stock_items': args.include_non_stock_items or 1,
- 'include_subcontracted_items': args.include_subcontracted_items or 1,
- 'ignore_existing_ordered_qty': args.ignore_existing_ordered_qty or 1,
- 'po_items': [{
+ 'include_non_stock_items': args.include_non_stock_items or 0,
+ 'include_subcontracted_items': args.include_subcontracted_items or 0,
+ 'ignore_existing_ordered_qty': args.ignore_existing_ordered_qty or 0,
+ 'get_items_from': 'Sales Order'
+ })
+
+ if not args.get("sales_order"):
+ pln.append('po_items', {
'use_multi_level_bom': args.use_multi_level_bom or 1,
'item_code': args.item_code,
'bom_no': frappe.db.get_value('Item', args.item_code, 'default_bom'),
'planned_qty': args.planned_qty or 1,
'planned_start_date': args.planned_start_date or now_datetime()
- }]
- })
- mr_items = get_items_for_material_requests(pln.as_dict())
- for d in mr_items:
- pln.append('mr_items', d)
+ })
+
+ if args.get("get_items_from") == "Sales Order" and args.get("sales_order"):
+ so = args.get("sales_order")
+ pln.append('sales_orders', {
+ 'sales_order': so.name,
+ 'sales_order_date': so.transaction_date,
+ 'customer': so.customer,
+ 'grand_total': so.grand_total
+ })
+ pln.get_items()
+
+ if not args.get("skip_getting_mr_items"):
+ mr_items = get_items_for_material_requests(pln.as_dict())
+ for d in mr_items:
+ pln.append('mr_items', d)
if not args.do_not_save:
pln.insert()
diff --git a/erpnext/manufacturing/doctype/routing/routing.js b/erpnext/manufacturing/doctype/routing/routing.js
index 33a313e..b480c70 100644
--- a/erpnext/manufacturing/doctype/routing/routing.js
+++ b/erpnext/manufacturing/doctype/routing/routing.js
@@ -17,7 +17,7 @@
},
calculate_operating_cost: function(frm, child) {
- const operating_cost = flt(flt(child.hour_rate) * flt(child.time_in_mins) / 60, 2);
+ const operating_cost = flt(flt(child.hour_rate) * flt(child.time_in_mins) / 60, precision("operating_cost", child));
frappe.model.set_value(child.doctype, child.name, "operating_cost", operating_cost);
}
});
diff --git a/erpnext/manufacturing/doctype/routing/routing.py b/erpnext/manufacturing/doctype/routing/routing.py
index 1c76634..b207906 100644
--- a/erpnext/manufacturing/doctype/routing/routing.py
+++ b/erpnext/manufacturing/doctype/routing/routing.py
@@ -20,7 +20,8 @@
for operation in self.operations:
if not operation.hour_rate:
operation.hour_rate = frappe.db.get_value("Workstation", operation.workstation, 'hour_rate')
- operation.operating_cost = flt(flt(operation.hour_rate) * flt(operation.time_in_mins) / 60, 2)
+ operation.operating_cost = flt(flt(operation.hour_rate) * flt(operation.time_in_mins) / 60,
+ operation.precision("operating_cost"))
def set_routing_id(self):
sequence_id = 0
diff --git a/erpnext/manufacturing/doctype/routing/test_routing.py b/erpnext/manufacturing/doctype/routing/test_routing.py
index 8bd60ea..696d9bc 100644
--- a/erpnext/manufacturing/doctype/routing/test_routing.py
+++ b/erpnext/manufacturing/doctype/routing/test_routing.py
@@ -2,14 +2,14 @@
# See license.txt
import frappe
from frappe.test_runner import make_test_records
+from frappe.tests.utils import FrappeTestCase
from erpnext.manufacturing.doctype.job_card.job_card import OperationSequenceError
from erpnext.manufacturing.doctype.work_order.test_work_order import make_wo_order_test_record
from erpnext.stock.doctype.item.test_item import make_item
-from erpnext.tests.utils import ERPNextTestCase
-class TestRouting(ERPNextTestCase):
+class TestRouting(FrappeTestCase):
@classmethod
def setUpClass(cls):
cls.item_code = "Test Routing Item - A"
diff --git a/erpnext/manufacturing/doctype/work_order/test_work_order.py b/erpnext/manufacturing/doctype/work_order/test_work_order.py
index a399edd..bc07d22 100644
--- a/erpnext/manufacturing/doctype/work_order/test_work_order.py
+++ b/erpnext/manufacturing/doctype/work_order/test_work_order.py
@@ -2,6 +2,7 @@
# License: GNU General Public License v3. See license.txt
import frappe
+from frappe.tests.utils import FrappeTestCase, timeout
from frappe.utils import add_days, add_months, cint, flt, now, today
from erpnext.manufacturing.doctype.job_card.job_card import JobCardCancelError
@@ -21,10 +22,9 @@
from erpnext.stock.doctype.stock_entry import test_stock_entry
from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
from erpnext.stock.utils import get_bin
-from erpnext.tests.utils import ERPNextTestCase, timeout
-class TestWorkOrder(ERPNextTestCase):
+class TestWorkOrder(FrappeTestCase):
def setUp(self):
self.warehouse = '_Test Warehouse 2 - _TC'
self.item = '_Test Item'
@@ -201,6 +201,21 @@
self.assertEqual(cint(bin1_on_end_production.reserved_qty_for_production),
cint(bin1_on_start_production.reserved_qty_for_production))
+ def test_reserved_qty_for_production_closed(self):
+
+ wo1 = make_wo_order_test_record(item="_Test FG Item", qty=2,
+ source_warehouse=self.warehouse)
+ item = wo1.required_items[0].item_code
+ bin_before = get_bin(item, self.warehouse)
+ bin_before.update_reserved_qty_for_production()
+
+ make_wo_order_test_record(item="_Test FG Item", qty=2,
+ source_warehouse=self.warehouse)
+ close_work_order(wo1.name, "Closed")
+
+ bin_after = get_bin(item, self.warehouse)
+ self.assertEqual(bin_before.reserved_qty_for_production, bin_after.reserved_qty_for_production)
+
def test_backflush_qty_for_overpduction_manufacture(self):
cancel_stock_entry = []
allow_overproduction("overproduction_percentage_for_work_order", 30)
@@ -703,7 +718,8 @@
wo = make_wo_order_test_record(item=item_name, qty=1, source_warehouse=source_warehouse,
company=company)
- self.assertRaises(frappe.ValidationError, make_stock_entry, wo.name, 'Material Transfer for Manufacture')
+ stock_entry = frappe.get_doc(make_stock_entry(wo.name, 'Material Transfer for Manufacture'))
+ self.assertRaises(frappe.ValidationError, stock_entry.save)
def test_wo_completion_with_pl_bom(self):
from erpnext.manufacturing.doctype.bom.test_bom import (
@@ -1024,7 +1040,7 @@
wo_order.scrap_warehouse = args.fg_warehouse or "_Test Scrap Warehouse - _TC"
wo_order.company = args.company or "_Test Company"
wo_order.stock_uom = args.stock_uom or "_Test UOM"
- wo_order.use_multi_level_bom=0
+ wo_order.use_multi_level_bom= args.use_multi_level_bom or 0
wo_order.skip_transfer=args.skip_transfer or 0
wo_order.get_items_and_operations_from_bom()
wo_order.sales_order = args.sales_order or None
diff --git a/erpnext/manufacturing/doctype/work_order/work_order.py b/erpnext/manufacturing/doctype/work_order/work_order.py
index a86edfa..374ab86 100644
--- a/erpnext/manufacturing/doctype/work_order/work_order.py
+++ b/erpnext/manufacturing/doctype/work_order/work_order.py
@@ -8,6 +8,8 @@
from frappe import _
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc
+from frappe.query_builder import Case
+from frappe.query_builder.functions import Sum
from frappe.utils import (
cint,
date_diff,
@@ -74,7 +76,6 @@
self.set_required_items(reset_only_qty = len(self.get("required_items")))
-
def validate_sales_order(self):
if self.sales_order:
self.check_sales_order_on_hold_or_close()
@@ -271,7 +272,7 @@
produced_qty = total_qty[0][0] if total_qty else 0
- production_plan.run_method("update_produced_qty", produced_qty, self.production_plan_item)
+ production_plan.run_method("update_produced_pending_qty", produced_qty, self.production_plan_item)
def before_submit(self):
self.create_serial_no_batch_no()
@@ -544,7 +545,7 @@
if node.is_bom:
operations.extend(_get_operations(node.name, qty=node.exploded_qty))
- bom_qty = frappe.db.get_value("BOM", self.bom_no, "quantity")
+ bom_qty = frappe.get_cached_value("BOM", self.bom_no, "quantity")
operations.extend(_get_operations(self.bom_no, qty=1.0/bom_qty))
for correct_index, operation in enumerate(operations, start=1):
@@ -625,7 +626,7 @@
frappe.delete_doc("Job Card", d.name)
def validate_production_item(self):
- if frappe.db.get_value("Item", self.production_item, "has_variants"):
+ if frappe.get_cached_value("Item", self.production_item, "has_variants"):
frappe.throw(_("Work Order cannot be raised against a Item Template"), ItemHasVariantError)
if self.production_item:
@@ -635,6 +636,21 @@
if not self.qty > 0:
frappe.throw(_("Quantity to Manufacture must be greater than 0."))
+ if self.production_plan and self.production_plan_item:
+ qty_dict = frappe.db.get_value("Production Plan Item", self.production_plan_item, ["planned_qty", "ordered_qty"], as_dict=1)
+
+ allowance_qty =flt(frappe.db.get_single_value("Manufacturing Settings",
+ "overproduction_percentage_for_work_order"))/100 * qty_dict.get("planned_qty", 0)
+
+ max_qty = qty_dict.get("planned_qty", 0) + allowance_qty - qty_dict.get("ordered_qty", 0)
+
+ if max_qty < 1:
+ frappe.throw(_("Cannot produce more item for {0}")
+ .format(self.production_item), OverProductionError)
+ elif self.qty > max_qty:
+ frappe.throw(_("Cannot produce more than {0} items for {1}")
+ .format(max_qty, self.production_item), OverProductionError)
+
def validate_transfer_against(self):
if not self.docstatus == 1:
# let user configure operations until they're ready to submit
@@ -838,7 +854,7 @@
res = res[0]
if skip_bom_info: return res
- filters = {"item": item, "is_default": 1}
+ filters = {"item": item, "is_default": 1, "docstatus": 1}
if project:
filters = {"item": item, "project": project}
@@ -1175,3 +1191,27 @@
doc.set_item_locations()
return doc
+
+def get_reserved_qty_for_production(item_code: str, warehouse: str) -> float:
+ """Get total reserved quantity for any item in specified warehouse"""
+ wo = frappe.qb.DocType("Work Order")
+ wo_item = frappe.qb.DocType("Work Order Item")
+
+ return (
+ frappe.qb
+ .from_(wo)
+ .from_(wo_item)
+ .select(Sum(Case()
+ .when(wo.skip_transfer == 0, wo_item.required_qty - wo_item.transferred_qty)
+ .else_(wo_item.required_qty - wo_item.consumed_qty))
+ )
+ .where(
+ (wo_item.item_code == item_code)
+ & (wo_item.parent == wo.name)
+ & (wo.docstatus == 1)
+ & (wo_item.source_warehouse == warehouse)
+ & (wo.status.notin(["Stopped", "Completed", "Closed"]))
+ & ((wo_item.required_qty > wo_item.transferred_qty)
+ | (wo_item.required_qty > wo_item.consumed_qty))
+ )
+ ).run()[0][0] or 0.0
diff --git a/erpnext/manufacturing/doctype/workstation/test_workstation.py b/erpnext/manufacturing/doctype/workstation/test_workstation.py
index c298c0a..dd51017 100644
--- a/erpnext/manufacturing/doctype/workstation/test_workstation.py
+++ b/erpnext/manufacturing/doctype/workstation/test_workstation.py
@@ -2,6 +2,7 @@
# See license.txt
import frappe
from frappe.test_runner import make_test_records
+from frappe.tests.utils import FrappeTestCase
from erpnext.manufacturing.doctype.operation.test_operation import make_operation
from erpnext.manufacturing.doctype.routing.test_routing import create_routing, setup_bom
@@ -10,13 +11,12 @@
WorkstationHolidayError,
check_if_within_operating_hours,
)
-from erpnext.tests.utils import ERPNextTestCase
test_dependencies = ["Warehouse"]
test_records = frappe.get_test_records('Workstation')
make_test_records('Workstation')
-class TestWorkstation(ERPNextTestCase):
+class TestWorkstation(FrappeTestCase):
def test_validate_timings(self):
check_if_within_operating_hours("_Test Workstation 1", "Operation 1", "2013-02-02 11:00:00", "2013-02-02 19:00:00")
check_if_within_operating_hours("_Test Workstation 1", "Operation 1", "2013-02-02 10:00:00", "2013-02-02 20:00:00")
diff --git a/erpnext/manufacturing/doctype/workstation/workstation_dashboard.py b/erpnext/manufacturing/doctype/workstation/workstation_dashboard.py
index bc481ca..1fa1494 100644
--- a/erpnext/manufacturing/doctype/workstation/workstation_dashboard.py
+++ b/erpnext/manufacturing/doctype/workstation/workstation_dashboard.py
@@ -11,9 +11,9 @@
},
{
'label': _('Transaction'),
- 'items': ['Work Order', 'Job Card', 'Timesheet']
+ 'items': ['Work Order', 'Job Card',]
}
],
'disable_create_buttons': ['BOM', 'Routing', 'Operation',
- 'Work Order', 'Job Card', 'Timesheet']
+ 'Work Order', 'Job Card',]
}
diff --git a/erpnext/manufacturing/report/test_reports.py b/erpnext/manufacturing/report/test_reports.py
index 9f51ded..e436fdc 100644
--- a/erpnext/manufacturing/report/test_reports.py
+++ b/erpnext/manufacturing/report/test_reports.py
@@ -55,10 +55,11 @@
def test_execute_all_manufacturing_reports(self):
"""Test that all script report in manufacturing modules are executable with supported filters"""
for report, filter in REPORT_FILTER_TEST_CASES:
- execute_script_report(
- report_name=report,
- module="Manufacturing",
- filters=filter,
- default_filters=DEFAULT_FILTERS,
- optional_filters=OPTIONAL_FILTERS if filter.get("_optional") else None,
- )
+ with self.subTest(report=report):
+ execute_script_report(
+ report_name=report,
+ module="Manufacturing",
+ filters=filter,
+ default_filters=DEFAULT_FILTERS,
+ optional_filters=OPTIONAL_FILTERS if filter.get("_optional") else None,
+ )
diff --git a/erpnext/modules.txt b/erpnext/modules.txt
index c5705c1..c6b3159 100644
--- a/erpnext/modules.txt
+++ b/erpnext/modules.txt
@@ -15,10 +15,10 @@
Education
Regional
ERPNext Integrations
-Non Profit
Quality Management
Communication
Loan Management
Payroll
Telephony
+Bulk Transaction
E-commerce
diff --git a/erpnext/non_profit/doctype/certification_application/__init__.py b/erpnext/non_profit/doctype/certification_application/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/certification_application/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/certification_application/certification_application.js b/erpnext/non_profit/doctype/certification_application/certification_application.js
deleted file mode 100644
index 1e6a9a4..0000000
--- a/erpnext/non_profit/doctype/certification_application/certification_application.js
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Certification Application', {
- refresh: function(frm) {
-
- }
-});
diff --git a/erpnext/non_profit/doctype/certification_application/certification_application.json b/erpnext/non_profit/doctype/certification_application/certification_application.json
deleted file mode 100644
index f562fa6..0000000
--- a/erpnext/non_profit/doctype/certification_application/certification_application.json
+++ /dev/null
@@ -1,323 +0,0 @@
-{
- "allow_copy": 0,
- "allow_events_in_timeline": 0,
- "allow_guest_to_view": 0,
- "allow_import": 0,
- "allow_rename": 0,
- "autoname": "NPO-CAPP-.YYYY.-.#####",
- "beta": 0,
- "creation": "2018-06-08 16:12:42.091729",
- "custom": 0,
- "docstatus": 0,
- "doctype": "DocType",
- "document_type": "",
- "editable_grid": 1,
- "engine": "InnoDB",
- "fields": [
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "name_of_applicant",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Name of Applicant",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "email",
- "fieldtype": "Link",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Email",
- "length": 0,
- "no_copy": 0,
- "options": "User",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "column_break_1",
- "fieldtype": "Column Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "certification_status",
- "fieldtype": "Select",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Certification Status",
- "length": 0,
- "no_copy": 0,
- "options": "Yet to appear\nCertified\nNot Certified",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "payment_details",
- "fieldtype": "Section Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Payment Details",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "paid",
- "fieldtype": "Check",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Paid",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "currency",
- "fieldtype": "Select",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Currency",
- "length": 0,
- "no_copy": 0,
- "options": "USD\nINR",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "amount",
- "fieldtype": "Float",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Amount",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- }
- ],
- "has_web_view": 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": "2018-11-04 03:36:35.337403",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Certification Application",
- "name_case": "",
- "owner": "Administrator",
- "permissions": [
- {
- "amend": 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": "System Manager",
- "set_user_permissions": 0,
- "share": 1,
- "submit": 0,
- "write": 1
- }
- ],
- "quick_entry": 0,
- "read_only": 0,
- "read_only_onload": 0,
- "restrict_to_domain": "Non Profit",
- "show_name_in_global_search": 0,
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_changes": 1,
- "track_seen": 0,
- "track_views": 0
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/certification_application/certification_application.py b/erpnext/non_profit/doctype/certification_application/certification_application.py
deleted file mode 100644
index cbbe191..0000000
--- a/erpnext/non_profit/doctype/certification_application/certification_application.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-from frappe.model.document import Document
-
-
-class CertificationApplication(Document):
- pass
diff --git a/erpnext/non_profit/doctype/certification_application/test_certification_application.py b/erpnext/non_profit/doctype/certification_application/test_certification_application.py
deleted file mode 100644
index 8687b4d..0000000
--- a/erpnext/non_profit/doctype/certification_application/test_certification_application.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-
-class TestCertificationApplication(unittest.TestCase):
- pass
diff --git a/erpnext/non_profit/doctype/certified_consultant/__init__.py b/erpnext/non_profit/doctype/certified_consultant/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/certified_consultant/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/certified_consultant/certified_consultant.js b/erpnext/non_profit/doctype/certified_consultant/certified_consultant.js
deleted file mode 100644
index cd004c3..0000000
--- a/erpnext/non_profit/doctype/certified_consultant/certified_consultant.js
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Certified Consultant', {
- refresh: function(frm) {
-
- }
-});
diff --git a/erpnext/non_profit/doctype/certified_consultant/certified_consultant.json b/erpnext/non_profit/doctype/certified_consultant/certified_consultant.json
deleted file mode 100644
index d77f1b2..0000000
--- a/erpnext/non_profit/doctype/certified_consultant/certified_consultant.json
+++ /dev/null
@@ -1,724 +0,0 @@
-{
- "allow_copy": 0,
- "allow_events_in_timeline": 0,
- "allow_guest_to_view": 0,
- "allow_import": 0,
- "allow_rename": 0,
- "autoname": "NPO-CONS-.YYYY.-.#####",
- "beta": 0,
- "creation": "2018-06-13 17:27:19.838334",
- "custom": 0,
- "docstatus": 0,
- "doctype": "DocType",
- "document_type": "",
- "editable_grid": 1,
- "engine": "InnoDB",
- "fields": [
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "name_of_consultant",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Name of Consultant",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "country",
- "fieldtype": "Link",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Country",
- "length": 0,
- "no_copy": 0,
- "options": "Country",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "email",
- "fieldtype": "Link",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Email",
- "length": 0,
- "no_copy": 0,
- "options": "User",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "phone",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Phone",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "website_url",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Website",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "address",
- "fieldtype": "Small Text",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Address",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "column_break1",
- "fieldtype": "Column Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "image",
- "fieldtype": "Attach Image",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Image",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "certification_application",
- "fieldtype": "Link",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Certification Application",
- "length": 0,
- "no_copy": 0,
- "options": "Certification Application",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "section_break1",
- "fieldtype": "Section Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Certification Validity",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "from_date",
- "fieldtype": "Date",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "From",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "column_beak2",
- "fieldtype": "Column Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "to_date",
- "fieldtype": "Date",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "To",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "section_break2",
- "fieldtype": "Section Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "introduction",
- "fieldtype": "Small Text",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Introduction",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 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_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Details",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "section_break3",
- "fieldtype": "Section Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "discuss_id",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Discuss ID",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "github_id",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "GitHub ID",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_in_quick_entry": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "show_in_website",
- "fieldtype": "Check",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Show in Website",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- }
- ],
- "has_web_view": 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": "2018-11-04 03:36:47.386618",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Certified Consultant",
- "name_case": "",
- "owner": "Administrator",
- "permissions": [
- {
- "amend": 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": "System Manager",
- "set_user_permissions": 0,
- "share": 1,
- "submit": 0,
- "write": 1
- },
- {
- "amend": 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": "Non Profit Manager",
- "set_user_permissions": 0,
- "share": 1,
- "submit": 0,
- "write": 1
- }
- ],
- "quick_entry": 0,
- "read_only": 0,
- "read_only_onload": 0,
- "restrict_to_domain": "Non Profit",
- "show_name_in_global_search": 0,
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_changes": 1,
- "track_seen": 0,
- "track_views": 0
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/certified_consultant/certified_consultant.py b/erpnext/non_profit/doctype/certified_consultant/certified_consultant.py
deleted file mode 100644
index 47361cc..0000000
--- a/erpnext/non_profit/doctype/certified_consultant/certified_consultant.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-from frappe.model.document import Document
-
-
-class CertifiedConsultant(Document):
- pass
diff --git a/erpnext/non_profit/doctype/certified_consultant/test_certified_consultant.py b/erpnext/non_profit/doctype/certified_consultant/test_certified_consultant.py
deleted file mode 100644
index d10353c..0000000
--- a/erpnext/non_profit/doctype/certified_consultant/test_certified_consultant.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-
-class TestCertifiedConsultant(unittest.TestCase):
- pass
diff --git a/erpnext/non_profit/doctype/chapter/chapter.js b/erpnext/non_profit/doctype/chapter/chapter.js
deleted file mode 100644
index c8b6d4a..0000000
--- a/erpnext/non_profit/doctype/chapter/chapter.js
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Chapter', {
- refresh: function() {
-
- }
-});
diff --git a/erpnext/non_profit/doctype/chapter/chapter.json b/erpnext/non_profit/doctype/chapter/chapter.json
deleted file mode 100644
index 86cba9a..0000000
--- a/erpnext/non_profit/doctype/chapter/chapter.json
+++ /dev/null
@@ -1,397 +0,0 @@
-{
- "allow_copy": 0,
- "allow_guest_to_view": 1,
- "allow_import": 0,
- "allow_rename": 1,
- "autoname": "prompt",
- "beta": 0,
- "creation": "2017-09-14 13:36:03.904702",
- "custom": 0,
- "docstatus": 0,
- "doctype": "DocType",
- "document_type": "",
- "editable_grid": 1,
- "engine": "InnoDB",
- "fields": [
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "chapter_head",
- "fieldtype": "Link",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Chapter Head",
- "length": 0,
- "no_copy": 0,
- "options": "Member",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "column_break_3",
- "fieldtype": "Column Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "region",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Region",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "section_break_5",
- "fieldtype": "Section Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "introduction",
- "fieldtype": "Text Editor",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Introduction",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "meetup_embed_html",
- "fieldtype": "Code",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Meetup Embed HTML",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "address",
- "fieldtype": "Text",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Address",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "description": "chapters/chapter_name\nleave blank automatically set after saving chapter.",
- "fieldname": "route",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Route",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "published",
- "fieldtype": "Check",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Published",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 1,
- "columns": 0,
- "fieldname": "chapter_members",
- "fieldtype": "Section Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Chapter Members",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "members",
- "fieldtype": "Table",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Members",
- "length": 0,
- "no_copy": 0,
- "options": "Chapter Member",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- }
- ],
- "has_web_view": 1,
- "hide_heading": 0,
- "hide_toolbar": 0,
- "idx": 0,
- "image_view": 0,
- "in_create": 0,
- "is_published_field": "published",
- "is_submittable": 0,
- "issingle": 0,
- "istable": 0,
- "max_attachments": 0,
- "modified": "2017-12-14 12:59:31.424240",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Chapter",
- "name_case": "Title 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": "Non Profit Manager",
- "set_user_permissions": 0,
- "share": 1,
- "submit": 0,
- "write": 1
- }
- ],
- "quick_entry": 1,
- "read_only": 0,
- "read_only_onload": 0,
- "restrict_to_domain": "Non Profit",
- "route": "chapters",
- "show_name_in_global_search": 0,
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_changes": 1,
- "track_seen": 0
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/chapter/chapter.py b/erpnext/non_profit/doctype/chapter/chapter.py
deleted file mode 100644
index c01b1ef..0000000
--- a/erpnext/non_profit/doctype/chapter/chapter.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-import frappe
-from frappe.website.website_generator import WebsiteGenerator
-
-
-class Chapter(WebsiteGenerator):
- _website = frappe._dict(
- condition_field = "published",
- )
-
- def get_context(self, context):
- context.no_cache = True
- context.show_sidebar = True
- context.parents = [dict(label='View All Chapters',
- route='chapters', title='View Chapters')]
-
- def validate(self):
- if not self.route: #pylint: disable=E0203
- self.route = 'chapters/' + self.scrub(self.name)
-
- def enable(self):
- chapter = frappe.get_doc('Chapter', frappe.form_dict.name)
- chapter.append('members', dict(enable=self.value))
- chapter.save(ignore_permissions=1)
- frappe.db.commit()
-
-
-def get_list_context(context):
- context.allow_guest = True
- context.no_cache = True
- context.show_sidebar = True
- context.title = 'All Chapters'
- context.no_breadcrumbs = True
- context.order_by = 'creation desc'
-
-
-@frappe.whitelist()
-def leave(title, user_id, leave_reason):
- chapter = frappe.get_doc("Chapter", title)
- for member in chapter.members:
- if member.user == user_id:
- member.enabled = 0
- member.leave_reason = leave_reason
- chapter.save(ignore_permissions=1)
- frappe.db.commit()
- return "Thank you for Feedback"
diff --git a/erpnext/non_profit/doctype/chapter/templates/chapter.html b/erpnext/non_profit/doctype/chapter/templates/chapter.html
deleted file mode 100644
index 321828f..0000000
--- a/erpnext/non_profit/doctype/chapter/templates/chapter.html
+++ /dev/null
@@ -1,79 +0,0 @@
-{% extends "templates/web.html" %}
-
-{% block page_content %}
-<h1>{{ title }}</h1>
-<p>{{ introduction }}</p>
-{% if meetup_embed_html %}
- {{ meetup_embed_html }}
-{% endif %}
-<h3>Member Details</h3>
-
-{% if members %}
- <table class="table" style="max-width: 600px;">
- {% set index = [1] %}
- {% for user in members %}
- {% if user.enabled == 1 %}
- <tr>
- <td>
- <div style="margin-bottom: 30px; max-width: 600px" class="with-border">
- <div class="row">
- <div class="col-lg-6 col-md-6 col-sm-6">
- <div class="pull-left">
- <b>{{ index|length }}. {{ frappe.db.get_value('User', user.user, 'full_name') }}</b></div>
- </div>
- <div class="pull-right">
- {% if user.website_url %}
- <a href="{{ user.website_url }}">{{ user.website_url | truncate (50) or '' }}</a>
- {% endif %}
- </div>
- <div class="clearfix"></div>
- </div>
- <br><br>
- <div class="col-lg-12">
- {% if user.introduction %}
- {{ user.introduction }}
- {% endif %}
- </div>
- </div>
- </div>
- </td>
- </tr>
- {% set __ = index.append(1) %}
- {% endif %}
- {% endfor %}
- </table>
-{% else %}
- <p>No member yet.</p>
-{% endif %}
-
-<h3>Chapter Head</h3>
-<div style="margin-bottom: 30px; max-width: 600px" class="with-border">
-
-<table class="table table-bordered small" style="max-width: 600px;">
- {% set doc = frappe.get_doc('Member',chapter_head) %}
- <tr>
- <td style='width: 15%'>Name</td>
- <td><b>{{ doc.member_name }}<b></td>
- </tr>
- <tr>
- <td>Email</td>
- <td>{{ frappe.db.get_value('User', doc.email, 'email') or '' }}</td>
- </tr>
- <tr>
- <td>Phone</td>
- <td>{{ frappe.db.get_value('User', doc.email, 'phone') or '' }}</td>
- </tr>
-</table>
-</div>
-
-{% if address %}
-<h3>Address</h3>
-<div style="margin-bottom: 30px; max-width: 600px" class="with-border">
-<p>{{ address or ''}}</p>
-</div>
-{% endif %}
-
-<p style="margin: 20px 0 30px;"><a href="/non_profit/join-chapter?name={{ name }}" class='btn btn-primary'>Join this Chapter</a></p>
-<p style="margin: 20px 0 30px;"><a href="/non_profit/leave-chapter?name={{ name }}" class=''>Leave this Chapter</a></p>
-
-{% endblock %}
diff --git a/erpnext/non_profit/doctype/chapter/templates/chapter_row.html b/erpnext/non_profit/doctype/chapter/templates/chapter_row.html
deleted file mode 100644
index cad34fa..0000000
--- a/erpnext/non_profit/doctype/chapter/templates/chapter_row.html
+++ /dev/null
@@ -1,25 +0,0 @@
-{% if doc.published %}
- <div style="margin-bottom: 30px; max-width: 600px" class="with-border clickable">
- <a href={{ doc.route }}>
- <h3>{{ doc.name }}</h3>
- <p>
- <span class="label"> Chapter Head : {{ frappe.db.get_value('User', chapter_head, 'full_name') }} </span>
- <span class="label">
- {% if members %}
- {% set index = [] %}
- {% for user in members %}
- {% if user.enabled == 1 %}
- {% set __ = index.append(1) %}
- {% endif %}
- {% endfor %}
- Members: {{ index|length }}
- {% else %}
- Members: 0
- {% endif %}
- </span>
- <!-- Assignment of value to global variable not working in jinja -->
- </p>
- <p>{{ html2text(doc.introduction) | truncate (200) }}</p>
- </a>
- </div>
-{% endif %}
diff --git a/erpnext/non_profit/doctype/chapter/test_chapter.py b/erpnext/non_profit/doctype/chapter/test_chapter.py
deleted file mode 100644
index 98601ef..0000000
--- a/erpnext/non_profit/doctype/chapter/test_chapter.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-
-class TestChapter(unittest.TestCase):
- pass
diff --git a/erpnext/non_profit/doctype/chapter_member/__init__.py b/erpnext/non_profit/doctype/chapter_member/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/chapter_member/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/chapter_member/chapter_member.json b/erpnext/non_profit/doctype/chapter_member/chapter_member.json
deleted file mode 100644
index 478bfd9..0000000
--- a/erpnext/non_profit/doctype/chapter_member/chapter_member.json
+++ /dev/null
@@ -1,199 +0,0 @@
-{
- "allow_copy": 0,
- "allow_guest_to_view": 0,
- "allow_import": 0,
- "allow_rename": 0,
- "beta": 0,
- "creation": "2017-09-14 13:38:04.296375",
- "custom": 0,
- "docstatus": 0,
- "doctype": "DocType",
- "document_type": "",
- "editable_grid": 1,
- "engine": "InnoDB",
- "fields": [
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "user",
- "fieldtype": "Link",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "User",
- "length": 0,
- "no_copy": 0,
- "options": "User",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "introduction",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Introduction",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "website_url",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Website URL",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 2,
- "default": "1",
- "fieldname": "enabled",
- "fieldtype": "Check",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Enabled",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "leave_reason",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Leave Reason",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "translatable": 0,
- "unique": 0
- }
- ],
- "has_web_view": 0,
- "hide_heading": 0,
- "hide_toolbar": 0,
- "idx": 0,
- "image_view": 0,
- "in_create": 0,
- "is_submittable": 0,
- "issingle": 0,
- "istable": 1,
- "max_attachments": 0,
- "modified": "2018-03-07 05:36:51.664816",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Chapter Member",
- "name_case": "",
- "owner": "Administrator",
- "permissions": [],
- "quick_entry": 1,
- "read_only": 0,
- "read_only_onload": 0,
- "restrict_to_domain": "Non Profit",
- "show_name_in_global_search": 0,
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_changes": 1,
- "track_seen": 0
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/chapter_member/chapter_member.py b/erpnext/non_profit/doctype/chapter_member/chapter_member.py
deleted file mode 100644
index 80c0446..0000000
--- a/erpnext/non_profit/doctype/chapter_member/chapter_member.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-from frappe.model.document import Document
-
-
-class ChapterMember(Document):
- pass
diff --git a/erpnext/non_profit/doctype/donation/__init__.py b/erpnext/non_profit/doctype/donation/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/donation/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/donation/donation.js b/erpnext/non_profit/doctype/donation/donation.js
deleted file mode 100644
index 10e8220..0000000
--- a/erpnext/non_profit/doctype/donation/donation.js
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Donation', {
- refresh: function(frm) {
- if (frm.doc.docstatus === 1 && !frm.doc.paid) {
- frm.add_custom_button(__('Create Payment Entry'), function() {
- frm.events.make_payment_entry(frm);
- });
- }
- },
-
- make_payment_entry: function(frm) {
- return frappe.call({
- method: 'erpnext.accounts.doctype.payment_entry.payment_entry.get_payment_entry',
- args: {
- 'dt': frm.doc.doctype,
- 'dn': frm.doc.name
- },
- callback: function(r) {
- var doc = frappe.model.sync(r.message);
- frappe.set_route('Form', doc[0].doctype, doc[0].name);
- }
- });
- },
-});
diff --git a/erpnext/non_profit/doctype/donation/donation.json b/erpnext/non_profit/doctype/donation/donation.json
deleted file mode 100644
index 6759569..0000000
--- a/erpnext/non_profit/doctype/donation/donation.json
+++ /dev/null
@@ -1,156 +0,0 @@
-{
- "actions": [],
- "autoname": "naming_series:",
- "creation": "2021-02-17 10:28:52.645731",
- "doctype": "DocType",
- "editable_grid": 1,
- "engine": "InnoDB",
- "field_order": [
- "naming_series",
- "donor",
- "donor_name",
- "email",
- "column_break_4",
- "company",
- "date",
- "payment_details_section",
- "paid",
- "amount",
- "mode_of_payment",
- "razorpay_payment_id",
- "amended_from"
- ],
- "fields": [
- {
- "fieldname": "donor",
- "fieldtype": "Link",
- "label": "Donor",
- "options": "Donor",
- "reqd": 1
- },
- {
- "fetch_from": "donor.donor_name",
- "fieldname": "donor_name",
- "fieldtype": "Data",
- "in_list_view": 1,
- "in_standard_filter": 1,
- "label": "Donor Name",
- "read_only": 1
- },
- {
- "fetch_from": "donor.email",
- "fieldname": "email",
- "fieldtype": "Data",
- "in_list_view": 1,
- "in_standard_filter": 1,
- "label": "Email",
- "read_only": 1
- },
- {
- "fieldname": "column_break_4",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "date",
- "fieldtype": "Date",
- "label": "Date",
- "reqd": 1
- },
- {
- "fieldname": "payment_details_section",
- "fieldtype": "Section Break",
- "label": "Payment Details"
- },
- {
- "fieldname": "amount",
- "fieldtype": "Currency",
- "label": "Amount",
- "reqd": 1
- },
- {
- "fieldname": "mode_of_payment",
- "fieldtype": "Link",
- "label": "Mode of Payment",
- "options": "Mode of Payment"
- },
- {
- "fieldname": "razorpay_payment_id",
- "fieldtype": "Data",
- "label": "Razorpay Payment ID",
- "read_only": 1
- },
- {
- "fieldname": "naming_series",
- "fieldtype": "Select",
- "label": "Naming Series",
- "options": "NPO-DTN-.YYYY.-"
- },
- {
- "default": "0",
- "fieldname": "paid",
- "fieldtype": "Check",
- "in_list_view": 1,
- "in_standard_filter": 1,
- "label": "Paid"
- },
- {
- "fieldname": "company",
- "fieldtype": "Link",
- "label": "Company",
- "options": "Company",
- "reqd": 1
- },
- {
- "fieldname": "amended_from",
- "fieldtype": "Link",
- "label": "Amended From",
- "no_copy": 1,
- "options": "Donation",
- "print_hide": 1,
- "read_only": 1
- }
- ],
- "index_web_pages_for_search": 1,
- "is_submittable": 1,
- "links": [],
- "modified": "2021-03-11 10:53:11.269005",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Donation",
- "owner": "Administrator",
- "permissions": [
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "export": 1,
- "print": 1,
- "read": 1,
- "report": 1,
- "role": "System Manager",
- "select": 1,
- "share": 1,
- "submit": 1,
- "write": 1
- },
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "export": 1,
- "print": 1,
- "read": 1,
- "report": 1,
- "role": "Non Profit Manager",
- "select": 1,
- "share": 1,
- "submit": 1,
- "write": 1
- }
- ],
- "search_fields": "donor_name, email",
- "sort_field": "modified",
- "sort_order": "DESC",
- "title_field": "donor_name",
- "track_changes": 1
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/donation/donation.py b/erpnext/non_profit/doctype/donation/donation.py
deleted file mode 100644
index 54bc94b..0000000
--- a/erpnext/non_profit/doctype/donation/donation.py
+++ /dev/null
@@ -1,220 +0,0 @@
-# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-import json
-
-import frappe
-from frappe import _
-from frappe.email import sendmail_to_system_managers
-from frappe.model.document import Document
-from frappe.utils import flt, get_link_to_form, getdate
-
-from erpnext.non_profit.doctype.membership.membership import verify_signature
-
-
-class Donation(Document):
- def validate(self):
- if not self.donor or not frappe.db.exists('Donor', self.donor):
- # for web forms
- user_type = frappe.db.get_value('User', frappe.session.user, 'user_type')
- if user_type == 'Website User':
- self.create_donor_for_website_user()
- else:
- frappe.throw(_('Please select a Member'))
-
- def create_donor_for_website_user(self):
- donor_name = frappe.get_value('Donor', dict(email=frappe.session.user))
-
- if not donor_name:
- user = frappe.get_doc('User', frappe.session.user)
- donor = frappe.get_doc(dict(
- doctype='Donor',
- donor_type=self.get('donor_type'),
- email=frappe.session.user,
- member_name=user.get_fullname()
- )).insert(ignore_permissions=True)
- donor_name = donor.name
-
- if self.get('__islocal'):
- self.donor = donor_name
-
- def on_payment_authorized(self, *args, **kwargs):
- self.load_from_db()
- self.create_payment_entry()
-
- def create_payment_entry(self, date=None):
- settings = frappe.get_doc('Non Profit Settings')
- if not settings.automate_donation_payment_entries:
- return
-
- if not settings.donation_payment_account:
- frappe.throw(_('You need to set <b>Payment Account</b> for Donation in {0}').format(
- get_link_to_form('Non Profit Settings', 'Non Profit Settings')))
-
- from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
-
- frappe.flags.ignore_account_permission = True
- pe = get_payment_entry(dt=self.doctype, dn=self.name)
- frappe.flags.ignore_account_permission = False
- pe.paid_from = settings.donation_debit_account
- pe.paid_to = settings.donation_payment_account
- pe.posting_date = date or getdate()
- pe.reference_no = self.name
- pe.reference_date = date or getdate()
- pe.flags.ignore_mandatory = True
- pe.insert()
- pe.submit()
-
-
-@frappe.whitelist(allow_guest=True)
-def capture_razorpay_donations(*args, **kwargs):
- """
- Creates Donation from Razorpay Webhook Request Data on payment.captured event
- Creates Donor from email if not found
- """
- data = frappe.request.get_data(as_text=True)
-
- try:
- verify_signature(data, endpoint='Donation')
- except Exception as e:
- log = frappe.log_error(e, 'Donation Webhook Verification Error')
- notify_failure(log)
- return { 'status': 'Failed', 'reason': e }
-
- if isinstance(data, str):
- data = json.loads(data)
- data = frappe._dict(data)
-
- payment = data.payload.get('payment', {}).get('entity', {})
- payment = frappe._dict(payment)
-
- try:
- if not data.event == 'payment.captured':
- return
-
- # to avoid capturing subscription payments as donations
- if payment.description and 'subscription' in str(payment.description).lower():
- return
-
- donor = get_donor(payment.email)
- if not donor:
- donor = create_donor(payment)
-
- donation = create_donation(donor, payment)
- donation.run_method('create_payment_entry')
-
- except Exception as e:
- message = '{0}\n\n{1}\n\n{2}: {3}'.format(e, frappe.get_traceback(), _('Payment ID'), payment.id)
- log = frappe.log_error(message, _('Error creating donation entry for {0}').format(donor.name))
- notify_failure(log)
- return { 'status': 'Failed', 'reason': e }
-
- return { 'status': 'Success' }
-
-
-def create_donation(donor, payment):
- if not frappe.db.exists('Mode of Payment', payment.method):
- create_mode_of_payment(payment.method)
-
- company = get_company_for_donations()
- donation = frappe.get_doc({
- 'doctype': 'Donation',
- 'company': company,
- 'donor': donor.name,
- 'donor_name': donor.donor_name,
- 'email': donor.email,
- 'date': getdate(),
- 'amount': flt(payment.amount) / 100, # Convert to rupees from paise
- 'mode_of_payment': payment.method,
- 'razorpay_payment_id': payment.id
- }).insert(ignore_mandatory=True)
-
- donation.submit()
- return donation
-
-
-def get_donor(email):
- donors = frappe.get_all('Donor',
- filters={'email': email},
- order_by='creation desc')
-
- try:
- return frappe.get_doc('Donor', donors[0]['name'])
- except Exception:
- return None
-
-
-@frappe.whitelist()
-def create_donor(payment):
- donor_details = frappe._dict(payment)
- donor_type = frappe.db.get_single_value('Non Profit Settings', 'default_donor_type')
-
- donor = frappe.new_doc('Donor')
- donor.update({
- 'donor_name': donor_details.email,
- 'donor_type': donor_type,
- 'email': donor_details.email,
- 'contact': donor_details.contact
- })
-
- if donor_details.get('notes'):
- donor = get_additional_notes(donor, donor_details)
-
- donor.insert(ignore_mandatory=True)
- return donor
-
-
-def get_company_for_donations():
- company = frappe.db.get_single_value('Non Profit Settings', 'donation_company')
- if not company:
- from erpnext.non_profit.utils import get_company
- company = get_company()
- return company
-
-
-def get_additional_notes(donor, donor_details):
- if type(donor_details.notes) == dict:
- for k, v in donor_details.notes.items():
- notes = '\n'.join('{}: {}'.format(k, v))
-
- # extract donor name from notes
- if 'name' in k.lower():
- donor.update({
- 'donor_name': donor_details.notes.get(k)
- })
-
- # extract pan from notes
- if 'pan' in k.lower():
- donor.update({
- 'pan_number': donor_details.notes.get(k)
- })
-
- donor.add_comment('Comment', notes)
-
- elif type(donor_details.notes) == str:
- donor.add_comment('Comment', donor_details.notes)
-
- return donor
-
-
-def create_mode_of_payment(method):
- frappe.get_doc({
- 'doctype': 'Mode of Payment',
- 'mode_of_payment': method
- }).insert(ignore_mandatory=True)
-
-
-def notify_failure(log):
- try:
- content = '''
- Dear System Manager,
- Razorpay webhook for creating donation failed due to some reason.
- Please check the error log linked below
- Error Log: {0}
- Regards, Administrator
- '''.format(get_link_to_form('Error Log', log.name))
-
- sendmail_to_system_managers(_('[Important] [ERPNext] Razorpay donation webhook failed, please check.'), content)
- except Exception:
- pass
diff --git a/erpnext/non_profit/doctype/donation/donation_dashboard.py b/erpnext/non_profit/doctype/donation/donation_dashboard.py
deleted file mode 100644
index 492ad62..0000000
--- a/erpnext/non_profit/doctype/donation/donation_dashboard.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from frappe import _
-
-
-def get_data():
- return {
- 'fieldname': 'donation',
- 'non_standard_fieldnames': {
- 'Payment Entry': 'reference_name'
- },
- 'transactions': [
- {
- 'label': _('Payment'),
- 'items': ['Payment Entry']
- }
- ]
- }
diff --git a/erpnext/non_profit/doctype/donation/test_donation.py b/erpnext/non_profit/doctype/donation/test_donation.py
deleted file mode 100644
index 5fa731a..0000000
--- a/erpnext/non_profit/doctype/donation/test_donation.py
+++ /dev/null
@@ -1,77 +0,0 @@
-# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-import frappe
-
-from erpnext.non_profit.doctype.donation.donation import create_donation
-
-
-class TestDonation(unittest.TestCase):
- def setUp(self):
- create_donor_type()
- settings = frappe.get_doc('Non Profit Settings')
- settings.company = '_Test Company'
- settings.donation_company = '_Test Company'
- settings.default_donor_type = '_Test Donor'
- settings.automate_donation_payment_entries = 1
- settings.donation_debit_account = 'Debtors - _TC'
- settings.donation_payment_account = 'Cash - _TC'
- settings.creation_user = 'Administrator'
- settings.flags.ignore_permissions = True
- settings.save()
-
- def test_payment_entry_for_donations(self):
- donor = create_donor()
- create_mode_of_payment()
- payment = frappe._dict({
- 'amount': 100,
- 'method': 'Debit Card',
- 'id': 'pay_MeXAmsgeKOhq7O'
- })
- donation = create_donation(donor, payment)
-
- self.assertTrue(donation.name)
-
- # Naive test to check if at all payment entry is generated
- # This method is actually triggered from Payment Gateway
- # In any case if details were missing, this would throw an error
- donation.on_payment_authorized()
- donation.reload()
-
- self.assertEqual(donation.paid, 1)
- self.assertTrue(frappe.db.exists('Payment Entry', {'reference_no': donation.name}))
-
-
-def create_donor_type():
- if not frappe.db.exists('Donor Type', '_Test Donor'):
- frappe.get_doc({
- 'doctype': 'Donor Type',
- 'donor_type': '_Test Donor'
- }).insert()
-
-
-def create_donor():
- donor = frappe.db.exists('Donor', 'donor@test.com')
- if donor:
- return frappe.get_doc('Donor', 'donor@test.com')
- else:
- return frappe.get_doc({
- 'doctype': 'Donor',
- 'donor_name': '_Test Donor',
- 'donor_type': '_Test Donor',
- 'email': 'donor@test.com'
- }).insert()
-
-
-def create_mode_of_payment():
- if not frappe.db.exists('Mode of Payment', 'Debit Card'):
- frappe.get_doc({
- 'doctype': 'Mode of Payment',
- 'mode_of_payment': 'Debit Card',
- 'accounts': [{
- 'company': '_Test Company',
- 'default_account': 'Cash - _TC'
- }]
- }).insert()
diff --git a/erpnext/non_profit/doctype/donor/__init__.py b/erpnext/non_profit/doctype/donor/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/donor/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/donor/donor.js b/erpnext/non_profit/doctype/donor/donor.js
deleted file mode 100644
index 090d5af..0000000
--- a/erpnext/non_profit/doctype/donor/donor.js
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Donor', {
- refresh: function(frm) {
- frappe.dynamic_link = {doc: frm.doc, fieldname: 'name', doctype: 'Donor'};
-
- frm.toggle_display(['address_html','contact_html'], !frm.doc.__islocal);
-
- if(!frm.doc.__islocal) {
- frappe.contacts.render_address_and_contact(frm);
- } else {
- frappe.contacts.clear_address_and_contact(frm);
- }
-
- }
-});
diff --git a/erpnext/non_profit/doctype/donor/donor.json b/erpnext/non_profit/doctype/donor/donor.json
deleted file mode 100644
index 72f24ef..0000000
--- a/erpnext/non_profit/doctype/donor/donor.json
+++ /dev/null
@@ -1,110 +0,0 @@
-{
- "actions": [],
- "allow_rename": 1,
- "autoname": "field:email",
- "creation": "2017-09-19 16:20:27.510196",
- "doctype": "DocType",
- "editable_grid": 1,
- "engine": "InnoDB",
- "field_order": [
- "donor_name",
- "column_break_5",
- "donor_type",
- "email",
- "image",
- "address_contacts",
- "address_html",
- "column_break_9",
- "contact_html"
- ],
- "fields": [
- {
- "fieldname": "donor_name",
- "fieldtype": "Data",
- "in_list_view": 1,
- "label": "Donor Name",
- "reqd": 1
- },
- {
- "fieldname": "column_break_5",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "donor_type",
- "fieldtype": "Link",
- "in_list_view": 1,
- "label": "Donor Type",
- "options": "Donor Type",
- "reqd": 1
- },
- {
- "fieldname": "email",
- "fieldtype": "Data",
- "in_list_view": 1,
- "label": "Email",
- "reqd": 1,
- "unique": 1
- },
- {
- "fieldname": "image",
- "fieldtype": "Attach Image",
- "hidden": 1,
- "label": "Image",
- "no_copy": 1,
- "print_hide": 1
- },
- {
- "depends_on": "eval:!doc.__islocal;",
- "fieldname": "address_contacts",
- "fieldtype": "Section Break",
- "label": "Address and Contact",
- "options": "fa fa-map-marker"
- },
- {
- "fieldname": "address_html",
- "fieldtype": "HTML",
- "label": "Address HTML"
- },
- {
- "fieldname": "column_break_9",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "contact_html",
- "fieldtype": "HTML",
- "label": "Contact HTML"
- }
- ],
- "image_field": "image",
- "links": [
- {
- "link_doctype": "Donation",
- "link_fieldname": "donor"
- }
- ],
- "modified": "2021-02-17 16:36:33.470731",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Donor",
- "owner": "Administrator",
- "permissions": [
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "export": 1,
- "print": 1,
- "read": 1,
- "report": 1,
- "role": "Non Profit Manager",
- "share": 1,
- "write": 1
- }
- ],
- "quick_entry": 1,
- "restrict_to_domain": "Non Profit",
- "sort_field": "modified",
- "sort_order": "DESC",
- "title_field": "donor_name",
- "track_changes": 1
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/donor/donor.py b/erpnext/non_profit/doctype/donor/donor.py
deleted file mode 100644
index 058321b..0000000
--- a/erpnext/non_profit/doctype/donor/donor.py
+++ /dev/null
@@ -1,17 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-from frappe.contacts.address_and_contact import load_address_and_contact
-from frappe.model.document import Document
-
-
-class Donor(Document):
- def onload(self):
- """Load address and contacts in `__onload`"""
- load_address_and_contact(self)
-
- def validate(self):
- from frappe.utils import validate_email_address
- if self.email:
- validate_email_address(self.email.strip(), True)
diff --git a/erpnext/non_profit/doctype/donor/donor_list.js b/erpnext/non_profit/doctype/donor/donor_list.js
deleted file mode 100644
index 31d4d29..0000000
--- a/erpnext/non_profit/doctype/donor/donor_list.js
+++ /dev/null
@@ -1,3 +0,0 @@
-frappe.listview_settings['Donor'] = {
- add_fields: ["donor_name", "donor_type", "image"],
-};
diff --git a/erpnext/non_profit/doctype/donor/test_donor.py b/erpnext/non_profit/doctype/donor/test_donor.py
deleted file mode 100644
index fe591c8..0000000
--- a/erpnext/non_profit/doctype/donor/test_donor.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-
-class TestDonor(unittest.TestCase):
- pass
diff --git a/erpnext/non_profit/doctype/donor_type/__init__.py b/erpnext/non_profit/doctype/donor_type/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/donor_type/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/donor_type/donor_type.js b/erpnext/non_profit/doctype/donor_type/donor_type.js
deleted file mode 100644
index 7b1fd4f..0000000
--- a/erpnext/non_profit/doctype/donor_type/donor_type.js
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Donor Type', {
- refresh: function() {
-
- }
-});
diff --git a/erpnext/non_profit/doctype/donor_type/donor_type.json b/erpnext/non_profit/doctype/donor_type/donor_type.json
deleted file mode 100644
index 07118fd..0000000
--- a/erpnext/non_profit/doctype/donor_type/donor_type.json
+++ /dev/null
@@ -1,94 +0,0 @@
-{
- "allow_copy": 0,
- "allow_guest_to_view": 0,
- "allow_import": 0,
- "allow_rename": 0,
- "autoname": "field:donor_type",
- "beta": 0,
- "creation": "2017-09-19 16:19:16.639635",
- "custom": 0,
- "docstatus": 0,
- "doctype": "DocType",
- "document_type": "",
- "editable_grid": 1,
- "engine": "InnoDB",
- "fields": [
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "donor_type",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 1,
- "label": "Donor Type",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- }
- ],
- "has_web_view": 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": "2017-12-05 07:04:36.757595",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Donor Type",
- "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": "Non Profit Manager",
- "set_user_permissions": 0,
- "share": 1,
- "submit": 0,
- "write": 1
- }
- ],
- "quick_entry": 1,
- "read_only": 0,
- "read_only_onload": 0,
- "restrict_to_domain": "Non Profit",
- "show_name_in_global_search": 0,
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_changes": 1,
- "track_seen": 0
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/donor_type/donor_type.py b/erpnext/non_profit/doctype/donor_type/donor_type.py
deleted file mode 100644
index 17dca89..0000000
--- a/erpnext/non_profit/doctype/donor_type/donor_type.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-from frappe.model.document import Document
-
-
-class DonorType(Document):
- pass
diff --git a/erpnext/non_profit/doctype/donor_type/test_donor_type.py b/erpnext/non_profit/doctype/donor_type/test_donor_type.py
deleted file mode 100644
index d433733..0000000
--- a/erpnext/non_profit/doctype/donor_type/test_donor_type.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-
-class TestDonorType(unittest.TestCase):
- pass
diff --git a/erpnext/non_profit/doctype/grant_application/__init__.py b/erpnext/non_profit/doctype/grant_application/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/grant_application/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/grant_application/grant_application.js b/erpnext/non_profit/doctype/grant_application/grant_application.js
deleted file mode 100644
index 70f319b..0000000
--- a/erpnext/non_profit/doctype/grant_application/grant_application.js
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Grant Application', {
- refresh: function(frm) {
- frappe.dynamic_link = {doc: frm.doc, fieldname: 'name', doctype: 'Grant Application'};
-
- frm.toggle_display(['address_html','contact_html'], !frm.doc.__islocal);
-
- if(!frm.doc.__islocal) {
- frappe.contacts.render_address_and_contact(frm);
- } else {
- frappe.contacts.clear_address_and_contact(frm);
- }
-
- if(frm.doc.status == 'Received' && !frm.doc.email_notification_sent){
- frm.add_custom_button(__("Send Grant Review Email"), function() {
- frappe.call({
- method: "erpnext.non_profit.doctype.grant_application.grant_application.send_grant_review_emails",
- args: {
- grant_application: frm.doc.name
- }
- });
- });
- }
- }
-});
diff --git a/erpnext/non_profit/doctype/grant_application/grant_application.json b/erpnext/non_profit/doctype/grant_application/grant_application.json
deleted file mode 100644
index 2eb2087..0000000
--- a/erpnext/non_profit/doctype/grant_application/grant_application.json
+++ /dev/null
@@ -1,851 +0,0 @@
-{
- "allow_copy": 0,
- "allow_guest_to_view": 1,
- "allow_import": 0,
- "allow_rename": 0,
- "autoname": "",
- "beta": 0,
- "creation": "2017-09-21 12:02:01.206913",
- "custom": 0,
- "docstatus": 0,
- "doctype": "DocType",
- "document_type": "",
- "editable_grid": 1,
- "engine": "InnoDB",
- "fields": [
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "applicant_type",
- "fieldtype": "Select",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Applicant Type",
- "length": 0,
- "no_copy": 0,
- "options": "Individual\nOrganization",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "applicant_name",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Name",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "depends_on": "eval:doc.applicant_type=='Organization'",
- "fieldname": "contact_person",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Contact Person",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "email",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Email",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "column_break_5",
- "fieldtype": "Column Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "default": "Open",
- "fieldname": "status",
- "fieldtype": "Select",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Status",
- "length": 0,
- "no_copy": 0,
- "options": "Open\nReceived\nIn Progress\nApproved\nRejected\nExpired\nWithdrawn",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "website_url",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Website URL",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "company",
- "fieldtype": "Link",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Company",
- "length": 0,
- "no_copy": 0,
- "options": "Company",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "address_contacts",
- "fieldtype": "Section Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Address and Contact",
- "length": 0,
- "no_copy": 0,
- "options": "fa fa-map-marker",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "address_html",
- "fieldtype": "HTML",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Address HTML",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "column_break_9",
- "fieldtype": "Column Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "contact_html",
- "fieldtype": "HTML",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Contact HTML",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "grant_application_details",
- "fieldtype": "Section Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Grant Application Details ",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "grant_description",
- "fieldtype": "Long Text",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Grant Description",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "section_break_15",
- "fieldtype": "Section Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "amount",
- "fieldtype": "Currency",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Requested Amount",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "has_any_past_grant_record",
- "fieldtype": "Check",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Has any past Grant Record",
- "length": 0,
- "no_copy": 0,
- "options": "",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "column_break_17",
- "fieldtype": "Column Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "route",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Route",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "published",
- "fieldtype": "Check",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Show on Website",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "assessment_result",
- "fieldtype": "Section Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Assessment Result",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "assessment_mark",
- "fieldtype": "Float",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Assessment Mark (Out of 10)",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "note",
- "fieldtype": "Small Text",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Note",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "column_break_24",
- "fieldtype": "Column Break",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "assessment_manager",
- "fieldtype": "Link",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Assessment Manager",
- "length": 0,
- "no_copy": 0,
- "options": "User",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- },
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "email_notification_sent",
- "fieldtype": "Check",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 0,
- "in_standard_filter": 0,
- "label": "Email Notification Sent",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 1,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- }
- ],
- "has_web_view": 1,
- "hide_heading": 0,
- "hide_toolbar": 0,
- "idx": 0,
- "image_field": "",
- "image_view": 0,
- "in_create": 0,
- "is_published_field": "published",
- "is_submittable": 0,
- "issingle": 0,
- "istable": 0,
- "max_attachments": 0,
- "modified": "2017-12-06 12:39:57.677899",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Grant Application",
- "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": "Non Profit Manager",
- "set_user_permissions": 0,
- "share": 1,
- "submit": 0,
- "write": 1
- }
- ],
- "quick_entry": 0,
- "read_only": 0,
- "read_only_onload": 0,
- "restrict_to_domain": "Non Profit",
- "route": "grant-application",
- "show_name_in_global_search": 0,
- "sort_field": "modified",
- "sort_order": "DESC",
- "title_field": "applicant_name",
- "track_changes": 1,
- "track_seen": 0
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/grant_application/grant_application.py b/erpnext/non_profit/doctype/grant_application/grant_application.py
deleted file mode 100644
index cc5e1b1..0000000
--- a/erpnext/non_profit/doctype/grant_application/grant_application.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-import frappe
-from frappe import _
-from frappe.contacts.address_and_contact import load_address_and_contact
-from frappe.utils import get_url
-from frappe.website.website_generator import WebsiteGenerator
-
-
-class GrantApplication(WebsiteGenerator):
- _website = frappe._dict(
- condition_field = "published",
- )
-
- def validate(self):
- if not self.route: #pylint: disable=E0203
- self.route = 'grant-application/' + self.scrub(self.name)
-
- def onload(self):
- """Load address and contacts in `__onload`"""
- load_address_and_contact(self)
-
- def get_context(self, context):
- context.no_cache = True
- context.show_sidebar = True
- context.parents = [dict(label='View All Grant Applications',
- route='grant-application', title='View Grants')]
-
-def get_list_context(context):
- context.allow_guest = True
- context.no_cache = True
- context.no_breadcrumbs = True
- context.show_sidebar = True
- context.order_by = 'creation desc'
- context.introduction ='''<a class="btn btn-primary" href="/my-grant?new=1">
- Apply for new Grant Application</a>'''
-
-@frappe.whitelist()
-def send_grant_review_emails(grant_application):
- grant = frappe.get_doc("Grant Application", grant_application)
- url = get_url('grant-application/{0}'.format(grant_application))
- frappe.sendmail(
- recipients= grant.assessment_manager,
- sender=frappe.session.user,
- subject='Grant Application for {0}'.format(grant.applicant_name),
- message='<p> Please Review this grant application</p><br>' + url,
- reference_doctype=grant.doctype,
- reference_name=grant.name
- )
-
- grant.status = 'In Progress'
- grant.email_notification_sent = 1
- grant.save()
- frappe.db.commit()
-
- frappe.msgprint(_("Review Invitation Sent"))
diff --git a/erpnext/non_profit/doctype/grant_application/templates/grant_application.html b/erpnext/non_profit/doctype/grant_application/templates/grant_application.html
deleted file mode 100644
index 52e8469..0000000
--- a/erpnext/non_profit/doctype/grant_application/templates/grant_application.html
+++ /dev/null
@@ -1,68 +0,0 @@
-{% extends "templates/web.html" %}
-
-{% block page_content %}
- <h1>{{ applicant_name }}</h1>
- {% if frappe.user == owner %}
- <p><a class='btn btn-primary btn-sm' href="/my-grant?name={{ name }}">Edit Grant</a></p>
- {% endif %}
- <br>
- <table class='table table-bordered small' style='max-width: 400px; margin-bottom: 0px;'>
- <tr>
- <td style='width: 38.2%'>Organization/Indvidual</td>
- <td>{{ applicant_type }}</td>
- </tr>
- <tr>
- <td>Grant Applicant Name</td>
- <td>{{ applicant_name}}</td>
- </tr>
- <tr>
- <td>Date</td>
- <td>{{ frappe.format_date(creation) }}</td>
- </tr>
- <tr>
- <td>Status</td>
- <td>{{ status }}</td>
- </tr>
- <tr>
- <td>Email</td>
- <td>{{ email }}</td>
- </tr>
- </table>
- <h2>Q. Please outline your current situation and why you are applying for a grant?</h2>
- <p> {{ grant_description }}</p>
- <h2>Q. Requested grant amount</h2>
- <p>{{ amount }}</p>
- <h2>Q. Have you recevied grant from us before?</h2>
- <p>{{ has_any_past_grant_record }}</p>
- <h3>Contact</h3>
- {% if frappe.user != 'Guest' %}
- <table class='table table-bordered small' style='max-width: 400px; margin-bottom: 0px;'>
- {% if contact_person %}
- <tr>
- <td style='width: 38.2%'>Contact Person</td>
- <td>{{ contact_person }}</td>
- </tr>
- {% endif %}
- <tr>
- <td style='width: 38.2%'>Email</td>
- <td>{{ email }}</td>
- </tr>
- </table>
- {% else %}
- <p><a href="/login">You must register and login to view contact details</a></p>
- {% endif %}
- <br>
- {% if frappe.session.user == assessment_manager %}
- {% if assessment_scale %}
- <p> Assessment Review done </p>
- {% endif %}
- {% else %}
- <p><br><a href="/my-grant?new=1" class='btn btn-primary'>Post a New Grant</a></p>
- {% endif %}
-{% endblock %}
-{% block style %}
-<link type="text/css" rel="stylesheet" href="/assets/css/non-profits.css">
-<style>
-{% if style is defined %}{{ style }}{% endif %}
-</style>
-{% endblock %}
diff --git a/erpnext/non_profit/doctype/grant_application/templates/grant_application_row.html b/erpnext/non_profit/doctype/grant_application/templates/grant_application_row.html
deleted file mode 100644
index e375b16..0000000
--- a/erpnext/non_profit/doctype/grant_application/templates/grant_application_row.html
+++ /dev/null
@@ -1,11 +0,0 @@
-{% if doc.published %}
- <div style='margin-bottom: 30px; max-width: 600px;'
- class='with-border clickable'>
- <a href="/{{ doc.route }}">
- <h3 style='margin-top: 0px;'>{{ doc.name }}</h3>
- <p>
- <span class='label'>{{ frappe.format_date(doc.creation) }}</span>
- </p>
- </a>
- </div>
-{% endif %}
diff --git a/erpnext/non_profit/doctype/grant_application/test_grant_application.py b/erpnext/non_profit/doctype/grant_application/test_grant_application.py
deleted file mode 100644
index ef267d7..0000000
--- a/erpnext/non_profit/doctype/grant_application/test_grant_application.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-
-class TestGrantApplication(unittest.TestCase):
- pass
diff --git a/erpnext/non_profit/doctype/member/__init__.py b/erpnext/non_profit/doctype/member/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/member/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/member/member.js b/erpnext/non_profit/doctype/member/member.js
deleted file mode 100644
index e58ec0f..0000000
--- a/erpnext/non_profit/doctype/member/member.js
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Member', {
- setup: function(frm) {
- frappe.db.get_single_value('Non Profit Settings', 'enable_razorpay_for_memberships').then(val => {
- if (val && (frm.doc.subscription_id || frm.doc.customer_id)) {
- frm.set_df_property('razorpay_details_section', 'hidden', false);
- }
- })
- },
-
- refresh: function(frm) {
-
- frappe.dynamic_link = {doc: frm.doc, fieldname: 'name', doctype: 'Member'};
-
- frm.toggle_display(['address_html','contact_html'], !frm.doc.__islocal);
-
- if(!frm.doc.__islocal) {
- frappe.contacts.render_address_and_contact(frm);
-
- // custom buttons
- frm.add_custom_button(__('Accounting Ledger'), function() {
- frappe.set_route('query-report', 'General Ledger',
- {party_type:'Member', party:frm.doc.name});
- });
-
- frm.add_custom_button(__('Accounts Receivable'), function() {
- frappe.set_route('query-report', 'Accounts Receivable', {member:frm.doc.name});
- });
-
- if (!frm.doc.customer) {
- frm.add_custom_button(__('Create Customer'), () => {
- frm.call('make_customer_and_link').then(() => {
- frm.reload_doc();
- });
- });
- }
-
- // indicator
- erpnext.utils.set_party_dashboard_indicators(frm);
-
- } else {
- frappe.contacts.clear_address_and_contact(frm);
- }
-
- frappe.call({
- method:"frappe.client.get_value",
- args:{
- 'doctype':"Membership",
- 'filters':{'member': frm.doc.name},
- 'fieldname':[
- 'to_date'
- ]
- },
- callback: function (data) {
- if(data.message) {
- frappe.model.set_value(frm.doctype,frm.docname,
- "membership_expiry_date", data.message.to_date);
- }
- }
- });
- }
-});
diff --git a/erpnext/non_profit/doctype/member/member.json b/erpnext/non_profit/doctype/member/member.json
deleted file mode 100644
index 7c1baf1..0000000
--- a/erpnext/non_profit/doctype/member/member.json
+++ /dev/null
@@ -1,210 +0,0 @@
-{
- "actions": [],
- "allow_rename": 1,
- "autoname": "naming_series:",
- "creation": "2017-09-11 09:24:52.898356",
- "doctype": "DocType",
- "editable_grid": 1,
- "engine": "InnoDB",
- "field_order": [
- "naming_series",
- "member_name",
- "membership_expiry_date",
- "column_break_5",
- "membership_type",
- "email_id",
- "image",
- "customer_section",
- "customer",
- "customer_name",
- "supplier_section",
- "supplier",
- "address_contacts",
- "address_html",
- "column_break_9",
- "contact_html",
- "razorpay_details_section",
- "subscription_id",
- "customer_id",
- "subscription_status",
- "column_break_21",
- "subscription_start",
- "subscription_end"
- ],
- "fields": [
- {
- "fieldname": "naming_series",
- "fieldtype": "Select",
- "label": "Series",
- "options": "NPO-MEM-.YYYY.-",
- "reqd": 1
- },
- {
- "fieldname": "member_name",
- "fieldtype": "Data",
- "in_list_view": 1,
- "label": "Member Name",
- "reqd": 1
- },
- {
- "fieldname": "membership_expiry_date",
- "fieldtype": "Date",
- "label": "Membership Expiry Date"
- },
- {
- "fieldname": "column_break_5",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "membership_type",
- "fieldtype": "Link",
- "in_list_view": 1,
- "label": "Membership Type",
- "options": "Membership Type",
- "reqd": 1
- },
- {
- "fieldname": "image",
- "fieldtype": "Attach Image",
- "hidden": 1,
- "label": "Image",
- "no_copy": 1,
- "print_hide": 1
- },
- {
- "collapsible": 1,
- "fieldname": "customer_section",
- "fieldtype": "Section Break",
- "label": "Customer"
- },
- {
- "fieldname": "customer",
- "fieldtype": "Link",
- "label": "Customer",
- "options": "Customer"
- },
- {
- "fetch_from": "customer.customer_name",
- "fieldname": "customer_name",
- "fieldtype": "Data",
- "label": "Customer Name",
- "read_only": 1
- },
- {
- "collapsible": 1,
- "fieldname": "supplier_section",
- "fieldtype": "Section Break",
- "label": "Supplier"
- },
- {
- "fieldname": "supplier",
- "fieldtype": "Link",
- "label": "Supplier",
- "options": "Supplier"
- },
- {
- "depends_on": "eval:!doc.__islocal;",
- "fieldname": "address_contacts",
- "fieldtype": "Section Break",
- "label": "Address and Contact",
- "options": "fa fa-map-marker"
- },
- {
- "fieldname": "address_html",
- "fieldtype": "HTML",
- "label": "Address HTML"
- },
- {
- "fieldname": "column_break_9",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "contact_html",
- "fieldtype": "HTML",
- "label": "Contact HTML"
- },
- {
- "fieldname": "email_id",
- "fieldtype": "Data",
- "label": "Email Address",
- "options": "Email"
- },
- {
- "fieldname": "subscription_id",
- "fieldtype": "Data",
- "label": "Subscription ID",
- "read_only": 1
- },
- {
- "fieldname": "customer_id",
- "fieldtype": "Data",
- "label": "Customer ID",
- "read_only": 1
- },
- {
- "fieldname": "razorpay_details_section",
- "fieldtype": "Section Break",
- "hidden": 1,
- "label": "Razorpay Details"
- },
- {
- "fieldname": "column_break_21",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "subscription_start",
- "fieldtype": "Date",
- "label": "Subscription Start "
- },
- {
- "fieldname": "subscription_end",
- "fieldtype": "Date",
- "label": "Subscription End"
- },
- {
- "fieldname": "subscription_status",
- "fieldtype": "Select",
- "label": "Subscription Status",
- "options": "\nActive\nHalted"
- }
- ],
- "image_field": "image",
- "links": [],
- "modified": "2021-07-11 14:27:26.368039",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Member",
- "owner": "Administrator",
- "permissions": [
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "export": 1,
- "print": 1,
- "read": 1,
- "report": 1,
- "role": "Non Profit Manager",
- "share": 1,
- "write": 1
- },
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "export": 1,
- "print": 1,
- "read": 1,
- "report": 1,
- "role": "Non Profit Member",
- "share": 1,
- "write": 1
- }
- ],
- "quick_entry": 1,
- "restrict_to_domain": "Non Profit",
- "sort_field": "modified",
- "sort_order": "DESC",
- "title_field": "member_name",
- "track_changes": 1
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/member/member.py b/erpnext/non_profit/doctype/member/member.py
deleted file mode 100644
index 4d80e57..0000000
--- a/erpnext/non_profit/doctype/member/member.py
+++ /dev/null
@@ -1,185 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-import frappe
-from frappe import _
-from frappe.contacts.address_and_contact import load_address_and_contact
-from frappe.integrations.utils import get_payment_gateway_controller
-from frappe.model.document import Document
-from frappe.utils import cint, get_link_to_form
-
-from erpnext.non_profit.doctype.membership_type.membership_type import get_membership_type
-
-
-class Member(Document):
- def onload(self):
- """Load address and contacts in `__onload`"""
- load_address_and_contact(self)
-
-
- def validate(self):
- if self.email_id:
- self.validate_email_type(self.email_id)
-
- def validate_email_type(self, email):
- from frappe.utils import validate_email_address
- validate_email_address(email.strip(), True)
-
- def setup_subscription(self):
- non_profit_settings = frappe.get_doc('Non Profit Settings')
- if not non_profit_settings.enable_razorpay_for_memberships:
- frappe.throw(_('Please check Enable Razorpay for Memberships in {0} to setup subscription')).format(
- get_link_to_form('Non Profit Settings', 'Non Profit Settings'))
-
- controller = get_payment_gateway_controller("Razorpay")
- settings = controller.get_settings({})
-
- plan_id = frappe.get_value("Membership Type", self.membership_type, "razorpay_plan_id")
-
- if not plan_id:
- frappe.throw(_("Please setup Razorpay Plan ID"))
-
- subscription_details = {
- "plan_id": plan_id,
- "billing_frequency": cint(non_profit_settings.billing_frequency),
- "customer_notify": 1
- }
-
- args = {
- 'subscription_details': subscription_details
- }
-
- subscription = controller.setup_subscription(settings, **args)
-
- return subscription
-
- @frappe.whitelist()
- def make_customer_and_link(self):
- if self.customer:
- frappe.msgprint(_("A customer is already linked to this Member"))
-
- customer = create_customer(frappe._dict({
- 'fullname': self.member_name,
- 'email': self.email_id,
- 'phone': None
- }))
-
- self.customer = customer
- self.save()
- frappe.msgprint(_("Customer {0} has been created succesfully.").format(self.customer))
-
-
-def get_or_create_member(user_details):
- member_list = frappe.get_all("Member", filters={'email': user_details.email, 'membership_type': user_details.plan_id})
- if member_list and member_list[0]:
- return member_list[0]['name']
- else:
- return create_member(user_details)
-
-def create_member(user_details):
- user_details = frappe._dict(user_details)
- member = frappe.new_doc("Member")
- member.update({
- "member_name": user_details.fullname,
- "email_id": user_details.email,
- "pan_number": user_details.pan or None,
- "membership_type": user_details.plan_id,
- "customer_id": user_details.customer_id or None,
- "subscription_id": user_details.subscription_id or None,
- "subscription_status": user_details.subscription_status or ""
- })
-
- member.insert(ignore_permissions=True)
- member.customer = create_customer(user_details, member.name)
- member.save(ignore_permissions=True)
-
- return member
-
-def create_customer(user_details, member=None):
- customer = frappe.new_doc("Customer")
- customer.customer_name = user_details.fullname
- customer.customer_type = "Individual"
- customer.flags.ignore_mandatory = True
- customer.insert(ignore_permissions=True)
-
- try:
- contact = frappe.new_doc("Contact")
- contact.first_name = user_details.fullname
- if user_details.mobile:
- contact.add_phone(user_details.mobile, is_primary_phone=1, is_primary_mobile_no=1)
- if user_details.email:
- contact.add_email(user_details.email, is_primary=1)
- contact.insert(ignore_permissions=True)
-
- contact.append("links", {
- "link_doctype": "Customer",
- "link_name": customer.name
- })
-
- if member:
- contact.append("links", {
- "link_doctype": "Member",
- "link_name": member
- })
-
- contact.save(ignore_permissions=True)
-
- except frappe.DuplicateEntryError:
- return customer.name
-
- except Exception as e:
- frappe.log_error(frappe.get_traceback(), _("Contact Creation Failed"))
- pass
-
- return customer.name
-
-@frappe.whitelist(allow_guest=True)
-def create_member_subscription_order(user_details):
- """Create Member subscription and order for payment
-
- Args:
- user_details (TYPE): Description
-
- Returns:
- Dictionary: Dictionary with subscription details
- {
- 'subscription_details': {
- 'plan_id': 'plan_EXwyxDYDCj3X4v',
- 'billing_frequency': 24,
- 'customer_notify': 1
- },
- 'subscription_id': 'sub_EZycCvXFvqnC6p'
- }
- """
-
- user_details = frappe._dict(user_details)
- member = get_or_create_member(user_details)
-
- subscription = member.setup_subscription()
-
- member.subscription_id = subscription.get('subscription_id')
- member.save(ignore_permissions=True)
-
- return subscription
-
-@frappe.whitelist()
-def register_member(fullname, email, rzpay_plan_id, subscription_id, pan=None, mobile=None):
- plan = get_membership_type(rzpay_plan_id)
- if not plan:
- raise frappe.DoesNotExistError
-
- member = frappe.db.exists("Member", {'email': email, 'subscription_id': subscription_id })
- if member:
- return member
- else:
- member = create_member(dict(
- fullname=fullname,
- email=email,
- plan_id=plan,
- subscription_id=subscription_id,
- pan=pan,
- mobile=mobile
- ))
-
- return member.name
diff --git a/erpnext/non_profit/doctype/member/member_dashboard.py b/erpnext/non_profit/doctype/member/member_dashboard.py
deleted file mode 100644
index 0e31e3c..0000000
--- a/erpnext/non_profit/doctype/member/member_dashboard.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from frappe import _
-
-
-def get_data():
- return {
- 'heatmap': True,
- 'heatmap_message': _('Member Activity'),
- 'fieldname': 'member',
- 'non_standard_fieldnames': {
- 'Bank Account': 'party'
- },
- 'transactions': [
- {
- 'label': _('Membership Details'),
- 'items': ['Membership']
- },
- {
- 'label': _('Fee'),
- 'items': ['Bank Account']
- }
- ]
- }
diff --git a/erpnext/non_profit/doctype/member/member_list.js b/erpnext/non_profit/doctype/member/member_list.js
deleted file mode 100644
index 8e41e7f..0000000
--- a/erpnext/non_profit/doctype/member/member_list.js
+++ /dev/null
@@ -1,3 +0,0 @@
-frappe.listview_settings['Member'] = {
- add_fields: ["member_name", "membership_type", "image"],
-};
diff --git a/erpnext/non_profit/doctype/member/test_member.py b/erpnext/non_profit/doctype/member/test_member.py
deleted file mode 100644
index 46f14ed..0000000
--- a/erpnext/non_profit/doctype/member/test_member.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-
-class TestMember(unittest.TestCase):
- pass
diff --git a/erpnext/non_profit/doctype/membership/__init__.py b/erpnext/non_profit/doctype/membership/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/membership/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/membership/membership.js b/erpnext/non_profit/doctype/membership/membership.js
deleted file mode 100644
index 3187204..0000000
--- a/erpnext/non_profit/doctype/membership/membership.js
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Membership', {
- setup: function(frm) {
- frappe.db.get_single_value("Non Profit Settings", "enable_razorpay_for_memberships").then(val => {
- if (val) frm.set_df_property("razorpay_details_section", "hidden", false);
- })
- },
-
- refresh: function(frm) {
- if (frm.doc.__islocal)
- return;
-
- !frm.doc.invoice && frm.add_custom_button("Generate Invoice", () => {
- frm.call({
- doc: frm.doc,
- method: "generate_invoice",
- args: {save: true},
- freeze: true,
- freeze_message: __("Creating Membership Invoice"),
- callback: function(r) {
- if (r.invoice)
- frm.reload_doc();
- }
- });
- });
-
- frappe.db.get_single_value("Non Profit Settings", "send_email").then(val => {
- if (val) frm.add_custom_button("Send Acknowledgement", () => {
- frm.call("send_acknowlement").then(() => {
- frm.reload_doc();
- });
- });
- })
- },
-
- onload: function(frm) {
- frm.add_fetch("membership_type", "amount", "amount");
- }
-});
diff --git a/erpnext/non_profit/doctype/membership/membership.json b/erpnext/non_profit/doctype/membership/membership.json
deleted file mode 100644
index 11d32f9..0000000
--- a/erpnext/non_profit/doctype/membership/membership.json
+++ /dev/null
@@ -1,184 +0,0 @@
-{
- "actions": [],
- "autoname": "NPO-MSH-.YYYY.-.#####",
- "creation": "2017-09-11 11:39:18.492184",
- "doctype": "DocType",
- "editable_grid": 1,
- "engine": "InnoDB",
- "field_order": [
- "member",
- "member_name",
- "membership_type",
- "column_break_3",
- "company",
- "membership_status",
- "membership_validity_section",
- "from_date",
- "to_date",
- "column_break_8",
- "member_since_date",
- "payment_details",
- "paid",
- "currency",
- "amount",
- "invoice",
- "razorpay_details_section",
- "subscription_id",
- "payment_id"
- ],
- "fields": [
- {
- "fieldname": "member",
- "fieldtype": "Link",
- "label": "Member",
- "options": "Member"
- },
- {
- "fieldname": "membership_type",
- "fieldtype": "Link",
- "in_list_view": 1,
- "label": "Membership Type",
- "options": "Membership Type",
- "reqd": 1
- },
- {
- "fieldname": "column_break_3",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "membership_status",
- "fieldtype": "Select",
- "in_list_view": 1,
- "in_standard_filter": 1,
- "label": "Membership Status",
- "options": "New\nCurrent\nExpired\nPending\nCancelled"
- },
- {
- "fieldname": "membership_validity_section",
- "fieldtype": "Section Break",
- "label": "Validity"
- },
- {
- "fieldname": "from_date",
- "fieldtype": "Date",
- "in_list_view": 1,
- "label": "From",
- "reqd": 1
- },
- {
- "fieldname": "to_date",
- "fieldtype": "Date",
- "in_list_view": 1,
- "label": "To",
- "reqd": 1
- },
- {
- "fieldname": "column_break_8",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "member_since_date",
- "fieldtype": "Date",
- "label": "Member Since"
- },
- {
- "fieldname": "payment_details",
- "fieldtype": "Section Break",
- "label": "Payment Details"
- },
- {
- "default": "0",
- "fieldname": "paid",
- "fieldtype": "Check",
- "label": "Paid"
- },
- {
- "fieldname": "currency",
- "fieldtype": "Link",
- "label": "Currency",
- "options": "Currency"
- },
- {
- "fieldname": "amount",
- "fieldtype": "Float",
- "label": "Amount"
- },
- {
- "fieldname": "razorpay_details_section",
- "fieldtype": "Section Break",
- "hidden": 1,
- "label": "Razorpay Details"
- },
- {
- "fieldname": "subscription_id",
- "fieldtype": "Data",
- "label": "Subscription ID",
- "read_only": 1
- },
- {
- "fieldname": "payment_id",
- "fieldtype": "Data",
- "label": "Payment ID",
- "read_only": 1
- },
- {
- "fieldname": "invoice",
- "fieldtype": "Link",
- "label": "Invoice",
- "options": "Sales Invoice"
- },
- {
- "fetch_from": "member.member_name",
- "fieldname": "member_name",
- "fieldtype": "Data",
- "label": "Member Name",
- "read_only": 1
- },
- {
- "fieldname": "company",
- "fieldtype": "Link",
- "label": "Company",
- "options": "Company",
- "reqd": 1
- }
- ],
- "index_web_pages_for_search": 1,
- "links": [],
- "modified": "2021-02-19 14:33:44.925122",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Membership",
- "owner": "Administrator",
- "permissions": [
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "export": 1,
- "print": 1,
- "read": 1,
- "report": 1,
- "role": "Non Profit Manager",
- "share": 1,
- "write": 1
- },
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "export": 1,
- "print": 1,
- "read": 1,
- "report": 1,
- "role": "Non Profit Member",
- "share": 1,
- "write": 1
- }
- ],
- "restrict_to_domain": "Non Profit",
- "search_fields": "member, member_name",
- "sort_field": "modified",
- "sort_order": "DESC",
- "title_field": "member_name",
- "track_changes": 1
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/membership/membership.py b/erpnext/non_profit/doctype/membership/membership.py
deleted file mode 100644
index f9b295a..0000000
--- a/erpnext/non_profit/doctype/membership/membership.py
+++ /dev/null
@@ -1,415 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-import json
-from datetime import datetime
-
-import frappe
-from frappe import _
-from frappe.email import sendmail_to_system_managers
-from frappe.model.document import Document
-from frappe.utils import add_days, add_months, add_years, get_link_to_form, getdate, nowdate
-
-import erpnext
-from erpnext.non_profit.doctype.member.member import create_member
-
-
-class Membership(Document):
- def validate(self):
- if not self.member or not frappe.db.exists("Member", self.member):
- # for web forms
- user_type = frappe.db.get_value("User", frappe.session.user, "user_type")
- if user_type == "Website User":
- self.create_member_from_website_user()
- else:
- frappe.throw(_("Please select a Member"))
-
- self.validate_membership_period()
-
- def create_member_from_website_user(self):
- member_name = frappe.get_value("Member", dict(email_id=frappe.session.user))
-
- if not member_name:
- user = frappe.get_doc("User", frappe.session.user)
- member = frappe.get_doc(dict(
- doctype="Member",
- email_id=frappe.session.user,
- membership_type=self.membership_type,
- member_name=user.get_fullname()
- )).insert(ignore_permissions=True)
- member_name = member.name
-
- if self.get("__islocal"):
- self.member = member_name
-
- def validate_membership_period(self):
- # get last membership (if active)
- last_membership = erpnext.get_last_membership(self.member)
-
- # if person applied for offline membership
- if last_membership and last_membership.name != self.name and not frappe.session.user == "Administrator":
- # if last membership does not expire in 30 days, then do not allow to renew
- if getdate(add_days(last_membership.to_date, -30)) > getdate(nowdate()) :
- frappe.throw(_("You can only renew if your membership expires within 30 days"))
-
- self.from_date = add_days(last_membership.to_date, 1)
- elif frappe.session.user == "Administrator":
- self.from_date = self.from_date
- else:
- self.from_date = nowdate()
-
- if frappe.db.get_single_value("Non Profit Settings", "billing_cycle") == "Yearly":
- self.to_date = add_years(self.from_date, 1)
- else:
- self.to_date = add_months(self.from_date, 1)
-
- def on_payment_authorized(self, status_changed_to=None):
- if status_changed_to not in ("Completed", "Authorized"):
- return
- self.load_from_db()
- self.db_set("paid", 1)
- settings = frappe.get_doc("Non Profit Settings")
- if settings.allow_invoicing and settings.automate_membership_invoicing:
- self.generate_invoice(with_payment_entry=settings.automate_membership_payment_entries, save=True)
-
-
- @frappe.whitelist()
- def generate_invoice(self, save=True, with_payment_entry=False):
- if not (self.paid or self.currency or self.amount):
- frappe.throw(_("The payment for this membership is not paid. To generate invoice fill the payment details"))
-
- if self.invoice:
- frappe.throw(_("An invoice is already linked to this document"))
-
- member = frappe.get_doc("Member", self.member)
- if not member.customer:
- frappe.throw(_("No customer linked to member {0}").format(frappe.bold(self.member)))
-
- plan = frappe.get_doc("Membership Type", self.membership_type)
- settings = frappe.get_doc("Non Profit Settings")
- self.validate_membership_type_and_settings(plan, settings)
-
- invoice = make_invoice(self, member, plan, settings)
- self.reload()
- self.invoice = invoice.name
-
- if with_payment_entry:
- self.make_payment_entry(settings, invoice)
-
- if save:
- self.save()
-
- return invoice
-
- def validate_membership_type_and_settings(self, plan, settings):
- settings_link = get_link_to_form("Membership Type", self.membership_type)
-
- if not settings.membership_debit_account:
- frappe.throw(_("You need to set <b>Debit Account</b> in {0}").format(settings_link))
-
- if not settings.company:
- frappe.throw(_("You need to set <b>Default Company</b> for invoicing in {0}").format(settings_link))
-
- if not plan.linked_item:
- frappe.throw(_("Please set a Linked Item for the Membership Type {0}").format(
- get_link_to_form("Membership Type", self.membership_type)))
-
- def make_payment_entry(self, settings, invoice):
- if not settings.membership_payment_account:
- frappe.throw(_("You need to set <b>Payment Account</b> for Membership in {0}").format(
- get_link_to_form("Non Profit Settings", "Non Profit Settings")))
-
- from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
- frappe.flags.ignore_account_permission = True
- pe = get_payment_entry(dt="Sales Invoice", dn=invoice.name, bank_amount=invoice.grand_total)
- frappe.flags.ignore_account_permission=False
- pe.paid_to = settings.membership_payment_account
- pe.reference_no = self.name
- pe.reference_date = getdate()
- pe.flags.ignore_mandatory = True
- pe.save()
- pe.submit()
-
- @frappe.whitelist()
- def send_acknowlement(self):
- settings = frappe.get_doc("Non Profit Settings")
- if not settings.send_email:
- frappe.throw(_("You need to enable <b>Send Acknowledge Email</b> in {0}").format(
- get_link_to_form("Non Profit Settings", "Non Profit Settings")))
-
- member = frappe.get_doc("Member", self.member)
- if not member.email_id:
- frappe.throw(_("Email address of member {0} is missing").format(frappe.utils.get_link_to_form("Member", self.member)))
-
- plan = frappe.get_doc("Membership Type", self.membership_type)
- email = member.email_id
- attachments = [frappe.attach_print("Membership", self.name, print_format=settings.membership_print_format)]
-
- if self.invoice and settings.send_invoice:
- attachments.append(frappe.attach_print("Sales Invoice", self.invoice, print_format=settings.inv_print_format))
-
- email_template = frappe.get_doc("Email Template", settings.email_template)
- context = { "doc": self, "member": member}
-
- email_args = {
- "recipients": [email],
- "message": frappe.render_template(email_template.get("response"), context),
- "subject": frappe.render_template(email_template.get("subject"), context),
- "attachments": attachments,
- "reference_doctype": self.doctype,
- "reference_name": self.name
- }
-
- if not frappe.flags.in_test:
- frappe.enqueue(method=frappe.sendmail, queue="short", timeout=300, is_async=True, **email_args)
- else:
- frappe.sendmail(**email_args)
-
- def generate_and_send_invoice(self):
- self.generate_invoice(save=False)
- self.send_acknowlement()
-
-
-def make_invoice(membership, member, plan, settings):
- invoice = frappe.get_doc({
- "doctype": "Sales Invoice",
- "customer": member.customer,
- "debit_to": settings.membership_debit_account,
- "currency": membership.currency,
- "company": settings.company,
- "is_pos": 0,
- "items": [
- {
- "item_code": plan.linked_item,
- "rate": membership.amount,
- "qty": 1
- }
- ]
- })
- invoice.set_missing_values()
- invoice.insert()
- invoice.submit()
-
- frappe.msgprint(_("Sales Invoice created successfully"))
-
- return invoice
-
-
-def get_member_based_on_subscription(subscription_id, email=None, customer_id=None):
- filters = {"subscription_id": subscription_id}
- if email:
- filters.update({"email_id": email})
- if customer_id:
- filters.update({"customer_id": customer_id})
-
- members = frappe.get_all("Member", filters=filters, order_by="creation desc")
-
- try:
- return frappe.get_doc("Member", members[0]["name"])
- except Exception:
- return None
-
-
-def verify_signature(data, endpoint="Membership"):
- signature = frappe.request.headers.get("X-Razorpay-Signature")
-
- settings = frappe.get_doc("Non Profit Settings")
- key = settings.get_webhook_secret(endpoint)
-
- controller = frappe.get_doc("Razorpay Settings")
-
- controller.verify_signature(data, signature, key)
- frappe.set_user(settings.creation_user)
-
-
-@frappe.whitelist(allow_guest=True)
-def trigger_razorpay_subscription(*args, **kwargs):
- data = frappe.request.get_data(as_text=True)
- data = process_request_data(data)
-
- subscription = data.payload.get("subscription", {}).get("entity", {})
- subscription = frappe._dict(subscription)
-
- payment = data.payload.get("payment", {}).get("entity", {})
- payment = frappe._dict(payment)
-
- try:
- if not data.event == "subscription.charged":
- return
-
- member = get_member_based_on_subscription(subscription.id, payment.email)
- if not member:
- member = create_member(frappe._dict({
- "fullname": payment.email,
- "email": payment.email,
- "plan_id": get_plan_from_razorpay_id(subscription.plan_id)
- }))
-
- member.subscription_id = subscription.id
- member.customer_id = payment.customer_id
-
- if subscription.get("notes"):
- member = get_additional_notes(member, subscription)
-
- company = get_company_for_memberships()
- # Update Membership
- membership = frappe.new_doc("Membership")
- membership.update({
- "company": company,
- "member": member.name,
- "membership_status": "Current",
- "membership_type": member.membership_type,
- "currency": "INR",
- "paid": 1,
- "payment_id": payment.id,
- "from_date": datetime.fromtimestamp(subscription.current_start),
- "to_date": datetime.fromtimestamp(subscription.current_end),
- "amount": payment.amount / 100 # Convert to rupees from paise
- })
- membership.flags.ignore_mandatory = True
- membership.insert()
-
- # Update membership values
- member.subscription_start = datetime.fromtimestamp(subscription.start_at)
- member.subscription_end = datetime.fromtimestamp(subscription.end_at)
- member.subscription_status = "Active"
- member.flags.ignore_mandatory = True
- member.save()
-
- settings = frappe.get_doc("Non Profit Settings")
- if settings.allow_invoicing and settings.automate_membership_invoicing:
- membership.reload()
- membership.generate_invoice(with_payment_entry=settings.automate_membership_payment_entries, save=True)
-
- except Exception as e:
- message = "{0}\n\n{1}\n\n{2}: {3}".format(e, frappe.get_traceback(), _("Payment ID"), payment.id)
- log = frappe.log_error(message, _("Error creating membership entry for {0}").format(member.name))
- notify_failure(log)
- return {"status": "Failed", "reason": e}
-
- return {"status": "Success"}
-
-
-@frappe.whitelist(allow_guest=True)
-def update_halted_razorpay_subscription(*args, **kwargs):
- """
- When all retries have been exhausted, Razorpay moves the subscription to the halted state.
- The customer has to manually retry the charge or change the card linked to the subscription,
- for the subscription to move back to the active state.
- """
- if frappe.request:
- data = frappe.request.get_data(as_text=True)
- data = process_request_data(data)
- elif frappe.flags.in_test:
- data = kwargs.get("data")
- data = frappe._dict(data)
- else:
- return
-
- if not data.event == "subscription.halted":
- return
-
- subscription = data.payload.get("subscription", {}).get("entity", {})
- subscription = frappe._dict(subscription)
-
- try:
- member = get_member_based_on_subscription(subscription.id, customer_id=subscription.customer_id)
- if not member:
- frappe.throw(_("Member with Razorpay Subscription ID {0} not found").format(subscription.id))
-
- member.subscription_status = "Halted"
- member.flags.ignore_mandatory = True
- member.save()
-
- if subscription.get("notes"):
- member = get_additional_notes(member, subscription)
-
- except Exception as e:
- message = "{0}\n\n{1}".format(e, frappe.get_traceback())
- log = frappe.log_error(message, _("Error updating halted status for member {0}").format(member.name))
- notify_failure(log)
- return {"status": "Failed", "reason": e}
-
- return {"status": "Success"}
-
-
-def process_request_data(data):
- try:
- verify_signature(data)
- except Exception as e:
- log = frappe.log_error(e, "Membership Webhook Verification Error")
- notify_failure(log)
- return {"status": "Failed", "reason": e}
-
- if isinstance(data, str):
- data = json.loads(data)
- data = frappe._dict(data)
-
- return data
-
-
-def get_company_for_memberships():
- company = frappe.db.get_single_value("Non Profit Settings", "company")
- if not company:
- from erpnext.non_profit.utils import get_company
- company = get_company()
- return company
-
-
-def get_additional_notes(member, subscription):
- if type(subscription.notes) == dict:
- for k, v in subscription.notes.items():
- notes = "\n".join("{}: {}".format(k, v))
-
- # extract member name from notes
- if "name" in k.lower():
- member.update({
- "member_name": subscription.notes.get(k)
- })
-
- # extract pan number from notes
- if "pan" in k.lower():
- member.update({
- "pan_number": subscription.notes.get(k)
- })
-
- member.add_comment("Comment", notes)
-
- elif type(subscription.notes) == str:
- member.add_comment("Comment", subscription.notes)
-
- return member
-
-
-def notify_failure(log):
- try:
- content = """
- Dear System Manager,
- Razorpay webhook for creating renewing membership subscription failed due to some reason.
- Please check the following error log linked below
- Error Log: {0}
- Regards, Administrator
- """.format(get_link_to_form("Error Log", log.name))
-
- sendmail_to_system_managers("[Important] [ERPNext] Razorpay membership webhook failed , please check.", content)
- except Exception:
- pass
-
-
-def get_plan_from_razorpay_id(plan_id):
- plan = frappe.get_all("Membership Type", filters={"razorpay_plan_id": plan_id}, order_by="creation desc")
-
- try:
- return plan[0]["name"]
- except Exception:
- return None
-
-
-def set_expired_status():
- frappe.db.sql("""
- UPDATE
- `tabMembership` SET `membership_status` = 'Expired'
- WHERE
- `membership_status` not in ('Cancelled') AND `to_date` < %s
- """, (nowdate()))
diff --git a/erpnext/non_profit/doctype/membership/membership_list.js b/erpnext/non_profit/doctype/membership/membership_list.js
deleted file mode 100644
index a959159..0000000
--- a/erpnext/non_profit/doctype/membership/membership_list.js
+++ /dev/null
@@ -1,15 +0,0 @@
-frappe.listview_settings['Membership'] = {
- get_indicator: function(doc) {
- if (doc.membership_status == 'New') {
- return [__('New'), 'blue', 'membership_status,=,New'];
- } else if (doc.membership_status === 'Current') {
- return [__('Current'), 'green', 'membership_status,=,Current'];
- } else if (doc.membership_status === 'Pending') {
- return [__('Pending'), 'yellow', 'membership_status,=,Pending'];
- } else if (doc.membership_status === 'Expired') {
- return [__('Expired'), 'grey', 'membership_status,=,Expired'];
- } else {
- return [__('Cancelled'), 'red', 'membership_status,=,Cancelled'];
- }
- }
-};
diff --git a/erpnext/non_profit/doctype/membership/test_membership.py b/erpnext/non_profit/doctype/membership/test_membership.py
deleted file mode 100644
index fbe344c..0000000
--- a/erpnext/non_profit/doctype/membership/test_membership.py
+++ /dev/null
@@ -1,164 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-import frappe
-from frappe.utils import add_months, nowdate
-
-import erpnext
-from erpnext.non_profit.doctype.member.member import create_member
-from erpnext.non_profit.doctype.membership.membership import update_halted_razorpay_subscription
-
-
-class TestMembership(unittest.TestCase):
- def setUp(self):
- plan = setup_membership()
-
- # make test member
- self.member_doc = create_member(
- frappe._dict({
- "fullname": "_Test_Member",
- "email": "_test_member_erpnext@example.com",
- "plan_id": plan.name,
- "subscription_id": "sub_DEX6xcJ1HSW4CR",
- "customer_id": "cust_C0WlbKhp3aLA7W",
- "subscription_status": "Active"
- })
- )
- self.member_doc.make_customer_and_link()
- self.member = self.member_doc.name
-
- def test_auto_generate_invoice_and_payment_entry(self):
- entry = make_membership(self.member)
-
- # Naive test to see if at all invoice was generated and attached to member
- # In any case if details were missing, the invoicing would throw an error
- invoice = entry.generate_invoice(save=True)
- self.assertEqual(invoice.name, entry.invoice)
-
- def test_renew_within_30_days(self):
- # create a membership for two months
- # Should work fine
- make_membership(self.member, { "from_date": nowdate() })
- make_membership(self.member, { "from_date": add_months(nowdate(), 1) })
-
- from frappe.utils.user import add_role
- add_role("test@example.com", "Non Profit Manager")
- frappe.set_user("test@example.com")
-
- # create next membership with expiry not within 30 days
- self.assertRaises(frappe.ValidationError, make_membership, self.member, {
- "from_date": add_months(nowdate(), 2),
- })
-
- frappe.set_user("Administrator")
- # create the same membership but as administrator
- make_membership(self.member, {
- "from_date": add_months(nowdate(), 2),
- "to_date": add_months(nowdate(), 3),
- })
-
- def test_halted_memberships(self):
- make_membership(self.member, {
- "from_date": add_months(nowdate(), 2),
- "to_date": add_months(nowdate(), 3)
- })
-
- self.assertEqual(frappe.db.get_value("Member", self.member, "subscription_status"), "Active")
- payload = get_subscription_payload()
- update_halted_razorpay_subscription(data=payload)
- self.assertEqual(frappe.db.get_value("Member", self.member, "subscription_status"), "Halted")
-
- def tearDown(self):
- frappe.db.rollback()
-
-def set_config(key, value):
- frappe.db.set_value("Non Profit Settings", None, key, value)
-
-def make_membership(member, payload={}):
- data = {
- "doctype": "Membership",
- "member": member,
- "membership_status": "Current",
- "membership_type": "_rzpy_test_milythm",
- "currency": "INR",
- "paid": 1,
- "from_date": nowdate(),
- "amount": 100
- }
- data.update(payload)
- membership = frappe.get_doc(data)
- membership.insert(ignore_permissions=True, ignore_if_duplicate=True)
- return membership
-
-def create_item(item_code):
- if not frappe.db.exists("Item", item_code):
- item = frappe.new_doc("Item")
- item.item_code = item_code
- item.item_name = item_code
- item.stock_uom = "Nos"
- item.description = item_code
- item.item_group = "All Item Groups"
- item.is_stock_item = 0
- item.save()
- else:
- item = frappe.get_doc("Item", item_code)
- return item
-
-def setup_membership():
- # Get default company
- company = frappe.get_doc("Company", erpnext.get_default_company())
-
- # update non profit settings
- settings = frappe.get_doc("Non Profit Settings")
- # Enable razorpay
- settings.enable_razorpay_for_memberships = 1
- settings.billing_cycle = "Monthly"
- settings.billing_frequency = 24
- # Enable invoicing
- settings.allow_invoicing = 1
- settings.automate_membership_payment_entries = 1
- settings.company = company.name
- settings.donation_company = company.name
- settings.membership_payment_account = company.default_cash_account
- settings.membership_debit_account = company.default_receivable_account
- settings.flags.ignore_mandatory = True
- settings.save()
-
- # make test plan
- if not frappe.db.exists("Membership Type", "_rzpy_test_milythm"):
- plan = frappe.new_doc("Membership Type")
- plan.membership_type = "_rzpy_test_milythm"
- plan.amount = 100
- plan.razorpay_plan_id = "_rzpy_test_milythm"
- plan.linked_item = create_item("_Test Item for Non Profit Membership").name
- plan.insert()
- else:
- plan = frappe.get_doc("Membership Type", "_rzpy_test_milythm")
-
- return plan
-
-def get_subscription_payload():
- return {
- "entity": "event",
- "account_id": "acc_BFQ7uQEaa7j2z7",
- "event": "subscription.halted",
- "contains": [
- "subscription"
- ],
- "payload": {
- "subscription": {
- "entity": {
- "id": "sub_DEX6xcJ1HSW4CR",
- "entity": "subscription",
- "plan_id": "_rzpy_test_milythm",
- "customer_id": "cust_C0WlbKhp3aLA7W",
- "status": "halted",
- "notes": {
- "Important": "Notes for Internal Reference"
- },
- }
- }
- }
- }
diff --git a/erpnext/non_profit/doctype/membership_type/__init__.py b/erpnext/non_profit/doctype/membership_type/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/membership_type/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/membership_type/membership_type.js b/erpnext/non_profit/doctype/membership_type/membership_type.js
deleted file mode 100644
index 2f24276..0000000
--- a/erpnext/non_profit/doctype/membership_type/membership_type.js
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Membership Type', {
- refresh: function (frm) {
- frappe.db.get_single_value('Non Profit Settings', 'enable_razorpay_for_memberships').then(val => {
- if (val) frm.set_df_property('razorpay_plan_id', 'hidden', false);
- });
-
- frappe.db.get_single_value('Non Profit Settings', 'allow_invoicing').then(val => {
- if (val) frm.set_df_property('linked_item', 'hidden', false);
- });
-
- frm.set_query('linked_item', () => {
- return {
- filters: {
- is_stock_item: 0
- }
- };
- });
- }
-});
diff --git a/erpnext/non_profit/doctype/membership_type/membership_type.json b/erpnext/non_profit/doctype/membership_type/membership_type.json
deleted file mode 100644
index 6ce1ecd..0000000
--- a/erpnext/non_profit/doctype/membership_type/membership_type.json
+++ /dev/null
@@ -1,71 +0,0 @@
-{
- "actions": [],
- "autoname": "field:membership_type",
- "creation": "2017-09-18 12:56:56.343999",
- "doctype": "DocType",
- "editable_grid": 1,
- "engine": "InnoDB",
- "field_order": [
- "membership_type",
- "amount",
- "razorpay_plan_id",
- "linked_item"
- ],
- "fields": [
- {
- "fieldname": "membership_type",
- "fieldtype": "Data",
- "in_list_view": 1,
- "in_standard_filter": 1,
- "label": "Membership Type",
- "reqd": 1,
- "unique": 1
- },
- {
- "fieldname": "amount",
- "fieldtype": "Float",
- "in_list_view": 1,
- "label": "Amount",
- "reqd": 1
- },
- {
- "fieldname": "razorpay_plan_id",
- "fieldtype": "Data",
- "hidden": 1,
- "label": "Razorpay Plan ID",
- "unique": 1
- },
- {
- "fieldname": "linked_item",
- "fieldtype": "Link",
- "label": "Linked Item",
- "options": "Item",
- "unique": 1
- }
- ],
- "links": [],
- "modified": "2020-08-05 15:21:43.595745",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Membership Type",
- "owner": "Administrator",
- "permissions": [
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "export": 1,
- "print": 1,
- "read": 1,
- "report": 1,
- "role": "Non Profit Manager",
- "share": 1,
- "write": 1
- }
- ],
- "quick_entry": 1,
- "restrict_to_domain": "Non Profit",
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_changes": 1
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/membership_type/membership_type.py b/erpnext/non_profit/doctype/membership_type/membership_type.py
deleted file mode 100644
index b446421..0000000
--- a/erpnext/non_profit/doctype/membership_type/membership_type.py
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-import frappe
-from frappe import _
-from frappe.model.document import Document
-
-
-class MembershipType(Document):
- def validate(self):
- if self.linked_item:
- is_stock_item = frappe.db.get_value("Item", self.linked_item, "is_stock_item")
- if is_stock_item:
- frappe.throw(_("The Linked Item should be a service item"))
-
-def get_membership_type(razorpay_id):
- return frappe.db.exists("Membership Type", {"razorpay_plan_id": razorpay_id})
diff --git a/erpnext/non_profit/doctype/membership_type/test_membership_type.py b/erpnext/non_profit/doctype/membership_type/test_membership_type.py
deleted file mode 100644
index 98bc087..0000000
--- a/erpnext/non_profit/doctype/membership_type/test_membership_type.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-
-class TestMembershipType(unittest.TestCase):
- pass
diff --git a/erpnext/non_profit/doctype/non_profit_settings/__init__.py b/erpnext/non_profit/doctype/non_profit_settings/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/non_profit_settings/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/non_profit_settings/non_profit_settings.js b/erpnext/non_profit/doctype/non_profit_settings/non_profit_settings.js
deleted file mode 100644
index 4c4ca98..0000000
--- a/erpnext/non_profit/doctype/non_profit_settings/non_profit_settings.js
+++ /dev/null
@@ -1,133 +0,0 @@
-// Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on("Non Profit Settings", {
- refresh: function(frm) {
- frm.set_query("inv_print_format", function() {
- return {
- filters: {
- "doc_type": "Sales Invoice"
- }
- };
- });
-
- frm.set_query("membership_print_format", function() {
- return {
- filters: {
- "doc_type": "Membership"
- }
- };
- });
-
- frm.set_query("membership_debit_account", function() {
- return {
- filters: {
- "account_type": "Receivable",
- "is_group": 0,
- "company": frm.doc.company
- }
- };
- });
-
- frm.set_query("donation_debit_account", function() {
- return {
- filters: {
- "account_type": "Receivable",
- "is_group": 0,
- "company": frm.doc.donation_company
- }
- };
- });
-
- frm.set_query("membership_payment_account", function () {
- var account_types = ["Bank", "Cash"];
- return {
- filters: {
- "account_type": ["in", account_types],
- "is_group": 0,
- "company": frm.doc.company
- }
- };
- });
-
- frm.set_query("donation_payment_account", function () {
- var account_types = ["Bank", "Cash"];
- return {
- filters: {
- "account_type": ["in", account_types],
- "is_group": 0,
- "company": frm.doc.donation_company
- }
- };
- });
-
- let docs_url = "https://docs.erpnext.com/docs/user/manual/en/non_profit/membership";
-
- frm.set_intro(__("You can learn more about memberships in the manual. ") + `<a href='${docs_url}'>${__('ERPNext Docs')}</a>`, true);
- frm.trigger("setup_buttons_for_membership");
- frm.trigger("setup_buttons_for_donation");
- },
-
- setup_buttons_for_membership: function(frm) {
- let label;
-
- if (frm.doc.membership_webhook_secret) {
-
- frm.add_custom_button(__("Copy Webhook URL"), () => {
- frappe.utils.copy_to_clipboard(`https://${frappe.boot.sitename}/api/method/erpnext.non_profit.doctype.membership.membership.trigger_razorpay_subscription`);
- }, __("Memberships"));
-
- frm.add_custom_button(__("Revoke Key"), () => {
- frm.call("revoke_key", {
- key: "membership_webhook_secret"
- }).then(() => {
- frm.refresh();
- });
- }, __("Memberships"));
-
- label = __("Regenerate Webhook Secret");
-
- } else {
- label = __("Generate Webhook Secret");
- }
-
- frm.add_custom_button(label, () => {
- frm.call("generate_webhook_secret", {
- field: "membership_webhook_secret"
- }).then(() => {
- frm.refresh();
- });
- }, __("Memberships"));
- },
-
- setup_buttons_for_donation: function(frm) {
- let label;
-
- if (frm.doc.donation_webhook_secret) {
- label = __("Regenerate Webhook Secret");
-
- frm.add_custom_button(__("Copy Webhook URL"), () => {
- frappe.utils.copy_to_clipboard(`https://${frappe.boot.sitename}/api/method/erpnext.non_profit.doctype.donation.donation.capture_razorpay_donations`);
- }, __("Donations"));
-
- frm.add_custom_button(__("Revoke Key"), () => {
- frm.call("revoke_key", {
- key: "donation_webhook_secret"
- }).then(() => {
- frm.refresh();
- });
- }, __("Donations"));
-
- } else {
- label = __("Generate Webhook Secret");
- }
-
- frm.add_custom_button(label, () => {
- frm.call("generate_webhook_secret", {
- field: "donation_webhook_secret"
- }).then(() => {
- frm.refresh();
- });
- }, __("Donations"));
- }
-});
diff --git a/erpnext/non_profit/doctype/non_profit_settings/non_profit_settings.json b/erpnext/non_profit/doctype/non_profit_settings/non_profit_settings.json
deleted file mode 100644
index 25ff0c1..0000000
--- a/erpnext/non_profit/doctype/non_profit_settings/non_profit_settings.json
+++ /dev/null
@@ -1,273 +0,0 @@
-{
- "actions": [],
- "creation": "2020-03-29 12:57:03.005120",
- "doctype": "DocType",
- "editable_grid": 1,
- "engine": "InnoDB",
- "field_order": [
- "enable_razorpay_for_memberships",
- "razorpay_settings_section",
- "billing_cycle",
- "billing_frequency",
- "membership_webhook_secret",
- "column_break_6",
- "allow_invoicing",
- "automate_membership_invoicing",
- "automate_membership_payment_entries",
- "company",
- "membership_debit_account",
- "membership_payment_account",
- "column_break_9",
- "send_email",
- "send_invoice",
- "membership_print_format",
- "inv_print_format",
- "email_template",
- "donation_settings_section",
- "donation_company",
- "default_donor_type",
- "donation_webhook_secret",
- "column_break_22",
- "automate_donation_payment_entries",
- "donation_debit_account",
- "donation_payment_account",
- "section_break_27",
- "creation_user"
- ],
- "fields": [
- {
- "fieldname": "billing_cycle",
- "fieldtype": "Select",
- "label": "Billing Cycle",
- "options": "Monthly\nYearly"
- },
- {
- "depends_on": "eval:doc.enable_razorpay_for_memberships",
- "fieldname": "razorpay_settings_section",
- "fieldtype": "Section Break",
- "label": "RazorPay Settings for Memberships"
- },
- {
- "description": "The number of billing cycles for which the customer should be charged. For example, if a customer is buying a 1-year membership that should be billed on a monthly basis, this value should be 12.",
- "fieldname": "billing_frequency",
- "fieldtype": "Int",
- "label": "Billing Frequency"
- },
- {
- "fieldname": "column_break_6",
- "fieldtype": "Section Break",
- "label": "Membership Invoicing"
- },
- {
- "fieldname": "column_break_9",
- "fieldtype": "Column Break"
- },
- {
- "description": "This company will be set for the Memberships created via webhook.",
- "fieldname": "company",
- "fieldtype": "Link",
- "in_list_view": 1,
- "label": "Company",
- "options": "Company",
- "reqd": 1
- },
- {
- "default": "0",
- "depends_on": "eval:doc.allow_invoicing && doc.send_email",
- "fieldname": "send_invoice",
- "fieldtype": "Check",
- "label": "Send Invoice with Email"
- },
- {
- "default": "0",
- "fieldname": "send_email",
- "fieldtype": "Check",
- "label": "Send Membership Acknowledgement"
- },
- {
- "depends_on": "eval: doc.send_invoice",
- "fieldname": "inv_print_format",
- "fieldtype": "Link",
- "label": "Invoice Print Format",
- "mandatory_depends_on": "eval: doc.send_invoice",
- "options": "Print Format"
- },
- {
- "depends_on": "eval:doc.send_email",
- "fieldname": "membership_print_format",
- "fieldtype": "Link",
- "label": "Membership Print Format",
- "options": "Print Format"
- },
- {
- "depends_on": "eval:doc.send_email",
- "fieldname": "email_template",
- "fieldtype": "Link",
- "label": "Email Template",
- "mandatory_depends_on": "eval:doc.send_email",
- "options": "Email Template"
- },
- {
- "default": "0",
- "fieldname": "allow_invoicing",
- "fieldtype": "Check",
- "label": "Allow Invoicing for Memberships",
- "mandatory_depends_on": "eval:doc.send_invoice || doc.make_payment_entry"
- },
- {
- "default": "0",
- "depends_on": "eval:doc.allow_invoicing",
- "description": "Automatically create an invoice when payment is authorized from a web form entry",
- "fieldname": "automate_membership_invoicing",
- "fieldtype": "Check",
- "label": "Automate Invoicing for Web Forms"
- },
- {
- "default": "0",
- "depends_on": "eval:doc.allow_invoicing",
- "description": "Auto creates Payment Entry for Sales Invoices created for Membership from web forms.",
- "fieldname": "automate_membership_payment_entries",
- "fieldtype": "Check",
- "label": "Automate Payment Entry Creation"
- },
- {
- "default": "0",
- "fieldname": "enable_razorpay_for_memberships",
- "fieldtype": "Check",
- "label": "Enable RazorPay For Memberships"
- },
- {
- "depends_on": "eval:doc.automate_membership_payment_entries",
- "description": "Account for accepting membership payments",
- "fieldname": "membership_payment_account",
- "fieldtype": "Link",
- "label": "Membership Payment To",
- "mandatory_depends_on": "eval:doc.automate_membership_payment_entries",
- "options": "Account"
- },
- {
- "fieldname": "membership_webhook_secret",
- "fieldtype": "Password",
- "label": "Membership Webhook Secret",
- "read_only": 1
- },
- {
- "fieldname": "donation_webhook_secret",
- "fieldtype": "Password",
- "label": "Donation Webhook Secret",
- "read_only": 1
- },
- {
- "depends_on": "automate_donation_payment_entries",
- "description": "Account for accepting donation payments",
- "fieldname": "donation_payment_account",
- "fieldtype": "Link",
- "label": "Donation Payment To",
- "mandatory_depends_on": "automate_donation_payment_entries",
- "options": "Account"
- },
- {
- "default": "0",
- "description": "Auto creates Payment Entry for Donations created from web forms.",
- "fieldname": "automate_donation_payment_entries",
- "fieldtype": "Check",
- "label": "Automate Donation Payment Entries"
- },
- {
- "depends_on": "eval:doc.allow_invoicing",
- "fieldname": "membership_debit_account",
- "fieldtype": "Link",
- "label": "Debit Account",
- "mandatory_depends_on": "eval:doc.allow_invoicing",
- "options": "Account"
- },
- {
- "depends_on": "automate_donation_payment_entries",
- "fieldname": "donation_debit_account",
- "fieldtype": "Link",
- "label": "Debit Account",
- "mandatory_depends_on": "automate_donation_payment_entries",
- "options": "Account"
- },
- {
- "description": "This company will be set for the Donations created via webhook.",
- "fieldname": "donation_company",
- "fieldtype": "Link",
- "in_list_view": 1,
- "label": "Company",
- "options": "Company",
- "reqd": 1
- },
- {
- "fieldname": "donation_settings_section",
- "fieldtype": "Section Break",
- "label": "Donation Settings"
- },
- {
- "fieldname": "column_break_22",
- "fieldtype": "Column Break"
- },
- {
- "description": "This Donor Type will be set for the Donor created via Donation web form entry.",
- "fieldname": "default_donor_type",
- "fieldtype": "Link",
- "in_list_view": 1,
- "label": "Default Donor Type",
- "options": "Donor Type",
- "reqd": 1
- },
- {
- "fieldname": "section_break_27",
- "fieldtype": "Section Break"
- },
- {
- "description": "The user that will be used to create Donations, Memberships, Invoices, and Payment Entries. This user should have the relevant permissions.",
- "fieldname": "creation_user",
- "fieldtype": "Link",
- "label": "Creation User",
- "options": "User",
- "reqd": 1
- }
- ],
- "index_web_pages_for_search": 1,
- "issingle": 1,
- "links": [],
- "modified": "2021-03-11 10:43:38.124240",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Non Profit Settings",
- "owner": "Administrator",
- "permissions": [
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "print": 1,
- "read": 1,
- "role": "System Manager",
- "share": 1,
- "write": 1
- },
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "print": 1,
- "read": 1,
- "role": "Non Profit Manager",
- "share": 1,
- "write": 1
- },
- {
- "email": 1,
- "print": 1,
- "read": 1,
- "role": "Non Profit Member",
- "share": 1
- }
- ],
- "quick_entry": 1,
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_changes": 1
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/non_profit_settings/non_profit_settings.py b/erpnext/non_profit/doctype/non_profit_settings/non_profit_settings.py
deleted file mode 100644
index ace6605..0000000
--- a/erpnext/non_profit/doctype/non_profit_settings/non_profit_settings.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-import frappe
-from frappe import _
-from frappe.integrations.utils import get_payment_gateway_controller
-from frappe.model.document import Document
-
-
-class NonProfitSettings(Document):
- @frappe.whitelist()
- def generate_webhook_secret(self, field="membership_webhook_secret"):
- key = frappe.generate_hash(length=20)
- self.set(field, key)
- self.save()
-
- secret_for = "Membership" if field == "membership_webhook_secret" else "Donation"
-
- frappe.msgprint(
- _("Here is your webhook secret for {0} API, this will be shown to you only once.").format(secret_for) + "<br><br>" + key,
- _("Webhook Secret")
- )
-
- @frappe.whitelist()
- def revoke_key(self, key):
- self.set(key, None)
- self.save()
-
- def get_webhook_secret(self, endpoint="Membership"):
- fieldname = "membership_webhook_secret" if endpoint == "Membership" else "donation_webhook_secret"
- return self.get_password(fieldname=fieldname, raise_exception=False)
-
-@frappe.whitelist()
-def get_plans_for_membership(*args, **kwargs):
- controller = get_payment_gateway_controller("Razorpay")
- plans = controller.get_plans()
- return [plan.get("item") for plan in plans.get("items")]
diff --git a/erpnext/non_profit/doctype/non_profit_settings/test_non_profit_settings.py b/erpnext/non_profit/doctype/non_profit_settings/test_non_profit_settings.py
deleted file mode 100644
index 51d1ba0..0000000
--- a/erpnext/non_profit/doctype/non_profit_settings/test_non_profit_settings.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-# import frappe
-import unittest
-
-
-class TestNonProfitSettings(unittest.TestCase):
- pass
diff --git a/erpnext/non_profit/doctype/volunteer/__init__.py b/erpnext/non_profit/doctype/volunteer/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/volunteer/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/volunteer/test_volunteer.py b/erpnext/non_profit/doctype/volunteer/test_volunteer.py
deleted file mode 100644
index 0a0ab2c..0000000
--- a/erpnext/non_profit/doctype/volunteer/test_volunteer.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-
-class TestVolunteer(unittest.TestCase):
- pass
diff --git a/erpnext/non_profit/doctype/volunteer/volunteer.js b/erpnext/non_profit/doctype/volunteer/volunteer.js
deleted file mode 100644
index ac93d8c..0000000
--- a/erpnext/non_profit/doctype/volunteer/volunteer.js
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Volunteer', {
- refresh: function(frm) {
-
- frappe.dynamic_link = {doc: frm.doc, fieldname: 'name', doctype: 'Volunteer'};
-
- frm.toggle_display(['address_html','contact_html'], !frm.doc.__islocal);
-
- if(!frm.doc.__islocal) {
- frappe.contacts.render_address_and_contact(frm);
- } else {
- frappe.contacts.clear_address_and_contact(frm);
- }
- }
-});
diff --git a/erpnext/non_profit/doctype/volunteer/volunteer.json b/erpnext/non_profit/doctype/volunteer/volunteer.json
deleted file mode 100644
index 08b7f87..0000000
--- a/erpnext/non_profit/doctype/volunteer/volunteer.json
+++ /dev/null
@@ -1,148 +0,0 @@
-{
- "actions": [],
- "allow_rename": 1,
- "autoname": "field:email",
- "creation": "2017-09-19 16:16:45.676019",
- "doctype": "DocType",
- "editable_grid": 1,
- "engine": "InnoDB",
- "field_order": [
- "volunteer_name",
- "column_break_5",
- "volunteer_type",
- "email",
- "image",
- "address_contacts",
- "address_html",
- "column_break_9",
- "contact_html",
- "volunteer_availability_and_skills_details",
- "availability",
- "availability_timeslot",
- "column_break_12",
- "volunteer_skills",
- "section_break_15",
- "note"
- ],
- "fields": [
- {
- "fieldname": "volunteer_name",
- "fieldtype": "Data",
- "in_list_view": 1,
- "label": "Volunteer Name",
- "reqd": 1
- },
- {
- "fieldname": "column_break_5",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "volunteer_type",
- "fieldtype": "Link",
- "in_list_view": 1,
- "label": "Volunteer Type",
- "options": "Volunteer Type",
- "reqd": 1
- },
- {
- "fieldname": "email",
- "fieldtype": "Data",
- "in_list_view": 1,
- "label": "Email",
- "reqd": 1,
- "unique": 1
- },
- {
- "fieldname": "image",
- "fieldtype": "Attach Image",
- "hidden": 1,
- "label": "Image",
- "no_copy": 1,
- "print_hide": 1
- },
- {
- "depends_on": "eval:!doc.__islocal;",
- "fieldname": "address_contacts",
- "fieldtype": "Section Break",
- "label": "Address and Contact",
- "options": "fa fa-map-marker"
- },
- {
- "fieldname": "address_html",
- "fieldtype": "HTML",
- "label": "Address HTML"
- },
- {
- "fieldname": "column_break_9",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "contact_html",
- "fieldtype": "HTML",
- "label": "Contact HTML"
- },
- {
- "fieldname": "volunteer_availability_and_skills_details",
- "fieldtype": "Section Break",
- "label": "Availability and Skills"
- },
- {
- "fieldname": "availability",
- "fieldtype": "Select",
- "label": "Availability",
- "options": "\nWeekly\nWeekdays\nWeekends"
- },
- {
- "fieldname": "availability_timeslot",
- "fieldtype": "Select",
- "label": "Availability Timeslot",
- "options": "\nMorning\nAfternoon\nEvening\nAnytime"
- },
- {
- "fieldname": "column_break_12",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "volunteer_skills",
- "fieldtype": "Table",
- "label": "Volunteer Skills",
- "options": "Volunteer Skill"
- },
- {
- "fieldname": "section_break_15",
- "fieldtype": "Section Break"
- },
- {
- "fieldname": "note",
- "fieldtype": "Long Text",
- "label": "Note"
- }
- ],
- "image_field": "image",
- "links": [],
- "modified": "2020-09-16 23:45:15.595952",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Volunteer",
- "owner": "Administrator",
- "permissions": [
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "export": 1,
- "print": 1,
- "read": 1,
- "report": 1,
- "role": "Non Profit Manager",
- "share": 1,
- "write": 1
- }
- ],
- "quick_entry": 1,
- "restrict_to_domain": "Non Profit",
- "sort_field": "modified",
- "sort_order": "DESC",
- "title_field": "volunteer_name",
- "track_changes": 1
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/volunteer/volunteer.py b/erpnext/non_profit/doctype/volunteer/volunteer.py
deleted file mode 100644
index b44d67d..0000000
--- a/erpnext/non_profit/doctype/volunteer/volunteer.py
+++ /dev/null
@@ -1,12 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-from frappe.contacts.address_and_contact import load_address_and_contact
-from frappe.model.document import Document
-
-
-class Volunteer(Document):
- def onload(self):
- """Load address and contacts in `__onload`"""
- load_address_and_contact(self)
diff --git a/erpnext/non_profit/doctype/volunteer_skill/__init__.py b/erpnext/non_profit/doctype/volunteer_skill/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/volunteer_skill/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/volunteer_skill/volunteer_skill.json b/erpnext/non_profit/doctype/volunteer_skill/volunteer_skill.json
deleted file mode 100644
index 7d210aa..0000000
--- a/erpnext/non_profit/doctype/volunteer_skill/volunteer_skill.json
+++ /dev/null
@@ -1,73 +0,0 @@
-{
- "allow_copy": 0,
- "allow_guest_to_view": 0,
- "allow_import": 0,
- "allow_rename": 0,
- "beta": 0,
- "creation": "2017-09-20 15:26:26.453435",
- "custom": 0,
- "docstatus": 0,
- "doctype": "DocType",
- "document_type": "",
- "editable_grid": 1,
- "engine": "InnoDB",
- "fields": [
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "volunteer_skill",
- "fieldtype": "Data",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Volunteer Skill",
- "length": 0,
- "no_copy": 0,
- "options": "",
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 0,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- }
- ],
- "has_web_view": 0,
- "hide_heading": 0,
- "hide_toolbar": 0,
- "idx": 0,
- "image_view": 0,
- "in_create": 0,
- "is_submittable": 0,
- "issingle": 0,
- "istable": 1,
- "max_attachments": 0,
- "modified": "2017-12-06 11:54:14.396354",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Volunteer Skill",
- "name_case": "",
- "owner": "Administrator",
- "permissions": [],
- "quick_entry": 1,
- "read_only": 0,
- "read_only_onload": 0,
- "restrict_to_domain": "Non Profit",
- "show_name_in_global_search": 0,
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_changes": 1,
- "track_seen": 0
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/volunteer_skill/volunteer_skill.py b/erpnext/non_profit/doctype/volunteer_skill/volunteer_skill.py
deleted file mode 100644
index fe72518..0000000
--- a/erpnext/non_profit/doctype/volunteer_skill/volunteer_skill.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-from frappe.model.document import Document
-
-
-class VolunteerSkill(Document):
- pass
diff --git a/erpnext/non_profit/doctype/volunteer_type/__init__.py b/erpnext/non_profit/doctype/volunteer_type/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/doctype/volunteer_type/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/doctype/volunteer_type/test_volunteer_type.py b/erpnext/non_profit/doctype/volunteer_type/test_volunteer_type.py
deleted file mode 100644
index cef27c8..0000000
--- a/erpnext/non_profit/doctype/volunteer_type/test_volunteer_type.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-
-class TestVolunteerType(unittest.TestCase):
- pass
diff --git a/erpnext/non_profit/doctype/volunteer_type/volunteer_type.js b/erpnext/non_profit/doctype/volunteer_type/volunteer_type.js
deleted file mode 100644
index 5c17505..0000000
--- a/erpnext/non_profit/doctype/volunteer_type/volunteer_type.js
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Volunteer Type', {
- refresh: function() {
-
- }
-});
diff --git a/erpnext/non_profit/doctype/volunteer_type/volunteer_type.json b/erpnext/non_profit/doctype/volunteer_type/volunteer_type.json
deleted file mode 100644
index 256b25f..0000000
--- a/erpnext/non_profit/doctype/volunteer_type/volunteer_type.json
+++ /dev/null
@@ -1,94 +0,0 @@
-{
- "allow_copy": 0,
- "allow_guest_to_view": 0,
- "allow_import": 0,
- "allow_rename": 0,
- "autoname": "prompt",
- "beta": 0,
- "creation": "2017-09-19 16:13:07.763273",
- "custom": 0,
- "docstatus": 0,
- "doctype": "DocType",
- "document_type": "",
- "editable_grid": 1,
- "engine": "InnoDB",
- "fields": [
- {
- "allow_bulk_edit": 0,
- "allow_on_submit": 0,
- "bold": 0,
- "collapsible": 0,
- "columns": 0,
- "fieldname": "amount",
- "fieldtype": "Float",
- "hidden": 0,
- "ignore_user_permissions": 0,
- "ignore_xss_filter": 0,
- "in_filter": 0,
- "in_global_search": 0,
- "in_list_view": 1,
- "in_standard_filter": 0,
- "label": "Amount",
- "length": 0,
- "no_copy": 0,
- "permlevel": 0,
- "precision": "",
- "print_hide": 0,
- "print_hide_if_no_value": 0,
- "read_only": 0,
- "remember_last_selected_value": 0,
- "report_hide": 0,
- "reqd": 1,
- "search_index": 0,
- "set_only_once": 0,
- "unique": 0
- }
- ],
- "has_web_view": 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": "2017-12-06 11:52:08.800425",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Volunteer Type",
- "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": "Non Profit Manager",
- "set_user_permissions": 0,
- "share": 1,
- "submit": 0,
- "write": 1
- }
- ],
- "quick_entry": 1,
- "read_only": 0,
- "read_only_onload": 0,
- "restrict_to_domain": "Non Profit",
- "show_name_in_global_search": 0,
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_changes": 1,
- "track_seen": 0
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/doctype/volunteer_type/volunteer_type.py b/erpnext/non_profit/doctype/volunteer_type/volunteer_type.py
deleted file mode 100644
index 3b1ae1a..0000000
--- a/erpnext/non_profit/doctype/volunteer_type/volunteer_type.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-from frappe.model.document import Document
-
-
-class VolunteerType(Document):
- pass
diff --git a/erpnext/non_profit/report/__init__.py b/erpnext/non_profit/report/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/report/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/report/expiring_memberships/__init__.py b/erpnext/non_profit/report/expiring_memberships/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/report/expiring_memberships/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/report/expiring_memberships/expiring_memberships.js b/erpnext/non_profit/report/expiring_memberships/expiring_memberships.js
deleted file mode 100644
index be3a243..0000000
--- a/erpnext/non_profit/report/expiring_memberships/expiring_memberships.js
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-/* eslint-disable */
-
-frappe.query_reports["Expiring Memberships"] = {
- "filters": [
- {
- "fieldname": "fiscal_year",
- "label": __("Fiscal Year"),
- "fieldtype": "Link",
- "options": "Fiscal Year",
- "default": frappe.defaults.get_user_default("fiscal_year"),
- "reqd": 1
- },
- {
- "fieldname":"month",
- "label": __("Month"),
- "fieldtype": "Select",
- "options": "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSep\nOct\nNov\nDec",
- "default": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
- "Dec"][frappe.datetime.str_to_obj(frappe.datetime.get_today()).getMonth()],
- }
- ]
-}
diff --git a/erpnext/non_profit/report/expiring_memberships/expiring_memberships.json b/erpnext/non_profit/report/expiring_memberships/expiring_memberships.json
deleted file mode 100644
index c311057..0000000
--- a/erpnext/non_profit/report/expiring_memberships/expiring_memberships.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "add_total_row": 0,
- "apply_user_permissions": 1,
- "creation": "2018-05-24 11:44:08.942809",
- "disabled": 0,
- "docstatus": 0,
- "doctype": "Report",
- "idx": 0,
- "is_standard": "Yes",
- "letter_head": "ERPNext Foundation",
- "modified": "2018-05-24 11:44:08.942809",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Expiring Memberships",
- "owner": "Administrator",
- "ref_doctype": "Membership",
- "report_name": "Expiring Memberships",
- "report_type": "Script Report",
- "roles": [
- {
- "role": "Non Profit Manager"
- },
- {
- "role": "Non Profit Member"
- }
- ]
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/report/expiring_memberships/expiring_memberships.py b/erpnext/non_profit/report/expiring_memberships/expiring_memberships.py
deleted file mode 100644
index 3ddbfdc..0000000
--- a/erpnext/non_profit/report/expiring_memberships/expiring_memberships.py
+++ /dev/null
@@ -1,34 +0,0 @@
-# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-import frappe
-from frappe import _
-
-
-def execute(filters=None):
- columns = get_columns(filters)
- data = get_data(filters)
- return columns, data
-
-def get_columns(filters):
- return [
- _("Membership Type") + ":Link/Membership Type:100", _("Membership ID") + ":Link/Membership:140",
- _("Member ID") + ":Link/Member:140", _("Member Name") + ":Data:140", _("Email") + ":Data:140",
- _("Expiring On") + ":Date:120"
- ]
-
-def get_data(filters):
-
- filters["month"] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].index(filters.month) + 1
-
- return frappe.db.sql("""
- select ms.membership_type,ms.name,m.name,m.member_name,m.email,ms.max_membership_date
- from `tabMember` m
- inner join (select name,membership_type,max(to_date) as max_membership_date,member
- from `tabMembership`
- where paid = 1
- group by member
- order by max_membership_date asc) ms
- on m.name = ms.member
- where month(max_membership_date) = %(month)s and year(max_membership_date) = %(year)s """,{'month': filters.get('month'),'year':filters.get('fiscal_year')})
diff --git a/erpnext/non_profit/utils.py b/erpnext/non_profit/utils.py
deleted file mode 100644
index 47ea5f5..0000000
--- a/erpnext/non_profit/utils.py
+++ /dev/null
@@ -1,12 +0,0 @@
-import frappe
-
-
-def get_company():
- company = frappe.defaults.get_defaults().company
- if company:
- return company
- else:
- company = frappe.get_list("Company", limit=1)
- if company:
- return company[0].name
- return None
diff --git a/erpnext/non_profit/web_form/__init__.py b/erpnext/non_profit/web_form/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/web_form/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/web_form/certification_application/__init__.py b/erpnext/non_profit/web_form/certification_application/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/web_form/certification_application/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/web_form/certification_application/certification_application.js b/erpnext/non_profit/web_form/certification_application/certification_application.js
deleted file mode 100644
index 8b455ed..0000000
--- a/erpnext/non_profit/web_form/certification_application/certification_application.js
+++ /dev/null
@@ -1,16 +0,0 @@
-frappe.ready(function() {
- // bind events here
- $(".page-header-actions-block .btn-primary, .page-header-actions-block .btn-default").addClass('hidden');
- $(".text-right .btn-primary").addClass('hidden');
-
- if (frappe.utils.get_url_arg('name')) {
- $('.page-content .btn-form-submit').addClass('hidden');
- } else {
- user_name = frappe.full_name
- user_email_id = frappe.session.user
- $('[data-fieldname="currency"]').val("INR");
- $('[data-fieldname="name_of_applicant"]').val(user_name);
- $('[data-fieldname="email"]').val(user_email_id);
- $('[data-fieldname="amount"]').val(20000);
- }
-})
diff --git a/erpnext/non_profit/web_form/certification_application/certification_application.json b/erpnext/non_profit/web_form/certification_application/certification_application.json
deleted file mode 100644
index 5fda978..0000000
--- a/erpnext/non_profit/web_form/certification_application/certification_application.json
+++ /dev/null
@@ -1,79 +0,0 @@
-{
- "accept_payment": 1,
- "allow_comments": 0,
- "allow_delete": 0,
- "allow_edit": 0,
- "allow_incomplete": 0,
- "allow_multiple": 1,
- "allow_print": 0,
- "amount": 0.0,
- "amount_based_on_field": 1,
- "amount_field": "amount",
- "creation": "2018-06-08 16:24:05.805225",
- "doc_type": "Certification Application",
- "docstatus": 0,
- "doctype": "Web Form",
- "idx": 0,
- "introduction_text": "",
- "is_standard": 1,
- "login_required": 1,
- "max_attachment_size": 0,
- "modified": "2018-06-11 16:11:14.544987",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "certification-application",
- "owner": "Administrator",
- "payment_button_help": "Pay for your certification using RazorPay",
- "payment_button_label": "Pay Now",
- "payment_gateway": "Razorpay",
- "published": 1,
- "route": "certification-application",
- "show_sidebar": 1,
- "sidebar_items": [],
- "success_url": "/certification-application",
- "title": "Certification Application",
- "web_form_fields": [
- {
- "fieldname": "name_of_applicant",
- "fieldtype": "Data",
- "hidden": 0,
- "label": "Name of Applicant",
- "max_length": 0,
- "max_value": 0,
- "read_only": 0,
- "reqd": 0
- },
- {
- "fieldname": "email",
- "fieldtype": "Link",
- "hidden": 0,
- "label": "Email",
- "max_length": 0,
- "max_value": 0,
- "options": "User",
- "read_only": 1,
- "reqd": 1
- },
- {
- "fieldname": "currency",
- "fieldtype": "Select",
- "hidden": 0,
- "label": "Currency",
- "max_length": 0,
- "max_value": 0,
- "options": "USD\nINR",
- "read_only": 1,
- "reqd": 0
- },
- {
- "fieldname": "amount",
- "fieldtype": "Float",
- "hidden": 0,
- "label": "Amount",
- "max_length": 0,
- "max_value": 0,
- "read_only": 1,
- "reqd": 0
- }
- ]
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/web_form/certification_application/certification_application.py b/erpnext/non_profit/web_form/certification_application/certification_application.py
deleted file mode 100644
index 02e3e93..0000000
--- a/erpnext/non_profit/web_form/certification_application/certification_application.py
+++ /dev/null
@@ -1,3 +0,0 @@
-def get_context(context):
- # do your magic here
- pass
diff --git a/erpnext/non_profit/web_form/certification_application_usd/__init__.py b/erpnext/non_profit/web_form/certification_application_usd/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/web_form/certification_application_usd/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/web_form/certification_application_usd/certification_application_usd.js b/erpnext/non_profit/web_form/certification_application_usd/certification_application_usd.js
deleted file mode 100644
index 005d1dd..0000000
--- a/erpnext/non_profit/web_form/certification_application_usd/certification_application_usd.js
+++ /dev/null
@@ -1,16 +0,0 @@
-frappe.ready(function() {
- // bind events here
- $(".page-header-actions-block .btn-primary, .page-header-actions-block .btn-default").addClass('hidden');
- $(".text-right .btn-primary").addClass('hidden');
-
- if (frappe.utils.get_url_arg('name')) {
- $('.page-content .btn-form-submit').addClass('hidden');
- } else {
- user_name = frappe.full_name
- user_email_id = frappe.session.user
- $('[data-fieldname="currency"]').val("USD");
- $('[data-fieldname="name_of_applicant"]').val(user_name);
- $('[data-fieldname="email"]').val(user_email_id);
- $('[data-fieldname="amount"]').val(300);
- }
-})
diff --git a/erpnext/non_profit/web_form/certification_application_usd/certification_application_usd.json b/erpnext/non_profit/web_form/certification_application_usd/certification_application_usd.json
deleted file mode 100644
index 266109f..0000000
--- a/erpnext/non_profit/web_form/certification_application_usd/certification_application_usd.json
+++ /dev/null
@@ -1,80 +0,0 @@
-{
- "accept_payment": 1,
- "allow_comments": 0,
- "allow_delete": 0,
- "allow_edit": 0,
- "allow_incomplete": 0,
- "allow_multiple": 1,
- "allow_print": 0,
- "amount": 0.0,
- "amount_based_on_field": 1,
- "amount_field": "amount",
- "creation": "2018-06-13 09:22:48.262441",
- "currency": "USD",
- "doc_type": "Certification Application",
- "docstatus": 0,
- "doctype": "Web Form",
- "idx": 0,
- "introduction_text": "",
- "is_standard": 1,
- "login_required": 1,
- "max_attachment_size": 0,
- "modified": "2018-06-13 09:26:35.502064",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "certification-application-usd",
- "owner": "Administrator",
- "payment_button_help": "Pay for your certification using PayPal",
- "payment_button_label": "Pay Now",
- "payment_gateway": "PayPal",
- "published": 1,
- "route": "certification-application-usd",
- "show_sidebar": 1,
- "sidebar_items": [],
- "success_url": "/certification-application-usd",
- "title": "Certification Application USD",
- "web_form_fields": [
- {
- "fieldname": "name_of_applicant",
- "fieldtype": "Data",
- "hidden": 0,
- "label": "Name of Applicant",
- "max_length": 0,
- "max_value": 0,
- "read_only": 0,
- "reqd": 0
- },
- {
- "fieldname": "email",
- "fieldtype": "Link",
- "hidden": 0,
- "label": "Email",
- "max_length": 0,
- "max_value": 0,
- "options": "User",
- "read_only": 1,
- "reqd": 1
- },
- {
- "fieldname": "currency",
- "fieldtype": "Select",
- "hidden": 0,
- "label": "Currency",
- "max_length": 0,
- "max_value": 0,
- "options": "USD\nINR",
- "read_only": 1,
- "reqd": 0
- },
- {
- "fieldname": "amount",
- "fieldtype": "Float",
- "hidden": 0,
- "label": "Amount",
- "max_length": 0,
- "max_value": 0,
- "read_only": 1,
- "reqd": 0
- }
- ]
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/web_form/certification_application_usd/certification_application_usd.py b/erpnext/non_profit/web_form/certification_application_usd/certification_application_usd.py
deleted file mode 100644
index 02e3e93..0000000
--- a/erpnext/non_profit/web_form/certification_application_usd/certification_application_usd.py
+++ /dev/null
@@ -1,3 +0,0 @@
-def get_context(context):
- # do your magic here
- pass
diff --git a/erpnext/non_profit/web_form/grant_application/__init__.py b/erpnext/non_profit/web_form/grant_application/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/non_profit/web_form/grant_application/__init__.py
+++ /dev/null
diff --git a/erpnext/non_profit/web_form/grant_application/grant_application.js b/erpnext/non_profit/web_form/grant_application/grant_application.js
deleted file mode 100644
index f09e540..0000000
--- a/erpnext/non_profit/web_form/grant_application/grant_application.js
+++ /dev/null
@@ -1,3 +0,0 @@
-frappe.ready(function() {
- // bind events here
-});
diff --git a/erpnext/non_profit/web_form/grant_application/grant_application.json b/erpnext/non_profit/web_form/grant_application/grant_application.json
deleted file mode 100644
index 73c9445..0000000
--- a/erpnext/non_profit/web_form/grant_application/grant_application.json
+++ /dev/null
@@ -1,108 +0,0 @@
-{
- "accept_payment": 0,
- "allow_comments": 0,
- "allow_delete": 1,
- "allow_edit": 1,
- "allow_incomplete": 0,
- "allow_multiple": 1,
- "allow_print": 0,
- "amount": 0.0,
- "amount_based_on_field": 0,
- "creation": "2017-10-30 15:57:10.825188",
- "currency": "INR",
- "doc_type": "Grant Application",
- "docstatus": 0,
- "doctype": "Web Form",
- "idx": 0,
- "introduction_text": "Share as many details as you can to get quick response from organization",
- "is_standard": 1,
- "login_required": 1,
- "max_attachment_size": 0,
- "modified": "2017-12-06 12:32:16.893289",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "grant-application",
- "owner": "Administrator",
- "payment_button_label": "Buy Now",
- "published": 1,
- "route": "my-grant",
- "show_sidebar": 1,
- "sidebar_items": [],
- "success_url": "/grant-application",
- "title": "Grant Application",
- "web_form_fields": [
- {
- "fieldname": "applicant_type",
- "fieldtype": "Select",
- "hidden": 0,
- "label": "Applicant Type",
- "max_length": 0,
- "max_value": 0,
- "options": "Individual\nOrganization",
- "read_only": 0,
- "reqd": 1
- },
- {
- "fieldname": "applicant_name",
- "fieldtype": "Data",
- "hidden": 0,
- "label": "Name",
- "max_length": 0,
- "max_value": 0,
- "read_only": 0,
- "reqd": 1
- },
- {
- "fieldname": "email",
- "fieldtype": "Data",
- "hidden": 0,
- "label": "Email Address",
- "max_length": 0,
- "max_value": 0,
- "read_only": 0,
- "reqd": 1
- },
- {
- "description": "",
- "fieldname": "grant_description",
- "fieldtype": "Text",
- "hidden": 0,
- "label": "Please outline your current situation and why you are applying for a grant?",
- "max_length": 0,
- "max_value": 0,
- "read_only": 0,
- "reqd": 1
- },
- {
- "fieldname": "amount",
- "fieldtype": "Float",
- "hidden": 0,
- "label": "Requested Amount",
- "max_length": 0,
- "max_value": 0,
- "read_only": 0,
- "reqd": 0
- },
- {
- "fieldname": "has_any_past_grant_record",
- "fieldtype": "Check",
- "hidden": 0,
- "label": "Have you received any grant from us before?",
- "max_length": 0,
- "max_value": 0,
- "options": "",
- "read_only": 0,
- "reqd": 0
- },
- {
- "fieldname": "published",
- "fieldtype": "Check",
- "hidden": 0,
- "label": "Show on Website",
- "max_length": 0,
- "max_value": 0,
- "read_only": 0,
- "reqd": 0
- }
- ]
-}
\ No newline at end of file
diff --git a/erpnext/non_profit/web_form/grant_application/grant_application.py b/erpnext/non_profit/web_form/grant_application/grant_application.py
deleted file mode 100644
index 3dfb381..0000000
--- a/erpnext/non_profit/web_form/grant_application/grant_application.py
+++ /dev/null
@@ -1,4 +0,0 @@
-def get_context(context):
- context.no_cache = True
- context.parents = [dict(label='View All ',
- route='grant-application', title='View All')]
diff --git a/erpnext/non_profit/workspace/non_profit/non_profit.json b/erpnext/non_profit/workspace/non_profit/non_profit.json
deleted file mode 100644
index fc90475..0000000
--- a/erpnext/non_profit/workspace/non_profit/non_profit.json
+++ /dev/null
@@ -1,272 +0,0 @@
-{
- "charts": [],
- "content": "[{\"type\":\"header\",\"data\":{\"text\":\"<span class=\\\"h4\\\"><b>Your Shortcuts</b></span>\",\"col\":12}},{\"type\":\"shortcut\",\"data\":{\"shortcut_name\":\"Member\",\"col\":3}},{\"type\":\"shortcut\",\"data\":{\"shortcut_name\":\"Non Profit Settings\",\"col\":3}},{\"type\":\"shortcut\",\"data\":{\"shortcut_name\":\"Membership\",\"col\":3}},{\"type\":\"shortcut\",\"data\":{\"shortcut_name\":\"Chapter\",\"col\":3}},{\"type\":\"shortcut\",\"data\":{\"shortcut_name\":\"Chapter Member\",\"col\":3}},{\"type\":\"spacer\",\"data\":{\"col\":12}},{\"type\":\"header\",\"data\":{\"text\":\"<span class=\\\"h4\\\"><b>Reports & Masters</b></span>\",\"col\":12}},{\"type\":\"card\",\"data\":{\"card_name\":\"Loan Management\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Grant Application\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Membership\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Volunteer\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Chapter\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Donation\",\"col\":4}},{\"type\":\"card\",\"data\":{\"card_name\":\"Tax Exemption Certification (India)\",\"col\":4}}]",
- "creation": "2020-03-02 17:23:47.811421",
- "docstatus": 0,
- "doctype": "Workspace",
- "for_user": "",
- "hide_custom": 0,
- "icon": "non-profit",
- "idx": 0,
- "label": "Non Profit",
- "links": [
- {
- "hidden": 0,
- "is_query_report": 0,
- "label": "Loan Management",
- "link_count": 0,
- "onboard": 0,
- "type": "Card Break"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Loan Type",
- "link_count": 0,
- "link_to": "Loan Type",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Loan Application",
- "link_count": 0,
- "link_to": "Loan Application",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Loan",
- "link_count": 0,
- "link_to": "Loan",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "hidden": 0,
- "is_query_report": 0,
- "label": "Grant Application",
- "link_count": 0,
- "onboard": 0,
- "type": "Card Break"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Grant Application",
- "link_count": 0,
- "link_to": "Grant Application",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "hidden": 0,
- "is_query_report": 0,
- "label": "Membership",
- "link_count": 0,
- "onboard": 0,
- "type": "Card Break"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Member",
- "link_count": 0,
- "link_to": "Member",
- "link_type": "DocType",
- "onboard": 1,
- "type": "Link"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Membership",
- "link_count": 0,
- "link_to": "Membership",
- "link_type": "DocType",
- "onboard": 1,
- "type": "Link"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Membership Type",
- "link_count": 0,
- "link_to": "Membership Type",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Membership Settings",
- "link_count": 0,
- "link_to": "Non Profit Settings",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "hidden": 0,
- "is_query_report": 0,
- "label": "Volunteer",
- "link_count": 0,
- "onboard": 0,
- "type": "Card Break"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Volunteer",
- "link_count": 0,
- "link_to": "Volunteer",
- "link_type": "DocType",
- "onboard": 1,
- "type": "Link"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Volunteer Type",
- "link_count": 0,
- "link_to": "Volunteer Type",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "hidden": 0,
- "is_query_report": 0,
- "label": "Chapter",
- "link_count": 0,
- "onboard": 0,
- "type": "Card Break"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Chapter",
- "link_count": 0,
- "link_to": "Chapter",
- "link_type": "DocType",
- "onboard": 1,
- "type": "Link"
- },
- {
- "hidden": 0,
- "is_query_report": 0,
- "label": "Donation",
- "link_count": 0,
- "onboard": 0,
- "type": "Card Break"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Donor",
- "link_count": 0,
- "link_to": "Donor",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "dependencies": "",
- "hidden": 0,
- "is_query_report": 0,
- "label": "Donor Type",
- "link_count": 0,
- "link_to": "Donor Type",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "hidden": 0,
- "is_query_report": 0,
- "label": "Donation",
- "link_count": 0,
- "link_to": "Donation",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- },
- {
- "hidden": 0,
- "is_query_report": 0,
- "label": "Tax Exemption Certification (India)",
- "link_count": 0,
- "link_type": "DocType",
- "onboard": 0,
- "type": "Card Break"
- },
- {
- "hidden": 0,
- "is_query_report": 0,
- "label": "Tax Exemption 80G Certificate",
- "link_count": 0,
- "link_to": "Tax Exemption 80G Certificate",
- "link_type": "DocType",
- "onboard": 0,
- "type": "Link"
- }
- ],
- "modified": "2022-01-13 17:40:50.220877",
- "modified_by": "Administrator",
- "module": "Non Profit",
- "name": "Non Profit",
- "owner": "Administrator",
- "parent_page": "",
- "public": 1,
- "restrict_to_domain": "Non Profit",
- "roles": [],
- "sequence_id": 18.0,
- "shortcuts": [
- {
- "label": "Member",
- "link_to": "Member",
- "type": "DocType"
- },
- {
- "label": "Non Profit Settings",
- "link_to": "Non Profit Settings",
- "type": "DocType"
- },
- {
- "label": "Membership",
- "link_to": "Membership",
- "type": "DocType"
- },
- {
- "label": "Chapter",
- "link_to": "Chapter",
- "type": "DocType"
- },
- {
- "label": "Chapter Member",
- "link_to": "Chapter Member",
- "type": "DocType"
- }
- ],
- "title": "Non Profit"
-}
\ No newline at end of file
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index feafecb..13f0e7b 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -329,10 +329,10 @@
erpnext.patches.v14_0.set_payroll_cost_centers
erpnext.patches.v13_0.agriculture_deprecation_warning
erpnext.patches.v13_0.hospitality_deprecation_warning
-erpnext.patches.v13_0.update_exchange_rate_settings
erpnext.patches.v13_0.update_asset_quantity_field
erpnext.patches.v13_0.delete_bank_reconciliation_detail
erpnext.patches.v13_0.enable_provisional_accounting
+erpnext.patches.v13_0.non_profit_deprecation_warning
[post_model_sync]
erpnext.patches.v14_0.rename_ongoing_status_in_sla_documents
@@ -350,3 +350,11 @@
erpnext.patches.v13_0.convert_to_website_item_in_item_card_group_template
erpnext.patches.v13_0.shopping_cart_to_ecommerce
erpnext.patches.v13_0.update_disbursement_account
+erpnext.patches.v13_0.update_reserved_qty_closed_wo
+erpnext.patches.v13_0.update_exchange_rate_settings
+erpnext.patches.v14_0.delete_amazon_mws_doctype
+erpnext.patches.v13_0.set_work_order_qty_in_so_from_mr
+erpnext.patches.v13_0.update_accounts_in_loan_docs
+erpnext.patches.v14_0.update_batch_valuation_flag
+erpnext.patches.v14_0.delete_non_profit_doctypes
+erpnext.patches.v14_0.update_employee_advance_status
\ No newline at end of file
diff --git a/erpnext/patches/v12_0/move_bank_account_swift_number_to_bank.py b/erpnext/patches/v12_0/move_bank_account_swift_number_to_bank.py
index b3ee340..7ae4c42 100644
--- a/erpnext/patches/v12_0/move_bank_account_swift_number_to_bank.py
+++ b/erpnext/patches/v12_0/move_bank_account_swift_number_to_bank.py
@@ -5,10 +5,13 @@
frappe.reload_doc('accounts', 'doctype', 'bank', force=1)
if frappe.db.table_exists('Bank') and frappe.db.table_exists('Bank Account') and frappe.db.has_column('Bank Account', 'swift_number'):
- frappe.db.sql("""
- UPDATE `tabBank` b, `tabBank Account` ba
- SET b.swift_number = ba.swift_number WHERE b.name = ba.bank
- """)
+ try:
+ frappe.db.sql("""
+ UPDATE `tabBank` b, `tabBank Account` ba
+ SET b.swift_number = ba.swift_number WHERE b.name = ba.bank
+ """)
+ except Exception as e:
+ frappe.log_error(e, title="Patch Migration Failed")
frappe.reload_doc('accounts', 'doctype', 'bank_account')
frappe.reload_doc('accounts', 'doctype', 'payment_request')
diff --git a/erpnext/patches/v12_0/recalculate_requested_qty_in_bin.py b/erpnext/patches/v12_0/recalculate_requested_qty_in_bin.py
index 9b083ca..8dec9ff 100644
--- a/erpnext/patches/v12_0/recalculate_requested_qty_in_bin.py
+++ b/erpnext/patches/v12_0/recalculate_requested_qty_in_bin.py
@@ -9,6 +9,8 @@
FROM `tabBin`""",as_dict=1)
for entry in bin_details:
+ if not (entry.item_code and entry.warehouse):
+ continue
update_bin_qty(entry.get("item_code"), entry.get("warehouse"), {
"indented_qty": get_indented_qty(entry.get("item_code"), entry.get("warehouse"))
})
diff --git a/erpnext/patches/v12_0/rename_mws_settings_fields.py b/erpnext/patches/v12_0/rename_mws_settings_fields.py
deleted file mode 100644
index d5bf38d..0000000
--- a/erpnext/patches/v12_0/rename_mws_settings_fields.py
+++ /dev/null
@@ -1,12 +0,0 @@
-# Copyright (c) 2020, Frappe and Contributors
-# License: GNU General Public License v3. See license.txt
-
-import frappe
-
-
-def execute():
- count = frappe.db.sql("SELECT COUNT(*) FROM `tabSingles` WHERE doctype='Amazon MWS Settings' AND field='enable_sync';")[0][0]
- if count == 0:
- frappe.db.sql("UPDATE `tabSingles` SET field='enable_sync' WHERE doctype='Amazon MWS Settings' AND field='enable_synch';")
-
- frappe.reload_doc("ERPNext Integrations", "doctype", "Amazon MWS Settings")
diff --git a/erpnext/patches/v13_0/non_profit_deprecation_warning.py b/erpnext/patches/v13_0/non_profit_deprecation_warning.py
new file mode 100644
index 0000000..5b54b25
--- /dev/null
+++ b/erpnext/patches/v13_0/non_profit_deprecation_warning.py
@@ -0,0 +1,10 @@
+import click
+
+
+def execute():
+
+ click.secho(
+ "Non Profit Domain is moved to a separate app and will be removed from ERPNext in version-14.\n"
+ "When upgrading to ERPNext version-14, please install the app to continue using the Non Profit domain: https://github.com/frappe/non_profit",
+ fg="yellow",
+ )
diff --git a/erpnext/patches/v13_0/set_work_order_qty_in_so_from_mr.py b/erpnext/patches/v13_0/set_work_order_qty_in_so_from_mr.py
new file mode 100644
index 0000000..f097ab9
--- /dev/null
+++ b/erpnext/patches/v13_0/set_work_order_qty_in_so_from_mr.py
@@ -0,0 +1,36 @@
+import frappe
+
+
+def execute():
+ """
+ 1. Get submitted Work Orders with MR, MR Item and SO set
+ 2. Get SO Item detail from MR Item detail in WO, and set in WO
+ 3. Update work_order_qty in SO
+ """
+ work_order = frappe.qb.DocType("Work Order")
+ query = (
+ frappe.qb.from_(work_order)
+ .select(
+ work_order.name, work_order.produced_qty,
+ work_order.material_request,
+ work_order.material_request_item,
+ work_order.sales_order
+ ).where(
+ (work_order.material_request.isnotnull())
+ & (work_order.material_request_item.isnotnull())
+ & (work_order.sales_order.isnotnull())
+ & (work_order.docstatus == 1)
+ & (work_order.produced_qty > 0)
+ )
+ )
+ results = query.run(as_dict=True)
+
+ for row in results:
+ so_item = frappe.get_value(
+ "Material Request Item", row.material_request_item, "sales_order_item"
+ )
+ frappe.db.set_value("Work Order", row.name, "sales_order_item", so_item)
+
+ if so_item:
+ wo = frappe.get_doc("Work Order", row.name)
+ wo.update_work_order_qty_in_so()
diff --git a/erpnext/patches/v13_0/update_accounts_in_loan_docs.py b/erpnext/patches/v13_0/update_accounts_in_loan_docs.py
new file mode 100644
index 0000000..440f912
--- /dev/null
+++ b/erpnext/patches/v13_0/update_accounts_in_loan_docs.py
@@ -0,0 +1,37 @@
+import frappe
+
+
+def execute():
+ ld = frappe.qb.DocType("Loan Disbursement").as_("ld")
+ lr = frappe.qb.DocType("Loan Repayment").as_("lr")
+ loan = frappe.qb.DocType("Loan")
+
+ frappe.qb.update(
+ ld
+ ).inner_join(
+ loan
+ ).on(
+ loan.name == ld.against_loan
+ ).set(
+ ld.disbursement_account, loan.disbursement_account
+ ).set(
+ ld.loan_account, loan.loan_account
+ ).where(
+ ld.docstatus < 2
+ ).run()
+
+ frappe.qb.update(
+ lr
+ ).inner_join(
+ loan
+ ).on(
+ loan.name == lr.against_loan
+ ).set(
+ lr.payment_account, loan.payment_account
+ ).set(
+ lr.loan_account, loan.loan_account
+ ).set(
+ lr.penalty_income_account, loan.penalty_income_account
+ ).where(
+ lr.docstatus < 2
+ ).run()
diff --git a/erpnext/patches/v13_0/update_reserved_qty_closed_wo.py b/erpnext/patches/v13_0/update_reserved_qty_closed_wo.py
new file mode 100644
index 0000000..00926b0
--- /dev/null
+++ b/erpnext/patches/v13_0/update_reserved_qty_closed_wo.py
@@ -0,0 +1,28 @@
+import frappe
+
+from erpnext.stock.utils import get_bin
+
+
+def execute():
+
+ wo = frappe.qb.DocType("Work Order")
+ wo_item = frappe.qb.DocType("Work Order Item")
+
+ incorrect_item_wh = (
+ frappe.qb
+ .from_(wo)
+ .join(wo_item).on(wo.name == wo_item.parent)
+ .select(wo_item.item_code, wo.source_warehouse).distinct()
+ .where(
+ (wo.status == "Closed")
+ & (wo.docstatus == 1)
+ & (wo.source_warehouse.notnull())
+ )
+ ).run()
+
+ for item_code, warehouse in incorrect_item_wh:
+ if not (item_code and warehouse):
+ continue
+
+ bin = get_bin(item_code, warehouse)
+ bin.update_reserved_qty_for_production()
diff --git a/erpnext/patches/v14_0/delete_amazon_mws_doctype.py b/erpnext/patches/v14_0/delete_amazon_mws_doctype.py
new file mode 100644
index 0000000..525da6c
--- /dev/null
+++ b/erpnext/patches/v14_0/delete_amazon_mws_doctype.py
@@ -0,0 +1,5 @@
+import frappe
+
+
+def execute():
+ frappe.delete_doc("DocType", "Amazon MWS Settings", ignore_missing=True)
\ No newline at end of file
diff --git a/erpnext/patches/v14_0/delete_non_profit_doctypes.py b/erpnext/patches/v14_0/delete_non_profit_doctypes.py
new file mode 100644
index 0000000..565b10c
--- /dev/null
+++ b/erpnext/patches/v14_0/delete_non_profit_doctypes.py
@@ -0,0 +1,63 @@
+import frappe
+
+
+def execute():
+ frappe.delete_doc("Module Def", "Non Profit", ignore_missing=True, force=True)
+
+ frappe.delete_doc("Workspace", "Non Profit", ignore_missing=True, force=True)
+
+ print_formats = frappe.get_all("Print Format", {"module": "Non Profit", "standard": "Yes"}, pluck='name')
+ for print_format in print_formats:
+ frappe.delete_doc("Print Format", print_format, ignore_missing=True, force=True)
+
+ print_formats = ['80G Certificate for Membership', '80G Certificate for Donation']
+ for print_format in print_formats:
+ frappe.delete_doc("Print Format", print_format, ignore_missing=True, force=True)
+
+ reports = frappe.get_all("Report", {"module": "Non Profit", "is_standard": "Yes"}, pluck='name')
+ for report in reports:
+ frappe.delete_doc("Report", report, ignore_missing=True, force=True)
+
+ dashboards = frappe.get_all("Dashboard", {"module": "Non Profit", "is_standard": 1}, pluck='name')
+ for dashboard in dashboards:
+ frappe.delete_doc("Dashboard", dashboard, ignore_missing=True, force=True)
+
+ doctypes = frappe.get_all("DocType", {"module": "Non Profit", "custom": 0}, pluck='name')
+ for doctype in doctypes:
+ frappe.delete_doc("DocType", doctype, ignore_missing=True)
+
+ doctypes = ['Tax Exemption 80G Certificate', 'Tax Exemption 80G Certificate Detail']
+ for doctype in doctypes:
+ frappe.delete_doc("DocType", doctype, ignore_missing=True)
+
+ forms = ['grant-application', 'certification-application', 'certification-application-usd']
+ for form in forms:
+ frappe.delete_doc("Web Form", form, ignore_missing=True, force=True)
+
+ custom_records = [
+ {"doctype": "Party Type", "name": "Member"},
+ {"doctype": "Party Type", "name": "Donor"},
+ ]
+ for record in custom_records:
+ try:
+ frappe.delete_doc(record['doctype'], record['name'], ignore_missing=True)
+ except frappe.LinkExistsError:
+ pass
+
+ custom_fields = {
+ 'Member': ['pan_number'],
+ 'Donor': ['pan_number'],
+ 'Company': [
+ 'non_profit_section', 'company_80g_number', 'with_effect_from',
+ 'non_profit_column_break', 'pan_details'
+ ],
+ }
+
+ for doc, fields in custom_fields.items():
+ filters = {
+ 'dt': doc,
+ 'fieldname': ['in', fields]
+ }
+ records = frappe.get_all('Custom Field', filters=filters, pluck='name')
+ for record in records:
+ frappe.delete_doc('Custom Field', record, ignore_missing=True, force=True)
diff --git a/erpnext/patches/v14_0/update_batch_valuation_flag.py b/erpnext/patches/v14_0/update_batch_valuation_flag.py
new file mode 100644
index 0000000..55c8c48
--- /dev/null
+++ b/erpnext/patches/v14_0/update_batch_valuation_flag.py
@@ -0,0 +1,11 @@
+import frappe
+
+
+def execute():
+ """
+ - Don't use batchwise valuation for existing batches.
+ - Only batches created after this patch shoule use it.
+ """
+
+ batch = frappe.qb.DocType("Batch")
+ frappe.qb.update(batch).set(batch.use_batchwise_valuation, 0).run()
diff --git a/erpnext/patches/v14_0/update_employee_advance_status.py b/erpnext/patches/v14_0/update_employee_advance_status.py
new file mode 100644
index 0000000..a20e35a
--- /dev/null
+++ b/erpnext/patches/v14_0/update_employee_advance_status.py
@@ -0,0 +1,26 @@
+import frappe
+
+
+def execute():
+ frappe.reload_doc('hr', 'doctype', 'employee_advance')
+
+ advance = frappe.qb.DocType('Employee Advance')
+ (frappe.qb
+ .update(advance)
+ .set(advance.status, 'Returned')
+ .where(
+ (advance.docstatus == 1)
+ & ((advance.return_amount) & (advance.paid_amount == advance.return_amount))
+ & (advance.status == 'Paid')
+ )
+ ).run()
+
+ (frappe.qb
+ .update(advance)
+ .set(advance.status, 'Partly Claimed and Returned')
+ .where(
+ (advance.docstatus == 1)
+ & ((advance.claimed_amount & advance.return_amount) & (advance.paid_amount == (advance.return_amount + advance.claimed_amount)))
+ & (advance.status == 'Paid')
+ )
+ ).run()
\ No newline at end of file
diff --git a/erpnext/patches/v14_0/update_opportunity_currency_fields.py b/erpnext/patches/v14_0/update_opportunity_currency_fields.py
index 1307147..75049a6 100644
--- a/erpnext/patches/v14_0/update_opportunity_currency_fields.py
+++ b/erpnext/patches/v14_0/update_opportunity_currency_fields.py
@@ -6,9 +6,6 @@
def execute():
- frappe.reload_doc('crm', 'doctype', 'opportunity')
- frappe.reload_doc('crm', 'doctype', 'opportunity_item')
-
opportunities = frappe.db.get_list('Opportunity', filters={
'opportunity_amount': ['>', 0]
}, fields=['name', 'company', 'currency', 'opportunity_amount'])
@@ -20,15 +17,11 @@
if opportunity.currency != company_currency:
conversion_rate = get_exchange_rate(opportunity.currency, company_currency)
base_opportunity_amount = flt(conversion_rate) * flt(opportunity.opportunity_amount)
- grand_total = flt(opportunity.opportunity_amount)
- base_grand_total = flt(conversion_rate) * flt(opportunity.opportunity_amount)
else:
conversion_rate = 1
- base_opportunity_amount = grand_total = base_grand_total = flt(opportunity.opportunity_amount)
+ base_opportunity_amount = flt(opportunity.opportunity_amount)
frappe.db.set_value('Opportunity', opportunity.name, {
'conversion_rate': conversion_rate,
- 'base_opportunity_amount': base_opportunity_amount,
- 'grand_total': grand_total,
- 'base_grand_total': base_grand_total
+ 'base_opportunity_amount': base_opportunity_amount
}, update_modified=False)
diff --git a/erpnext/patches/v4_2/repost_reserved_qty.py b/erpnext/patches/v4_2/repost_reserved_qty.py
index c2ca9be..ed4b19d 100644
--- a/erpnext/patches/v4_2/repost_reserved_qty.py
+++ b/erpnext/patches/v4_2/repost_reserved_qty.py
@@ -29,9 +29,11 @@
""")
for item_code, warehouse in repost_for:
- update_bin_qty(item_code, warehouse, {
- "reserved_qty": get_reserved_qty(item_code, warehouse)
- })
+ if not (item_code and warehouse):
+ continue
+ update_bin_qty(item_code, warehouse, {
+ "reserved_qty": get_reserved_qty(item_code, warehouse)
+ })
frappe.db.sql("""delete from tabBin
where exists(
diff --git a/erpnext/patches/v4_2/update_requested_and_ordered_qty.py b/erpnext/patches/v4_2/update_requested_and_ordered_qty.py
index 42b0b04..dd79410 100644
--- a/erpnext/patches/v4_2/update_requested_and_ordered_qty.py
+++ b/erpnext/patches/v4_2/update_requested_and_ordered_qty.py
@@ -14,6 +14,8 @@
union
select item_code, warehouse from `tabStock Ledger Entry`) a"""):
try:
+ if not (item_code and warehouse):
+ continue
count += 1
update_bin_qty(item_code, warehouse, {
"indented_qty": get_indented_qty(item_code, warehouse),
diff --git a/erpnext/payroll/doctype/additional_salary/additional_salary.py b/erpnext/payroll/doctype/additional_salary/additional_salary.py
index bf8bd05..d618568 100644
--- a/erpnext/payroll/doctype/additional_salary/additional_salary.py
+++ b/erpnext/payroll/doctype/additional_salary/additional_salary.py
@@ -105,6 +105,8 @@
return_amount += self.amount
frappe.db.set_value("Employee Advance", self.ref_docname, "return_amount", return_amount)
+ advance = frappe.get_doc("Employee Advance", self.ref_docname)
+ advance.set_status(update=True)
def update_employee_referral(self, cancel=False):
if self.ref_doctype == "Employee Referral":
diff --git a/erpnext/payroll/doctype/gratuity/gratuity.js b/erpnext/payroll/doctype/gratuity/gratuity.js
index d4f7c9c..3d69c46 100644
--- a/erpnext/payroll/doctype/gratuity/gratuity.js
+++ b/erpnext/payroll/doctype/gratuity/gratuity.js
@@ -3,6 +3,14 @@
frappe.ui.form.on('Gratuity', {
setup: function (frm) {
+ frm.set_query("salary_component", function () {
+ return {
+ filters: {
+ type: "Earning"
+ }
+ };
+ });
+
frm.set_query("expense_account", function () {
return {
filters: {
@@ -24,7 +32,7 @@
});
},
refresh: function (frm) {
- if (frm.doc.docstatus == 1 && frm.doc.status == "Unpaid") {
+ if (frm.doc.docstatus == 1 && !frm.doc.pay_via_salary_slip && frm.doc.status == "Unpaid") {
frm.add_custom_button(__("Create Payment Entry"), function () {
return frappe.call({
method: 'erpnext.accounts.doctype.payment_entry.payment_entry.get_payment_entry',
diff --git a/erpnext/payroll/doctype/gratuity/gratuity.json b/erpnext/payroll/doctype/gratuity/gratuity.json
index 1970895..1fd1cec 100644
--- a/erpnext/payroll/doctype/gratuity/gratuity.json
+++ b/erpnext/payroll/doctype/gratuity/gratuity.json
@@ -1,7 +1,7 @@
{
"actions": [],
"autoname": "HR-GRA-PAY-.#####",
- "creation": "2020-08-05 20:52:13.024683",
+ "creation": "2022-01-27 16:24:28.200061",
"doctype": "DocType",
"editable_grid": 1,
"engine": "InnoDB",
@@ -16,6 +16,9 @@
"company",
"gratuity_rule",
"section_break_5",
+ "pay_via_salary_slip",
+ "payroll_date",
+ "salary_component",
"payable_account",
"expense_account",
"mode_of_payment",
@@ -78,18 +81,20 @@
"reqd": 1
},
{
+ "depends_on": "eval: !doc.pay_via_salary_slip",
"fieldname": "expense_account",
"fieldtype": "Link",
"label": "Expense Account",
- "options": "Account",
- "reqd": 1
+ "mandatory_depends_on": "eval: !doc.pay_via_salary_slip",
+ "options": "Account"
},
{
+ "depends_on": "eval: !doc.pay_via_salary_slip",
"fieldname": "mode_of_payment",
"fieldtype": "Link",
"label": "Mode of Payment",
- "options": "Mode of Payment",
- "reqd": 1
+ "mandatory_depends_on": "eval: !doc.pay_via_salary_slip",
+ "options": "Mode of Payment"
},
{
"fieldname": "gratuity_rule",
@@ -151,23 +156,45 @@
"read_only": 1
},
{
+ "depends_on": "eval: !doc.pay_via_salary_slip",
"fieldname": "payable_account",
"fieldtype": "Link",
"label": "Payable Account",
- "options": "Account",
- "reqd": 1
+ "mandatory_depends_on": "eval: !doc.pay_via_salary_slip",
+ "options": "Account"
},
{
"fieldname": "cost_center",
"fieldtype": "Link",
"label": "Cost Center",
"options": "Cost Center"
+ },
+ {
+ "default": "1",
+ "fieldname": "pay_via_salary_slip",
+ "fieldtype": "Check",
+ "label": "Pay via Salary Slip"
+ },
+ {
+ "depends_on": "pay_via_salary_slip",
+ "fieldname": "payroll_date",
+ "fieldtype": "Date",
+ "label": "Payroll Date",
+ "mandatory_depends_on": "pay_via_salary_slip"
+ },
+ {
+ "depends_on": "pay_via_salary_slip",
+ "fieldname": "salary_component",
+ "fieldtype": "Link",
+ "label": "Salary Component",
+ "mandatory_depends_on": "pay_via_salary_slip",
+ "options": "Salary Component"
}
],
"index_web_pages_for_search": 1,
"is_submittable": 1,
"links": [],
- "modified": "2022-01-19 12:54:37.306145",
+ "modified": "2022-02-02 14:00:45.536152",
"modified_by": "Administrator",
"module": "Payroll",
"name": "Gratuity",
diff --git a/erpnext/payroll/doctype/gratuity/gratuity.py b/erpnext/payroll/doctype/gratuity/gratuity.py
index 476990a..939634a 100644
--- a/erpnext/payroll/doctype/gratuity/gratuity.py
+++ b/erpnext/payroll/doctype/gratuity/gratuity.py
@@ -21,7 +21,10 @@
self.status = "Unpaid"
def on_submit(self):
- self.create_gl_entries()
+ if self.pay_via_salary_slip:
+ self.create_additional_salary()
+ else:
+ self.create_gl_entries()
def on_cancel(self):
self.ignore_linked_doctypes = ['GL Entry']
@@ -64,6 +67,19 @@
return gl_entry
+ def create_additional_salary(self):
+ if self.pay_via_salary_slip:
+ additional_salary = frappe.new_doc('Additional Salary')
+ additional_salary.employee = self.employee
+ additional_salary.salary_component = self.salary_component
+ additional_salary.overwrite_salary_structure_amount = 0
+ additional_salary.amount = self.amount
+ additional_salary.payroll_date = self.payroll_date
+ additional_salary.company = self.company
+ additional_salary.ref_doctype = self.doctype
+ additional_salary.ref_docname = self.name
+ additional_salary.submit()
+
def set_total_advance_paid(self):
paid_amount = frappe.db.sql("""
select ifnull(sum(debit_in_account_currency), 0) as paid_amount
diff --git a/erpnext/payroll/doctype/gratuity/gratuity_dashboard.py b/erpnext/payroll/doctype/gratuity/gratuity_dashboard.py
index aeadba1..771a6fe 100644
--- a/erpnext/payroll/doctype/gratuity/gratuity_dashboard.py
+++ b/erpnext/payroll/doctype/gratuity/gratuity_dashboard.py
@@ -10,7 +10,7 @@
'transactions': [
{
'label': _('Payment'),
- 'items': ['Payment Entry']
+ 'items': ['Payment Entry', 'Additional Salary']
}
]
}
diff --git a/erpnext/payroll/doctype/gratuity/test_gratuity.py b/erpnext/payroll/doctype/gratuity/test_gratuity.py
index 93cba06..90e8061 100644
--- a/erpnext/payroll/doctype/gratuity/test_gratuity.py
+++ b/erpnext/payroll/doctype/gratuity/test_gratuity.py
@@ -18,27 +18,25 @@
test_dependencies = ["Salary Component", "Salary Slip", "Account"]
class TestGratuity(unittest.TestCase):
- @classmethod
- def setUpClass(cls):
+ def setUp(self):
+ frappe.db.delete("Gratuity")
+ frappe.db.delete("Additional Salary", {"ref_doctype": "Gratuity"})
+
make_earning_salary_component(setup=True, test_tax=True, company_list=['_Test Company'])
make_deduction_salary_component(setup=True, test_tax=True, company_list=['_Test Company'])
- def setUp(self):
- frappe.db.sql("DELETE FROM `tabGratuity`")
-
def test_get_last_salary_slip_should_return_none_for_new_employee(self):
new_employee = make_employee("new_employee@salary.com", company='_Test Company')
salary_slip = get_last_salary_slip(new_employee)
assert salary_slip is None
- def test_check_gratuity_amount_based_on_current_slab(self):
+ def test_check_gratuity_amount_based_on_current_slab_and_additional_salary_creation(self):
employee, sal_slip = create_employee_and_get_last_salary_slip()
rule = get_gratuity_rule("Rule Under Unlimited Contract on termination (UAE)")
+ gratuity = create_gratuity(pay_via_salary_slip=1, employee=employee, rule=rule.name)
- gratuity = create_gratuity(employee=employee, rule=rule.name)
-
- #work experience calculation
+ # work experience calculation
date_of_joining, relieving_date = frappe.db.get_value('Employee', employee, ['date_of_joining', 'relieving_date'])
employee_total_workings_days = (get_datetime(relieving_date) - get_datetime(date_of_joining)).days
@@ -64,6 +62,9 @@
self.assertEqual(flt(gratuity_amount, 2), flt(gratuity.amount, 2))
+ # additional salary creation (Pay via salary slip)
+ self.assertTrue(frappe.db.exists("Additional Salary", {"ref_docname": gratuity.name}))
+
def test_check_gratuity_amount_based_on_all_previous_slabs(self):
employee, sal_slip = create_employee_and_get_last_salary_slip()
rule = get_gratuity_rule("Rule Under Limited Contract (UAE)")
@@ -117,8 +118,8 @@
self.assertEqual(flt(gratuity.paid_amount,2), flt(gratuity.amount, 2))
def tearDown(self):
- frappe.db.sql("DELETE FROM `tabGratuity`")
- frappe.db.sql("DELETE FROM `tabAdditional Salary` WHERE ref_doctype = 'Gratuity'")
+ frappe.db.rollback()
+
def get_gratuity_rule(name):
rule = frappe.db.exists("Gratuity Rule", name)
@@ -141,9 +142,14 @@
gratuity.employee = args.employee
gratuity.posting_date = getdate()
gratuity.gratuity_rule = args.rule or "Rule Under Limited Contract (UAE)"
- gratuity.expense_account = args.expense_account or 'Payment Account - _TC'
- gratuity.payable_account = args.payable_account or get_payable_account("_Test Company")
- gratuity.mode_of_payment = args.mode_of_payment or 'Cash'
+ gratuity.pay_via_salary_slip = args.pay_via_salary_slip or 0
+ if gratuity.pay_via_salary_slip:
+ gratuity.payroll_date = getdate()
+ gratuity.salary_component = "Performance Bonus"
+ else:
+ gratuity.expense_account = args.expense_account or 'Payment Account - _TC'
+ gratuity.payable_account = args.payable_account or get_payable_account("_Test Company")
+ gratuity.mode_of_payment = args.mode_of_payment or 'Cash'
gratuity.save()
gratuity.submit()
diff --git a/erpnext/payroll/doctype/payroll_entry/payroll_entry.py b/erpnext/payroll/doctype/payroll_entry/payroll_entry.py
index db88c06..a634dfe 100644
--- a/erpnext/payroll/doctype/payroll_entry/payroll_entry.py
+++ b/erpnext/payroll/doctype/payroll_entry/payroll_entry.py
@@ -527,11 +527,12 @@
""" % cond, {"sal_struct": tuple(sal_struct), "from_date": end_date, "payroll_payable_account": payroll_payable_account}, as_dict=True)
def remove_payrolled_employees(emp_list, start_date, end_date):
+ new_emp_list = []
for employee_details in emp_list:
- if frappe.db.exists("Salary Slip", {"employee": employee_details.employee, "start_date": start_date, "end_date": end_date, "docstatus": 1}):
- emp_list.remove(employee_details)
+ if not frappe.db.exists("Salary Slip", {"employee": employee_details.employee, "start_date": start_date, "end_date": end_date, "docstatus": 1}):
+ new_emp_list.append(employee_details)
- return emp_list
+ return new_emp_list
@frappe.whitelist()
def get_start_end_dates(payroll_frequency, start_date=None, company=None):
diff --git a/erpnext/payroll/doctype/payroll_entry/test_payroll_entry.py b/erpnext/payroll/doctype/payroll_entry/test_payroll_entry.py
index 5f836db..3b7f4b2 100644
--- a/erpnext/payroll/doctype/payroll_entry/test_payroll_entry.py
+++ b/erpnext/payroll/doctype/payroll_entry/test_payroll_entry.py
@@ -124,7 +124,7 @@
if not frappe.db.exists("Account", "_Test Payroll Payable - _TC"):
create_account(account_name="_Test Payroll Payable",
- company="_Test Company", parent_account="Current Liabilities - _TC")
+ company="_Test Company", parent_account="Current Liabilities - _TC", account_type="Payable")
if not frappe.db.get_value("Company", "_Test Company", "default_payroll_payable_account") or \
frappe.db.get_value("Company", "_Test Company", "default_payroll_payable_account") != "_Test Payroll Payable - _TC":
diff --git a/erpnext/payroll/doctype/salary_slip/salary_slip.py b/erpnext/payroll/doctype/salary_slip/salary_slip.py
index f727ff4..b44dbb9 100644
--- a/erpnext/payroll/doctype/salary_slip/salary_slip.py
+++ b/erpnext/payroll/doctype/salary_slip/salary_slip.py
@@ -307,28 +307,59 @@
if payroll_based_on == "Attendance":
self.payment_days -= flt(absent)
- unmarked_days = self.get_unmarked_days()
consider_unmarked_attendance_as = frappe.db.get_value("Payroll Settings", None, "consider_unmarked_attendance_as") or "Present"
if payroll_based_on == "Attendance" and consider_unmarked_attendance_as =="Absent":
+ unmarked_days = self.get_unmarked_days(include_holidays_in_total_working_days)
self.absent_days += unmarked_days #will be treated as absent
self.payment_days -= unmarked_days
- if include_holidays_in_total_working_days:
- for holiday in holidays:
- if not frappe.db.exists("Attendance", {"employee": self.employee, "attendance_date": holiday, "docstatus": 1 }):
- self.payment_days += 1
else:
self.payment_days = 0
- def get_unmarked_days(self):
- marked_days = frappe.get_all("Attendance", filters = {
- "attendance_date": ["between", [self.start_date, self.end_date]],
- "employee": self.employee,
- "docstatus": 1
- }, fields = ["COUNT(*) as marked_days"])[0].marked_days
+ def get_unmarked_days(self, include_holidays_in_total_working_days):
+ unmarked_days = self.total_working_days
+ joining_date, relieving_date = frappe.get_cached_value("Employee", self.employee,
+ ["date_of_joining", "relieving_date"])
+ start_date = self.start_date
+ end_date = self.end_date
- return self.total_working_days - marked_days
+ if joining_date and (getdate(self.start_date) < joining_date <= getdate(self.end_date)):
+ start_date = joining_date
+ unmarked_days = self.get_unmarked_days_based_on_doj_or_relieving(unmarked_days,
+ include_holidays_in_total_working_days, self.start_date, joining_date)
+ if relieving_date and (getdate(self.start_date) <= relieving_date < getdate(self.end_date)):
+ end_date = relieving_date
+ unmarked_days = self.get_unmarked_days_based_on_doj_or_relieving(unmarked_days,
+ include_holidays_in_total_working_days, relieving_date, self.end_date)
+
+ # exclude days for which attendance has been marked
+ unmarked_days -= frappe.get_all("Attendance", filters = {
+ "attendance_date": ["between", [start_date, end_date]],
+ "employee": self.employee,
+ "docstatus": 1
+ }, fields = ["COUNT(*) as marked_days"])[0].marked_days
+
+ return unmarked_days
+
+ def get_unmarked_days_based_on_doj_or_relieving(self, unmarked_days,
+ include_holidays_in_total_working_days, start_date, end_date):
+ """
+ Exclude days before DOJ or after
+ Relieving Date from unmarked days
+ """
+ from erpnext.hr.doctype.employee.employee import is_holiday
+
+ if include_holidays_in_total_working_days:
+ unmarked_days -= date_diff(end_date, start_date)
+ else:
+ # exclude only if not holidays
+ for days in range(date_diff(end_date, start_date)):
+ date = add_days(end_date, -days)
+ if not is_holiday(self.employee, date):
+ unmarked_days -= 1
+
+ return unmarked_days
def get_payment_days(self, joining_date, relieving_date, include_holidays_in_total_working_days):
if not joining_date:
@@ -1268,7 +1299,7 @@
for i, earning in enumerate(self.earnings):
if earning.salary_component == salary_component:
self.earnings[i].amount = wages_amount
- self.gross_pay += self.earnings[i].amount
+ self.gross_pay += flt(self.earnings[i].amount, earning.precision("amount"))
self.net_pay = flt(self.gross_pay) - flt(self.total_deduction)
def compute_year_to_date(self):
diff --git a/erpnext/payroll/doctype/salary_slip/test_salary_slip.py b/erpnext/payroll/doctype/salary_slip/test_salary_slip.py
index 30b604b..fe15f2d 100644
--- a/erpnext/payroll/doctype/salary_slip/test_salary_slip.py
+++ b/erpnext/payroll/doctype/salary_slip/test_salary_slip.py
@@ -6,10 +6,13 @@
import unittest
import frappe
+from frappe.model.document import Document
+from frappe.tests.utils import change_settings
from frappe.utils import (
add_days,
add_months,
cstr,
+ date_diff,
flt,
get_first_day,
get_last_day,
@@ -20,6 +23,7 @@
import erpnext
from erpnext.accounts.utils import get_fiscal_year
+from erpnext.hr.doctype.attendance.attendance import mark_attendance
from erpnext.hr.doctype.employee.test_employee import make_employee
from erpnext.hr.doctype.leave_allocation.test_leave_allocation import create_leave_allocation
from erpnext.hr.doctype.leave_type.test_leave_type import create_leave_type
@@ -36,17 +40,17 @@
setup_test()
def tearDown(self):
+ frappe.db.rollback()
frappe.db.set_value("Payroll Settings", None, "include_holidays_in_total_working_days", 0)
frappe.set_user("Administrator")
+ @change_settings("Payroll Settings", {
+ "payroll_based_on": "Attendance",
+ "daily_wages_fraction_for_half_day": 0.75
+ })
def test_payment_days_based_on_attendance(self):
- from erpnext.hr.doctype.attendance.attendance import mark_attendance
no_of_days = self.get_no_of_days()
- # Payroll based on attendance
- frappe.db.set_value("Payroll Settings", None, "payroll_based_on", "Attendance")
- frappe.db.set_value("Payroll Settings", None, "daily_wages_fraction_for_half_day", 0.75)
-
emp_id = make_employee("test_payment_days_based_on_attendance@salary.com")
frappe.db.set_value("Employee", emp_id, {"relieving_date": None, "status": "Active"})
@@ -84,14 +88,78 @@
self.assertEqual(ss.gross_pay, gross_pay)
- frappe.db.set_value("Payroll Settings", None, "payroll_based_on", "Leave")
+ @change_settings("Payroll Settings", {
+ "payroll_based_on": "Attendance",
+ "consider_unmarked_attendance_as": "Absent",
+ "include_holidays_in_total_working_days": True
+ })
+ def test_payment_days_for_mid_joinee_including_holidays(self):
+ from erpnext.hr.doctype.holiday_list.holiday_list import is_holiday
+ no_of_days = self.get_no_of_days()
+ month_start_date, month_end_date = get_first_day(nowdate()), get_last_day(nowdate())
+
+ new_emp_id = make_employee("test_payment_days_based_on_joining_date@salary.com")
+ joining_date, relieving_date = add_days(month_start_date, 3), add_days(month_end_date, -5)
+ frappe.db.set_value("Employee", new_emp_id, {
+ "date_of_joining": joining_date,
+ "relieving_date": relieving_date,
+ "status": "Left"
+ })
+
+ holidays = 0
+
+ for days in range(date_diff(relieving_date, joining_date) + 1):
+ date = add_days(joining_date, days)
+ if not is_holiday("Salary Slip Test Holiday List", date):
+ mark_attendance(new_emp_id, date, 'Present', ignore_validate=True)
+ else:
+ holidays += 1
+
+ new_ss = make_employee_salary_slip("test_payment_days_based_on_joining_date@salary.com", "Monthly", "Test Payment Based On Attendence")
+
+ self.assertEqual(new_ss.total_working_days, no_of_days[0])
+ self.assertEqual(new_ss.payment_days, no_of_days[0] - holidays - 8)
+
+ @change_settings("Payroll Settings", {
+ "payroll_based_on": "Attendance",
+ "consider_unmarked_attendance_as": "Absent",
+ "include_holidays_in_total_working_days": False
+ })
+ def test_payment_days_for_mid_joinee_excluding_holidays(self):
+ from erpnext.hr.doctype.holiday_list.holiday_list import is_holiday
+
+ no_of_days = self.get_no_of_days()
+ month_start_date, month_end_date = get_first_day(nowdate()), get_last_day(nowdate())
+
+ new_emp_id = make_employee("test_payment_days_based_on_joining_date@salary.com")
+ joining_date, relieving_date = add_days(month_start_date, 3), add_days(month_end_date, -5)
+ frappe.db.set_value("Employee", new_emp_id, {
+ "date_of_joining": joining_date,
+ "relieving_date": relieving_date,
+ "status": "Left"
+ })
+
+ holidays = 0
+
+ for days in range(date_diff(relieving_date, joining_date) + 1):
+ date = add_days(joining_date, days)
+ if not is_holiday("Salary Slip Test Holiday List", date):
+ mark_attendance(new_emp_id, date, 'Present', ignore_validate=True)
+ else:
+ holidays += 1
+
+ new_ss = make_employee_salary_slip("test_payment_days_based_on_joining_date@salary.com", "Monthly", "Test Payment Based On Attendence")
+
+ self.assertEqual(new_ss.total_working_days, no_of_days[0] - no_of_days[1])
+ self.assertEqual(new_ss.payment_days, no_of_days[0] - holidays - 8)
+
+ @change_settings("Payroll Settings", {
+ "payroll_based_on": "Leave"
+ })
def test_payment_days_based_on_leave_application(self):
no_of_days = self.get_no_of_days()
- # Payroll based on attendance
- frappe.db.set_value("Payroll Settings", None, "payroll_based_on", "Leave")
-
emp_id = make_employee("test_payment_days_based_on_leave_application@salary.com")
frappe.db.set_value("Employee", emp_id, {"relieving_date": None, "status": "Active"})
@@ -132,8 +200,9 @@
self.assertEqual(ss.payment_days, days_in_month - no_of_holidays - 4)
- frappe.db.set_value("Payroll Settings", None, "payroll_based_on", "Leave")
-
+ @change_settings("Payroll Settings", {
+ "payroll_based_on": "Attendance"
+ })
def test_payment_days_in_salary_slip_based_on_timesheet(self):
from erpnext.hr.doctype.attendance.attendance import mark_attendance
from erpnext.projects.doctype.timesheet.test_timesheet import (
@@ -144,9 +213,6 @@
make_salary_slip as make_salary_slip_for_timesheet,
)
- # Payroll based on attendance
- frappe.db.set_value("Payroll Settings", None, "payroll_based_on", "Attendance")
-
emp = make_employee("test_employee_timesheet@salary.com", company="_Test Company", holiday_list="Salary Slip Test Holiday List")
frappe.db.set_value("Employee", emp, {"relieving_date": None, "status": "Active"})
@@ -184,17 +250,15 @@
self.assertEqual(salary_slip.gross_pay, flt(gross_pay, 2))
- frappe.db.set_value("Payroll Settings", None, "payroll_based_on", "Leave")
-
+ @change_settings("Payroll Settings", {
+ "payroll_based_on": "Attendance"
+ })
def test_component_amount_dependent_on_another_payment_days_based_component(self):
from erpnext.hr.doctype.attendance.attendance import mark_attendance
from erpnext.payroll.doctype.salary_structure.test_salary_structure import (
create_salary_structure_assignment,
)
- # Payroll based on attendance
- frappe.db.set_value("Payroll Settings", None, "payroll_based_on", "Attendance")
-
salary_structure = make_salary_structure_for_payment_days_based_component_dependency()
employee = make_employee("test_payment_days_based_component@salary.com", company="_Test Company")
@@ -237,11 +301,12 @@
expected_amount = flt((flt(ss.gross_pay) - payment_days_based_comp_amount) * 0.12, precision)
self.assertEqual(actual_amount, expected_amount)
- frappe.db.set_value("Payroll Settings", None, "payroll_based_on", "Leave")
+ @change_settings("Payroll Settings", {
+ "include_holidays_in_total_working_days": 1
+ })
def test_salary_slip_with_holidays_included(self):
no_of_days = self.get_no_of_days()
- frappe.db.set_value("Payroll Settings", None, "include_holidays_in_total_working_days", 1)
make_employee("test_salary_slip_with_holidays_included@salary.com")
frappe.db.set_value("Employee", frappe.get_value("Employee",
{"employee_name":"test_salary_slip_with_holidays_included@salary.com"}, "name"), "relieving_date", None)
@@ -255,9 +320,11 @@
self.assertEqual(ss.earnings[1].amount, 3000)
self.assertEqual(ss.gross_pay, 78000)
+ @change_settings("Payroll Settings", {
+ "include_holidays_in_total_working_days": 0
+ })
def test_salary_slip_with_holidays_excluded(self):
no_of_days = self.get_no_of_days()
- frappe.db.set_value("Payroll Settings", None, "include_holidays_in_total_working_days", 0)
make_employee("test_salary_slip_with_holidays_excluded@salary.com")
frappe.db.set_value("Employee", frappe.get_value("Employee",
{"employee_name":"test_salary_slip_with_holidays_excluded@salary.com"}, "name"), "relieving_date", None)
@@ -272,14 +339,15 @@
self.assertEqual(ss.earnings[1].amount, 3000)
self.assertEqual(ss.gross_pay, 78000)
+ @change_settings("Payroll Settings", {
+ "include_holidays_in_total_working_days": 1
+ })
def test_payment_days(self):
from erpnext.payroll.doctype.salary_structure.test_salary_structure import (
create_salary_structure_assignment,
)
no_of_days = self.get_no_of_days()
- # Holidays not included in working days
- frappe.db.set_value("Payroll Settings", None, "include_holidays_in_total_working_days", 1)
# set joinng date in the same month
employee = make_employee("test_payment_days@salary.com")
@@ -337,11 +405,12 @@
frappe.set_user("test_employee_salary_slip_read_permission@salary.com")
self.assertTrue(salary_slip_test_employee.has_permission("read"))
+ @change_settings("Payroll Settings", {
+ "email_salary_slip_to_employee": 1
+ })
def test_email_salary_slip(self):
frappe.db.sql("delete from `tabEmail Queue`")
- frappe.db.set_value("Payroll Settings", None, "email_salary_slip_to_employee", 1)
-
make_employee("test_email_salary_slip@salary.com")
ss = make_employee_salary_slip("test_email_salary_slip@salary.com", "Monthly", "Test Salary Slip Email")
ss.company = "_Test Company"
@@ -687,20 +756,25 @@
def make_salary_component(salary_components, test_tax, company_list=None):
for salary_component in salary_components:
- if not frappe.db.exists('Salary Component', salary_component["salary_component"]):
- if test_tax:
- if salary_component["type"] == "Earning":
- salary_component["is_tax_applicable"] = 1
- elif salary_component["salary_component"] == "TDS":
- salary_component["variable_based_on_taxable_salary"] = 1
- salary_component["amount_based_on_formula"] = 0
- salary_component["amount"] = 0
- salary_component["formula"] = ""
- salary_component["condition"] = ""
- salary_component["doctype"] = "Salary Component"
- salary_component["salary_component_abbr"] = salary_component["abbr"]
- frappe.get_doc(salary_component).insert()
- get_salary_component_account(salary_component["salary_component"], company_list)
+ if frappe.db.exists('Salary Component', salary_component["salary_component"]):
+ continue
+
+ if test_tax:
+ if salary_component["type"] == "Earning":
+ salary_component["is_tax_applicable"] = 1
+ elif salary_component["salary_component"] == "TDS":
+ salary_component["variable_based_on_taxable_salary"] = 1
+ salary_component["amount_based_on_formula"] = 0
+ salary_component["amount"] = 0
+ salary_component["formula"] = ""
+ salary_component["condition"] = ""
+
+ salary_component["salary_component_abbr"] = salary_component["abbr"]
+ doc = frappe.new_doc("Salary Component")
+ doc.update(salary_component)
+ doc.insert()
+
+ get_salary_component_account(doc, company_list)
def get_salary_component_account(sal_comp, company_list=None):
company = erpnext.get_default_company()
@@ -708,7 +782,9 @@
if company_list and company not in company_list:
company_list.append(company)
- sal_comp = frappe.get_doc("Salary Component", sal_comp)
+ if not isinstance(sal_comp, Document):
+ sal_comp = frappe.get_doc("Salary Component", sal_comp)
+
if not sal_comp.get("accounts"):
for d in company_list:
company_abbr = frappe.get_cached_value('Company', d, 'abbr')
@@ -726,7 +802,7 @@
})
sal_comp.save()
-def create_account(account_name, company, parent_account):
+def create_account(account_name, company, parent_account, account_type=None):
company_abbr = frappe.get_cached_value('Company', company, 'abbr')
account = frappe.db.get_value("Account", account_name + " - " + company_abbr)
if not account:
@@ -1011,13 +1087,13 @@
frappe.db.set_value('HR Settings', None, 'leave_status_notification_template', None)
frappe.db.set_value('HR Settings', None, 'leave_approval_notification_template', None)
-def make_holiday_list():
+def make_holiday_list(holiday_list_name=None):
fiscal_year = get_fiscal_year(nowdate(), company=erpnext.get_default_company())
- holiday_list = frappe.db.exists("Holiday List", "Salary Slip Test Holiday List")
+ holiday_list = frappe.db.exists("Holiday List", holiday_list_name or "Salary Slip Test Holiday List")
if not holiday_list:
holiday_list = frappe.get_doc({
"doctype": "Holiday List",
- "holiday_list_name": "Salary Slip Test Holiday List",
+ "holiday_list_name": holiday_list_name or "Salary Slip Test Holiday List",
"from_date": fiscal_year[1],
"to_date": fiscal_year[2],
"weekly_off": "Sunday"
diff --git a/erpnext/portal/doctype/homepage_section/test_homepage_section.py b/erpnext/portal/doctype/homepage_section/test_homepage_section.py
index b30d983..c3be146 100644
--- a/erpnext/portal/doctype/homepage_section/test_homepage_section.py
+++ b/erpnext/portal/doctype/homepage_section/test_homepage_section.py
@@ -21,7 +21,7 @@
{'title': 'Card 2', 'subtitle': 'Subtitle 2', 'content': 'This is test card 2', 'image': 'test.jpg'},
],
'no_of_columns': 3
- }).insert()
+ }).insert(ignore_if_duplicate=True)
except frappe.DuplicateEntryError:
pass
diff --git a/erpnext/projects/doctype/timesheet/test_timesheet.py b/erpnext/projects/doctype/timesheet/test_timesheet.py
index 989bcd1..8b60357 100644
--- a/erpnext/projects/doctype/timesheet/test_timesheet.py
+++ b/erpnext/projects/doctype/timesheet/test_timesheet.py
@@ -151,6 +151,35 @@
settings.ignore_employee_time_overlap = initial_setting
settings.save()
+ def test_timesheet_not_overlapping_with_continuous_timelogs(self):
+ emp = make_employee("test_employee_6@salary.com")
+
+ update_activity_type("_Test Activity Type")
+ timesheet = frappe.new_doc("Timesheet")
+ timesheet.employee = emp
+ timesheet.append(
+ 'time_logs',
+ {
+ "billable": 1,
+ "activity_type": "_Test Activity Type",
+ "from_time": now_datetime(),
+ "to_time": now_datetime() + datetime.timedelta(hours=3),
+ "company": "_Test Company"
+ }
+ )
+ timesheet.append(
+ 'time_logs',
+ {
+ "billable": 1,
+ "activity_type": "_Test Activity Type",
+ "from_time": now_datetime() + datetime.timedelta(hours=3),
+ "to_time": now_datetime() + datetime.timedelta(hours=4),
+ "company": "_Test Company"
+ }
+ )
+
+ timesheet.save() # should not throw an error
+
def test_to_time(self):
emp = make_employee("test_employee_6@salary.com")
from_time = now_datetime()
diff --git a/erpnext/projects/doctype/timesheet/timesheet.js b/erpnext/projects/doctype/timesheet/timesheet.js
index f615f05..453d46c 100644
--- a/erpnext/projects/doctype/timesheet/timesheet.js
+++ b/erpnext/projects/doctype/timesheet/timesheet.js
@@ -116,7 +116,7 @@
currency: function(frm) {
let base_currency = frappe.defaults.get_global_default('currency');
- if (base_currency != frm.doc.currency) {
+ if (frm.doc.currency && (base_currency != frm.doc.currency)) {
frappe.call({
method: "erpnext.setup.utils.get_exchange_rate",
args: {
diff --git a/erpnext/projects/doctype/timesheet/timesheet.py b/erpnext/projects/doctype/timesheet/timesheet.py
index dd0b5f9..b44d501 100644
--- a/erpnext/projects/doctype/timesheet/timesheet.py
+++ b/erpnext/projects/doctype/timesheet/timesheet.py
@@ -7,7 +7,7 @@
import frappe
from frappe import _
from frappe.model.document import Document
-from frappe.utils import add_to_date, flt, getdate, time_diff_in_hours
+from frappe.utils import add_to_date, flt, get_datetime, getdate, time_diff_in_hours
from erpnext.controllers.queries import get_match_cond
from erpnext.hr.utils import validate_active_employee
@@ -145,7 +145,7 @@
if not (data.from_time and data.hours):
return
- _to_time = add_to_date(data.from_time, hours=data.hours, as_datetime=True)
+ _to_time = get_datetime(add_to_date(data.from_time, hours=data.hours, as_datetime=True))
if data.to_time != _to_time:
data.to_time = _to_time
@@ -171,39 +171,54 @@
.format(args.idx, self.name, existing.name), OverlapError)
def get_overlap_for(self, fieldname, args, value):
- cond = "ts.`{0}`".format(fieldname)
- if fieldname == 'workstation':
- cond = "tsd.`{0}`".format(fieldname)
+ timesheet = frappe.qb.DocType("Timesheet")
+ timelog = frappe.qb.DocType("Timesheet Detail")
- existing = frappe.db.sql("""select ts.name as name, tsd.from_time as from_time, tsd.to_time as to_time from
- `tabTimesheet Detail` tsd, `tabTimesheet` ts where {0}=%(val)s and tsd.parent = ts.name and
- (
- (%(from_time)s > tsd.from_time and %(from_time)s < tsd.to_time) or
- (%(to_time)s > tsd.from_time and %(to_time)s < tsd.to_time) or
- (%(from_time)s <= tsd.from_time and %(to_time)s >= tsd.to_time))
- and tsd.name!=%(name)s
- and ts.name!=%(parent)s
- and ts.docstatus < 2""".format(cond),
- {
- "val": value,
- "from_time": args.from_time,
- "to_time": args.to_time,
- "name": args.name or "No Name",
- "parent": args.parent or "No Name"
- }, as_dict=True)
- # check internal overlap
- for time_log in self.time_logs:
- if not (time_log.from_time and time_log.to_time
- and args.from_time and args.to_time): continue
+ from_time = get_datetime(args.from_time)
+ to_time = get_datetime(args.to_time)
- if (fieldname != 'workstation' or args.get(fieldname) == time_log.get(fieldname)) and \
- args.idx != time_log.idx and ((args.from_time > time_log.from_time and args.from_time < time_log.to_time) or
- (args.to_time > time_log.from_time and args.to_time < time_log.to_time) or
- (args.from_time <= time_log.from_time and args.to_time >= time_log.to_time)):
- return self
+ existing = (
+ frappe.qb.from_(timesheet)
+ .join(timelog)
+ .on(timelog.parent == timesheet.name)
+ .select(timesheet.name.as_('name'), timelog.from_time.as_('from_time'), timelog.to_time.as_('to_time'))
+ .where(
+ (timelog.name != (args.name or "No Name"))
+ & (timesheet.name != (args.parent or "No Name"))
+ & (timesheet.docstatus < 2)
+ & (timesheet[fieldname] == value)
+ & (
+ ((from_time > timelog.from_time) & (from_time < timelog.to_time))
+ | ((to_time > timelog.from_time) & (to_time < timelog.to_time))
+ | ((from_time <= timelog.from_time) & (to_time >= timelog.to_time))
+ )
+ )
+ ).run(as_dict=True)
+
+ if self.check_internal_overlap(fieldname, args):
+ return self
return existing[0] if existing else None
+ def check_internal_overlap(self, fieldname, args):
+ for time_log in self.time_logs:
+ if not (time_log.from_time and time_log.to_time
+ and args.from_time and args.to_time):
+ continue
+
+ from_time = get_datetime(time_log.from_time)
+ to_time = get_datetime(time_log.to_time)
+ args_from_time = get_datetime(args.from_time)
+ args_to_time = get_datetime(args.to_time)
+
+ if (args.get(fieldname) == time_log.get(fieldname)) and (args.idx != time_log.idx) and (
+ (args_from_time > from_time and args_from_time < to_time)
+ or (args_to_time > from_time and args_to_time < to_time)
+ or (args_from_time <= from_time and args_to_time >= to_time)
+ ):
+ return True
+ return False
+
def update_cost(self):
for data in self.time_logs:
if data.activity_type or data.is_billable:
diff --git a/erpnext/projects/doctype/timesheet_detail/timesheet_detail.json b/erpnext/projects/doctype/timesheet_detail/timesheet_detail.json
index ee04c61..90fdb83 100644
--- a/erpnext/projects/doctype/timesheet_detail/timesheet_detail.json
+++ b/erpnext/projects/doctype/timesheet_detail/timesheet_detail.json
@@ -14,12 +14,6 @@
"to_time",
"hours",
"completed",
- "section_break_7",
- "completed_qty",
- "workstation",
- "column_break_12",
- "operation",
- "operation_id",
"project_details",
"project",
"project_name",
@@ -84,43 +78,6 @@
"label": "Completed"
},
{
- "fieldname": "section_break_7",
- "fieldtype": "Section Break"
- },
- {
- "depends_on": "eval:parent.work_order",
- "fieldname": "completed_qty",
- "fieldtype": "Float",
- "label": "Completed Qty"
- },
- {
- "depends_on": "eval:parent.work_order",
- "fieldname": "workstation",
- "fieldtype": "Link",
- "label": "Workstation",
- "options": "Workstation",
- "read_only": 1
- },
- {
- "fieldname": "column_break_12",
- "fieldtype": "Column Break"
- },
- {
- "depends_on": "eval:parent.work_order",
- "fieldname": "operation",
- "fieldtype": "Link",
- "label": "Operation",
- "options": "Operation",
- "read_only": 1
- },
- {
- "depends_on": "eval:parent.work_order",
- "fieldname": "operation_id",
- "fieldtype": "Data",
- "hidden": 1,
- "label": "Operation Id"
- },
- {
"fieldname": "project_details",
"fieldtype": "Section Break"
},
@@ -267,7 +224,7 @@
"idx": 1,
"istable": 1,
"links": [],
- "modified": "2021-05-18 12:19:33.205940",
+ "modified": "2022-02-17 16:53:34.878798",
"modified_by": "Administrator",
"module": "Projects",
"name": "Timesheet Detail",
@@ -275,5 +232,6 @@
"permissions": [],
"quick_entry": 1,
"sort_field": "modified",
- "sort_order": "ASC"
+ "sort_order": "ASC",
+ "states": []
}
\ No newline at end of file
diff --git a/erpnext/projects/report/project_profitability/test_project_profitability.py b/erpnext/projects/report/project_profitability/test_project_profitability.py
index 1eb3d0d..3ca28c1 100644
--- a/erpnext/projects/report/project_profitability/test_project_profitability.py
+++ b/erpnext/projects/report/project_profitability/test_project_profitability.py
@@ -1,6 +1,5 @@
-import unittest
-
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import add_days, getdate
from erpnext.hr.doctype.employee.test_employee import make_employee
@@ -12,7 +11,7 @@
from erpnext.projects.report.project_profitability.project_profitability import execute
-class TestProjectProfitability(unittest.TestCase):
+class TestProjectProfitability(FrappeTestCase):
def setUp(self):
frappe.db.sql('delete from `tabTimesheet`')
emp = make_employee('test_employee_9@salary.com', company='_Test Company')
@@ -67,6 +66,3 @@
fractional_cost = self.salary_slip.base_gross_pay * utilization
self.assertEqual(fractional_cost, row.fractional_cost)
-
- def tearDown(self):
- frappe.db.rollback()
diff --git a/erpnext/public/build.json b/erpnext/public/build.json
index 569910d..91a752c 100644
--- a/erpnext/public/build.json
+++ b/erpnext/public/build.json
@@ -39,7 +39,8 @@
"public/js/utils/dimension_tree_filter.js",
"public/js/telephony.js",
"public/js/templates/call_link.html",
- "public/js/templates/node_card.html"
+ "public/js/templates/node_card.html",
+ "public/js/bulk_transaction_processing.js"
],
"js/item-dashboard.min.js": [
"stock/dashboard/item_dashboard.html",
diff --git a/erpnext/public/js/bank_reconciliation_tool/dialog_manager.js b/erpnext/public/js/bank_reconciliation_tool/dialog_manager.js
index ca73393..214a1be 100644
--- a/erpnext/public/js/bank_reconciliation_tool/dialog_manager.js
+++ b/erpnext/public/js/bank_reconciliation_tool/dialog_manager.js
@@ -182,6 +182,12 @@
onchange: () => this.update_options(),
},
{
+ fieldtype: "Check",
+ label: "Loan Repayment",
+ fieldname: "loan_repayment",
+ onchange: () => this.update_options(),
+ },
+ {
fieldname: "column_break_5",
fieldtype: "Column Break",
},
@@ -191,7 +197,6 @@
fieldname: "sales_invoice",
onchange: () => this.update_options(),
},
-
{
fieldtype: "Check",
label: "Purchase Invoice",
@@ -199,6 +204,12 @@
onchange: () => this.update_options(),
},
{
+ fieldtype: "Check",
+ label: "Show Only Exact Amount",
+ fieldname: "exact_match",
+ onchange: () => this.update_options(),
+ },
+ {
fieldname: "column_break_5",
fieldtype: "Column Break",
},
@@ -210,8 +221,8 @@
},
{
fieldtype: "Check",
- label: "Show Only Exact Amount",
- fieldname: "exact_match",
+ label: "Loan Disbursement",
+ fieldname: "loan_disbursement",
onchange: () => this.update_options(),
},
{
diff --git a/erpnext/public/js/bulk_transaction_processing.js b/erpnext/public/js/bulk_transaction_processing.js
new file mode 100644
index 0000000..101f50c
--- /dev/null
+++ b/erpnext/public/js/bulk_transaction_processing.js
@@ -0,0 +1,30 @@
+frappe.provide("erpnext.bulk_transaction_processing");
+
+$.extend(erpnext.bulk_transaction_processing, {
+ create: function(listview, from_doctype, to_doctype) {
+ let checked_items = listview.get_checked_items();
+ const doc_name = [];
+ checked_items.forEach((Item)=> {
+ if (Item.docstatus == 0) {
+ doc_name.push(Item.name);
+ }
+ });
+
+ let count_of_rows = checked_items.length;
+ frappe.confirm(__("Create {0} {1} ?", [count_of_rows, to_doctype]), ()=>{
+ if (doc_name.length == 0) {
+ frappe.call({
+ method: "erpnext.utilities.bulk_transaction.transaction_processing",
+ args: {data: checked_items, from_doctype: from_doctype, to_doctype: to_doctype}
+ }).then(()=> {
+
+ });
+ if (count_of_rows > 10) {
+ frappe.show_alert("Starting a background job to create {0} {1}", [count_of_rows, to_doctype]);
+ }
+ } else {
+ frappe.msgprint(__("Selected document must be in submitted state"));
+ }
+ });
+ }
+});
\ No newline at end of file
diff --git a/erpnext/public/js/controllers/transaction.js b/erpnext/public/js/controllers/transaction.js
index 3791741..00373a6 100644
--- a/erpnext/public/js/controllers/transaction.js
+++ b/erpnext/public/js/controllers/transaction.js
@@ -525,6 +525,7 @@
item.weight_per_unit = 0;
item.weight_uom = '';
+ item.conversion_factor = 0;
if(['Sales Invoice'].includes(this.frm.doc.doctype)) {
update_stock = cint(me.frm.doc.update_stock);
@@ -719,6 +720,7 @@
'posting_time': posting_time,
'qty': item.qty * item.conversion_factor,
'serial_no': item.serial_no,
+ 'batch_no': item.batch_no,
'voucher_type': voucher_type,
'company': company,
'allow_zero_valuation_rate': item.allow_zero_valuation_rate
@@ -1463,7 +1465,8 @@
"item_code": d.item_code,
"pricing_rules": d.pricing_rules,
"parenttype": d.parenttype,
- "parent": d.parent
+ "parent": d.parent,
+ "price_list_rate": d.price_list_rate
})
}
});
@@ -2282,18 +2285,15 @@
}
coupon_code() {
- var me = this;
- if (this.frm.doc.coupon_code) {
- frappe.run_serially([
+ if (this.frm.doc.coupon_code || this.frm._last_coupon_code) {
+ // reset pricing rules if coupon code is set or is unset
+ const _ignore_pricing_rule = this.frm.doc.ignore_pricing_rule;
+ return frappe.run_serially([
() => this.frm.doc.ignore_pricing_rule=1,
- () => me.ignore_pricing_rule(),
- () => this.frm.doc.ignore_pricing_rule=0,
- () => me.apply_pricing_rule()
- ]);
- } else {
- frappe.run_serially([
- () => this.frm.doc.ignore_pricing_rule=1,
- () => me.ignore_pricing_rule()
+ () => this.frm.trigger('ignore_pricing_rule'),
+ () => this.frm.doc.ignore_pricing_rule=_ignore_pricing_rule,
+ () => this.frm.trigger('apply_pricing_rule'),
+ () => this.frm._last_coupon_code = this.frm.doc.coupon_code
]);
}
}
diff --git a/erpnext/public/js/education/student_button.html b/erpnext/public/js/education/student_button.html
deleted file mode 100644
index b64c73a..0000000
--- a/erpnext/public/js/education/student_button.html
+++ /dev/null
@@ -1,17 +0,0 @@
-<div class="col-sm-3">
- <div class="checkbox">
- <label>
- <input
- type="checkbox"
- data-group_roll_number="{{group_roll_number}}"
- data-student="{{student}}"
- data-student-name="{{student_name}}"
- class="students-check"
- {% if status === "Present" %}
- checked
- {% endif %}
- >
- {{ group_roll_number }} - {{ student_name }}
- </label>
- </div>
-</div>
diff --git a/erpnext/public/js/erpnext.bundle.js b/erpnext/public/js/erpnext.bundle.js
index 5259bdc..8409e78 100644
--- a/erpnext/public/js/erpnext.bundle.js
+++ b/erpnext/public/js/erpnext.bundle.js
@@ -16,11 +16,11 @@
import "./utils/item_quick_entry";
import "./utils/customer_quick_entry";
import "./utils/supplier_quick_entry";
-import "./education/student_button.html";
import "./education/assessment_result_tool.html";
import "./call_popup/call_popup";
import "./utils/dimension_tree_filter";
import "./telephony";
import "./templates/call_link.html";
+import "./bulk_transaction_processing";
// import { sum } from 'frappe/public/utils/util.js'
diff --git a/erpnext/public/js/hierarchy_chart/hierarchy_chart_desktop.js b/erpnext/public/js/hierarchy_chart/hierarchy_chart_desktop.js
index 831626a..a585aa6 100644
--- a/erpnext/public/js/hierarchy_chart/hierarchy_chart_desktop.js
+++ b/erpnext/public/js/hierarchy_chart/hierarchy_chart_desktop.js
@@ -304,12 +304,13 @@
}
get_child_nodes(node_id) {
+ let me = this;
return new Promise(resolve => {
frappe.call({
- method: this.method,
+ method: me.method,
args: {
parent: node_id,
- company: this.company
+ company: me.company
}
}).then(r => resolve(r.message));
});
@@ -350,12 +351,13 @@
}
get_all_nodes() {
+ let me = this;
return new Promise(resolve => {
frappe.call({
method: 'erpnext.utilities.hierarchy_chart.get_all_nodes',
args: {
- method: this.method,
- company: this.company
+ method: me.method,
+ company: me.company
},
callback: (r) => {
resolve(r.message);
@@ -427,8 +429,8 @@
add_connector(parent_id, child_id) {
// using pure javascript for better performance
- const parent_node = document.querySelector(`#${parent_id}`);
- const child_node = document.querySelector(`#${child_id}`);
+ const parent_node = document.getElementById(`${parent_id}`);
+ const child_node = document.getElementById(`${child_id}`);
let path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
diff --git a/erpnext/public/js/hierarchy_chart/hierarchy_chart_mobile.js b/erpnext/public/js/hierarchy_chart/hierarchy_chart_mobile.js
index 0a8ba78..52236e7 100644
--- a/erpnext/public/js/hierarchy_chart/hierarchy_chart_mobile.js
+++ b/erpnext/public/js/hierarchy_chart/hierarchy_chart_mobile.js
@@ -235,7 +235,7 @@
let me = this;
return new Promise(resolve => {
frappe.call({
- method: this.method,
+ method: me.method,
args: {
parent: node_id,
company: me.company,
@@ -286,8 +286,8 @@
}
add_connector(parent_id, child_id) {
- const parent_node = document.querySelector(`#${parent_id}`);
- const child_node = document.querySelector(`#${child_id}`);
+ const parent_node = document.getElementById(`${parent_id}`);
+ const child_node = document.getElementById(`${child_id}`);
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
@@ -518,7 +518,8 @@
level.nextAll('li').remove();
let node_object = this.nodes[node.id];
- let current_node = level.find(`#${node.id}`).detach();
+ let current_node = level.find(`[id="${node.id}"]`).detach();
+
current_node.removeClass('active-child active-path');
node_object.expanded = 0;
diff --git a/erpnext/public/js/setup_wizard.js b/erpnext/public/js/setup_wizard.js
index e746ce9..83b69ae 100644
--- a/erpnext/public/js/setup_wizard.js
+++ b/erpnext/public/js/setup_wizard.js
@@ -78,11 +78,11 @@
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, 5).toUpperCase());
+ 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 > 5) {
+ 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("");
}
@@ -96,7 +96,7 @@
if (!this.values.company_abbr) {
return false;
}
- if (this.values.company_abbr.length > 5) {
+ if (this.values.company_abbr.length > 10) {
return false;
}
return true;
diff --git a/erpnext/public/scss/shopping_cart.scss b/erpnext/public/scss/shopping_cart.scss
index 4b645b9..666043b 100644
--- a/erpnext/public/scss/shopping_cart.scss
+++ b/erpnext/public/scss/shopping_cart.scss
@@ -338,14 +338,14 @@
.btn-add-to-wishlist {
svg use {
- stroke: #F47A7A;
+ --icon-stroke: #F47A7A;
}
}
.btn-view-in-wishlist {
svg use {
fill: #F47A7A;
- stroke: none;
+ --icon-stroke: none;
}
}
@@ -1022,7 +1022,7 @@
.not-wished {
cursor: pointer;
- stroke: #F47A7A !important;
+ --icon-stroke: #F47A7A !important;
&:hover {
fill: #F47A7A;
@@ -1030,7 +1030,7 @@
}
.wished {
- stroke: none;
+ --icon-stroke: none;
fill: #F47A7A !important;
}
diff --git a/erpnext/regional/doctype/tax_exemption_80g_certificate/__init__.py b/erpnext/regional/doctype/tax_exemption_80g_certificate/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/regional/doctype/tax_exemption_80g_certificate/__init__.py
+++ /dev/null
diff --git a/erpnext/regional/doctype/tax_exemption_80g_certificate/tax_exemption_80g_certificate.js b/erpnext/regional/doctype/tax_exemption_80g_certificate/tax_exemption_80g_certificate.js
deleted file mode 100644
index 54cde9c..0000000
--- a/erpnext/regional/doctype/tax_exemption_80g_certificate/tax_exemption_80g_certificate.js
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Tax Exemption 80G Certificate', {
- refresh: function(frm) {
- if (frm.doc.donor) {
- frm.set_query('donation', function() {
- return {
- filters: {
- docstatus: 1,
- donor: frm.doc.donor
- }
- };
- });
- }
- },
-
- recipient: function(frm) {
- if (frm.doc.recipient === 'Donor') {
- frm.set_value({
- 'member': '',
- 'member_name': '',
- 'member_email': '',
- 'member_pan_number': '',
- 'fiscal_year': '',
- 'total': 0,
- 'payments': []
- });
- } else {
- frm.set_value({
- 'donor': '',
- 'donor_name': '',
- 'donor_email': '',
- 'donor_pan_number': '',
- 'donation': '',
- 'date_of_donation': '',
- 'amount': 0,
- 'mode_of_payment': '',
- 'razorpay_payment_id': ''
- });
- }
- },
-
- get_payments: function(frm) {
- frm.call({
- doc: frm.doc,
- method: 'get_payments',
- freeze: true
- });
- },
-
- company: function(frm) {
- if ((frm.doc.member || frm.doc.donor) && frm.doc.company) {
- frm.call({
- doc: frm.doc,
- method: 'set_company_address',
- freeze: true
- });
- }
- },
-
- donation: function(frm) {
- if (frm.doc.recipient === 'Donor' && !frm.doc.donor) {
- frappe.msgprint(__('Please select donor first'));
- }
- }
-});
diff --git a/erpnext/regional/doctype/tax_exemption_80g_certificate/tax_exemption_80g_certificate.json b/erpnext/regional/doctype/tax_exemption_80g_certificate/tax_exemption_80g_certificate.json
deleted file mode 100644
index 9eee722..0000000
--- a/erpnext/regional/doctype/tax_exemption_80g_certificate/tax_exemption_80g_certificate.json
+++ /dev/null
@@ -1,297 +0,0 @@
-{
- "actions": [],
- "autoname": "naming_series:",
- "creation": "2021-02-15 12:37:21.577042",
- "doctype": "DocType",
- "editable_grid": 1,
- "engine": "InnoDB",
- "field_order": [
- "naming_series",
- "recipient",
- "member",
- "member_name",
- "member_email",
- "member_pan_number",
- "donor",
- "donor_name",
- "donor_email",
- "donor_pan_number",
- "column_break_4",
- "date",
- "fiscal_year",
- "section_break_11",
- "company",
- "company_address",
- "company_address_display",
- "column_break_14",
- "company_pan_number",
- "company_80g_number",
- "company_80g_wef",
- "title",
- "section_break_6",
- "get_payments",
- "payments",
- "total",
- "donation_details_section",
- "donation",
- "date_of_donation",
- "amount",
- "column_break_27",
- "mode_of_payment",
- "razorpay_payment_id"
- ],
- "fields": [
- {
- "fieldname": "recipient",
- "fieldtype": "Select",
- "in_list_view": 1,
- "label": "Certificate Recipient",
- "options": "Member\nDonor",
- "reqd": 1
- },
- {
- "depends_on": "eval:doc.recipient === \"Member\";",
- "fieldname": "member",
- "fieldtype": "Link",
- "in_list_view": 1,
- "label": "Member",
- "mandatory_depends_on": "eval:doc.recipient === \"Member\";",
- "options": "Member"
- },
- {
- "depends_on": "eval:doc.recipient === \"Member\";",
- "fetch_from": "member.member_name",
- "fieldname": "member_name",
- "fieldtype": "Data",
- "label": "Member Name",
- "read_only": 1
- },
- {
- "depends_on": "eval:doc.recipient === \"Donor\";",
- "fieldname": "donor",
- "fieldtype": "Link",
- "in_list_view": 1,
- "label": "Donor",
- "mandatory_depends_on": "eval:doc.recipient === \"Donor\";",
- "options": "Donor"
- },
- {
- "fieldname": "column_break_4",
- "fieldtype": "Column Break"
- },
- {
- "fieldname": "date",
- "fieldtype": "Date",
- "label": "Date",
- "reqd": 1
- },
- {
- "depends_on": "eval:doc.recipient === \"Member\";",
- "fieldname": "section_break_6",
- "fieldtype": "Section Break"
- },
- {
- "fieldname": "payments",
- "fieldtype": "Table",
- "label": "Payments",
- "options": "Tax Exemption 80G Certificate Detail"
- },
- {
- "fieldname": "total",
- "fieldtype": "Currency",
- "in_list_view": 1,
- "label": "Total",
- "read_only": 1
- },
- {
- "depends_on": "eval:doc.recipient === \"Member\";",
- "fieldname": "fiscal_year",
- "fieldtype": "Link",
- "in_list_view": 1,
- "label": "Fiscal Year",
- "options": "Fiscal Year"
- },
- {
- "fieldname": "company",
- "fieldtype": "Link",
- "label": "Company",
- "options": "Company",
- "reqd": 1
- },
- {
- "fieldname": "get_payments",
- "fieldtype": "Button",
- "label": "Get Memberships"
- },
- {
- "fieldname": "naming_series",
- "fieldtype": "Select",
- "label": "Naming Series",
- "options": "NPO-80G-.YYYY.-"
- },
- {
- "fieldname": "section_break_11",
- "fieldtype": "Section Break",
- "label": "Company Details"
- },
- {
- "fieldname": "company_address",
- "fieldtype": "Link",
- "label": "Company Address",
- "options": "Address"
- },
- {
- "fieldname": "column_break_14",
- "fieldtype": "Column Break"
- },
- {
- "fetch_from": "company.pan_details",
- "fieldname": "company_pan_number",
- "fieldtype": "Data",
- "label": "PAN Number",
- "read_only": 1
- },
- {
- "fieldname": "company_address_display",
- "fieldtype": "Small Text",
- "hidden": 1,
- "label": "Company Address Display",
- "print_hide": 1,
- "read_only": 1
- },
- {
- "fetch_from": "company.company_80g_number",
- "fieldname": "company_80g_number",
- "fieldtype": "Data",
- "label": "80G Number",
- "read_only": 1
- },
- {
- "fetch_from": "company.with_effect_from",
- "fieldname": "company_80g_wef",
- "fieldtype": "Date",
- "label": "80G With Effect From",
- "read_only": 1
- },
- {
- "depends_on": "eval:doc.recipient === \"Donor\";",
- "fieldname": "donation_details_section",
- "fieldtype": "Section Break",
- "label": "Donation Details"
- },
- {
- "fieldname": "donation",
- "fieldtype": "Link",
- "label": "Donation",
- "mandatory_depends_on": "eval:doc.recipient === \"Donor\";",
- "options": "Donation"
- },
- {
- "fetch_from": "donation.amount",
- "fieldname": "amount",
- "fieldtype": "Currency",
- "label": "Amount",
- "read_only": 1
- },
- {
- "fetch_from": "donation.mode_of_payment",
- "fieldname": "mode_of_payment",
- "fieldtype": "Link",
- "label": "Mode of Payment",
- "options": "Mode of Payment",
- "read_only": 1
- },
- {
- "fetch_from": "donation.razorpay_payment_id",
- "fieldname": "razorpay_payment_id",
- "fieldtype": "Data",
- "label": "RazorPay Payment ID",
- "read_only": 1
- },
- {
- "fetch_from": "donation.date",
- "fieldname": "date_of_donation",
- "fieldtype": "Date",
- "label": "Date of Donation",
- "read_only": 1
- },
- {
- "fieldname": "column_break_27",
- "fieldtype": "Column Break"
- },
- {
- "depends_on": "eval:doc.recipient === \"Donor\";",
- "fetch_from": "donor.donor_name",
- "fieldname": "donor_name",
- "fieldtype": "Data",
- "label": "Donor Name",
- "read_only": 1
- },
- {
- "depends_on": "eval:doc.recipient === \"Donor\";",
- "fetch_from": "donor.email",
- "fieldname": "donor_email",
- "fieldtype": "Data",
- "label": "Email",
- "read_only": 1
- },
- {
- "depends_on": "eval:doc.recipient === \"Member\";",
- "fetch_from": "member.email_id",
- "fieldname": "member_email",
- "fieldtype": "Data",
- "in_list_view": 1,
- "label": "Email",
- "read_only": 1
- },
- {
- "depends_on": "eval:doc.recipient === \"Member\";",
- "fetch_from": "member.pan_number",
- "fieldname": "member_pan_number",
- "fieldtype": "Data",
- "label": "PAN Details",
- "read_only": 1
- },
- {
- "depends_on": "eval:doc.recipient === \"Donor\";",
- "fetch_from": "donor.pan_number",
- "fieldname": "donor_pan_number",
- "fieldtype": "Data",
- "label": "PAN Details",
- "read_only": 1
- },
- {
- "fieldname": "title",
- "fieldtype": "Data",
- "hidden": 1,
- "label": "Title",
- "print_hide": 1
- }
- ],
- "index_web_pages_for_search": 1,
- "links": [],
- "modified": "2021-02-22 00:03:34.215633",
- "modified_by": "Administrator",
- "module": "Regional",
- "name": "Tax Exemption 80G Certificate",
- "owner": "Administrator",
- "permissions": [
- {
- "create": 1,
- "delete": 1,
- "email": 1,
- "export": 1,
- "print": 1,
- "read": 1,
- "report": 1,
- "role": "System Manager",
- "share": 1,
- "write": 1
- }
- ],
- "search_fields": "member, member_name",
- "sort_field": "modified",
- "sort_order": "DESC",
- "title_field": "title",
- "track_changes": 1
-}
\ No newline at end of file
diff --git a/erpnext/regional/doctype/tax_exemption_80g_certificate/tax_exemption_80g_certificate.py b/erpnext/regional/doctype/tax_exemption_80g_certificate/tax_exemption_80g_certificate.py
deleted file mode 100644
index 0f08978..0000000
--- a/erpnext/regional/doctype/tax_exemption_80g_certificate/tax_exemption_80g_certificate.py
+++ /dev/null
@@ -1,104 +0,0 @@
-# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
-# For license information, please see license.txt
-
-
-import frappe
-from frappe import _
-from frappe.contacts.doctype.address.address import get_company_address
-from frappe.model.document import Document
-from frappe.utils import flt, get_link_to_form, getdate
-
-from erpnext.accounts.utils import get_fiscal_year
-
-
-class TaxExemption80GCertificate(Document):
- def validate(self):
- self.validate_date()
- self.validate_duplicates()
- self.validate_company_details()
- self.set_company_address()
- self.calculate_total()
- self.set_title()
-
- def validate_date(self):
- if self.recipient == 'Member':
- if getdate(self.date):
- fiscal_year = get_fiscal_year(fiscal_year=self.fiscal_year, as_dict=True)
-
- if not (fiscal_year.year_start_date <= getdate(self.date) \
- <= fiscal_year.year_end_date):
- frappe.throw(_('The Certificate Date is not in the Fiscal Year {0}').format(frappe.bold(self.fiscal_year)))
-
- def validate_duplicates(self):
- if self.recipient == 'Donor':
- certificate = frappe.db.exists(self.doctype, {
- 'donation': self.donation,
- 'name': ('!=', self.name)
- })
- if certificate:
- frappe.throw(_('An 80G Certificate {0} already exists for the donation {1}').format(
- get_link_to_form(self.doctype, certificate), frappe.bold(self.donation)
- ), title=_('Duplicate Certificate'))
-
- def validate_company_details(self):
- fields = ['company_80g_number', 'with_effect_from', 'pan_details']
- company_details = frappe.db.get_value('Company', self.company, fields, as_dict=True)
- if not company_details.company_80g_number:
- frappe.throw(_('Please set the {0} for company {1}').format(frappe.bold('80G Number'),
- get_link_to_form('Company', self.company)))
-
- if not company_details.pan_details:
- frappe.throw(_('Please set the {0} for company {1}').format(frappe.bold('PAN Number'),
- get_link_to_form('Company', self.company)))
-
- @frappe.whitelist()
- def set_company_address(self):
- address = get_company_address(self.company)
- self.company_address = address.company_address
- self.company_address_display = address.company_address_display
-
- def calculate_total(self):
- if self.recipient == 'Donor':
- return
-
- total = 0
- for entry in self.payments:
- total += flt(entry.amount)
- self.total = total
-
- def set_title(self):
- if self.recipient == 'Member':
- self.title = self.member_name
- else:
- self.title = self.donor_name
-
- @frappe.whitelist()
- def get_payments(self):
- if not self.member:
- frappe.throw(_('Please select a Member first.'))
-
- fiscal_year = get_fiscal_year(fiscal_year=self.fiscal_year, as_dict=True)
-
- memberships = frappe.db.get_all('Membership', {
- 'member': self.member,
- 'from_date': ['between', (fiscal_year.year_start_date, fiscal_year.year_end_date)],
- 'membership_status': ('!=', 'Cancelled')
- }, ['from_date', 'amount', 'name', 'invoice', 'payment_id'], order_by='from_date')
-
- if not memberships:
- frappe.msgprint(_('No Membership Payments found against the Member {0}').format(self.member))
-
- total = 0
- self.payments = []
-
- for doc in memberships:
- self.append('payments', {
- 'date': doc.from_date,
- 'amount': doc.amount,
- 'invoice_id': doc.invoice,
- 'razorpay_payment_id': doc.payment_id,
- 'membership': doc.name
- })
- total += flt(doc.amount)
-
- self.total = total
diff --git a/erpnext/regional/doctype/tax_exemption_80g_certificate/test_tax_exemption_80g_certificate.py b/erpnext/regional/doctype/tax_exemption_80g_certificate/test_tax_exemption_80g_certificate.py
deleted file mode 100644
index 6fa3b85..0000000
--- a/erpnext/regional/doctype/tax_exemption_80g_certificate/test_tax_exemption_80g_certificate.py
+++ /dev/null
@@ -1,106 +0,0 @@
-# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
-# See license.txt
-
-import unittest
-
-import frappe
-from frappe.utils import getdate
-
-from erpnext.accounts.utils import get_fiscal_year
-from erpnext.non_profit.doctype.donation.donation import create_donation
-from erpnext.non_profit.doctype.donation.test_donation import (
- create_donor,
- create_donor_type,
- create_mode_of_payment,
-)
-from erpnext.non_profit.doctype.member.member import create_member
-from erpnext.non_profit.doctype.membership.test_membership import make_membership, setup_membership
-
-
-class TestTaxExemption80GCertificate(unittest.TestCase):
- def setUp(self):
- frappe.db.sql('delete from `tabTax Exemption 80G Certificate`')
- frappe.db.sql('delete from `tabMembership`')
- create_donor_type()
- settings = frappe.get_doc('Non Profit Settings')
- settings.company = '_Test Company'
- settings.donation_company = '_Test Company'
- settings.default_donor_type = '_Test Donor'
- settings.creation_user = 'Administrator'
- settings.save()
-
- company = frappe.get_doc('Company', '_Test Company')
- company.pan_details = 'BBBTI3374C'
- company.company_80g_number = 'NQ.CIT(E)I2018-19/DEL-IE28615-27062018/10087'
- company.with_effect_from = getdate()
- company.save()
-
- def test_duplicate_donation_certificate(self):
- donor = create_donor()
- create_mode_of_payment()
- payment = frappe._dict({
- 'amount': 100,
- 'method': 'Debit Card',
- 'id': 'pay_MeXAmsgeKOhq7O'
- })
- donation = create_donation(donor, payment)
-
- args = frappe._dict({
- 'recipient': 'Donor',
- 'donor': donor.name,
- 'donation': donation.name
- })
- certificate = create_80g_certificate(args)
- certificate.insert()
-
- # check company details
- self.assertEqual(certificate.company_pan_number, 'BBBTI3374C')
- self.assertEqual(certificate.company_80g_number, 'NQ.CIT(E)I2018-19/DEL-IE28615-27062018/10087')
-
- # check donation details
- self.assertEqual(certificate.amount, donation.amount)
-
- duplicate_certificate = create_80g_certificate(args)
- # duplicate validation
- self.assertRaises(frappe.ValidationError, duplicate_certificate.insert)
-
- def test_membership_80g_certificate(self):
- plan = setup_membership()
-
- # make test member
- member_doc = create_member(frappe._dict({
- 'fullname': "_Test_Member",
- 'email': "_test_member_erpnext@example.com",
- 'plan_id': plan.name
- }))
- member_doc.make_customer_and_link()
- member = member_doc.name
-
- membership = make_membership(member, { "from_date": getdate() })
- invoice = membership.generate_invoice(save=True)
-
- args = frappe._dict({
- 'recipient': 'Member',
- 'member': member,
- 'fiscal_year': get_fiscal_year(getdate(), as_dict=True).get('name')
- })
- certificate = create_80g_certificate(args)
- certificate.get_payments()
- certificate.insert()
-
- self.assertEqual(len(certificate.payments), 1)
- self.assertEqual(certificate.payments[0].amount, membership.amount)
- self.assertEqual(certificate.payments[0].invoice_id, invoice.name)
-
-
-def create_80g_certificate(args):
- certificate = frappe.get_doc({
- 'doctype': 'Tax Exemption 80G Certificate',
- 'recipient': args.recipient,
- 'date': getdate(),
- 'company': '_Test Company'
- })
-
- certificate.update(args)
-
- return certificate
diff --git a/erpnext/regional/doctype/tax_exemption_80g_certificate_detail/tax_exemption_80g_certificate_detail.json b/erpnext/regional/doctype/tax_exemption_80g_certificate_detail/tax_exemption_80g_certificate_detail.json
deleted file mode 100644
index dfa817d..0000000
--- a/erpnext/regional/doctype/tax_exemption_80g_certificate_detail/tax_exemption_80g_certificate_detail.json
+++ /dev/null
@@ -1,66 +0,0 @@
-{
- "actions": [],
- "creation": "2021-02-15 12:43:52.754124",
- "doctype": "DocType",
- "editable_grid": 1,
- "engine": "InnoDB",
- "field_order": [
- "date",
- "amount",
- "invoice_id",
- "column_break_4",
- "razorpay_payment_id",
- "membership"
- ],
- "fields": [
- {
- "fieldname": "date",
- "fieldtype": "Date",
- "in_list_view": 1,
- "label": "Date",
- "reqd": 1
- },
- {
- "fieldname": "amount",
- "fieldtype": "Currency",
- "in_list_view": 1,
- "label": "Amount",
- "reqd": 1
- },
- {
- "fieldname": "invoice_id",
- "fieldtype": "Link",
- "in_list_view": 1,
- "label": "Invoice ID",
- "options": "Sales Invoice",
- "reqd": 1
- },
- {
- "fieldname": "razorpay_payment_id",
- "fieldtype": "Data",
- "label": "Razorpay Payment ID"
- },
- {
- "fieldname": "membership",
- "fieldtype": "Link",
- "label": "Membership",
- "options": "Membership"
- },
- {
- "fieldname": "column_break_4",
- "fieldtype": "Column Break"
- }
- ],
- "index_web_pages_for_search": 1,
- "istable": 1,
- "links": [],
- "modified": "2021-02-15 16:35:10.777587",
- "modified_by": "Administrator",
- "module": "Regional",
- "name": "Tax Exemption 80G Certificate Detail",
- "owner": "Administrator",
- "permissions": [],
- "sort_field": "modified",
- "sort_order": "DESC",
- "track_changes": 1
-}
\ No newline at end of file
diff --git a/erpnext/regional/india/e_invoice/einv_item_template.json b/erpnext/regional/india/e_invoice/einv_item_template.json
index 78e5651..2c04c6d 100644
--- a/erpnext/regional/india/e_invoice/einv_item_template.json
+++ b/erpnext/regional/india/e_invoice/einv_item_template.json
@@ -23,9 +23,5 @@
"StateCesAmt": "{item.state_cess_amount}",
"StateCesNonAdvlAmt": "{item.state_cess_nadv_amount}",
"OthChrg": "{item.other_charges}",
- "TotItemVal": "{item.total_value}",
- "BchDtls": {{
- "Nm": "{item.batch_no}",
- "ExpDt": "{item.batch_expiry_date}"
- }}
+ "TotItemVal": "{item.total_value}"
}}
\ 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 e3f7e90..64c75c4 100644
--- a/erpnext/regional/india/e_invoice/utils.py
+++ b/erpnext/regional/india/e_invoice/utils.py
@@ -214,8 +214,6 @@
item.taxable_value = abs(item.taxable_value)
item.discount_amount = 0
- 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
item.is_service_item = 'Y' if item.gst_hsn_code and item.gst_hsn_code[:2] == "99" else 'N'
item.serial_no = ""
diff --git a/erpnext/regional/india/setup.py b/erpnext/regional/india/setup.py
index 074bd52..12b10bb 100644
--- a/erpnext/regional/india/setup.py
+++ b/erpnext/regional/india/setup.py
@@ -53,10 +53,7 @@
hsn_code.description = d["description"]
hsn_code.hsn_code = d[code_field]
hsn_code.name = d[code_field]
- try:
- hsn_code.db_insert()
- except frappe.DuplicateEntryError:
- pass
+ hsn_code.db_insert(ignore_if_duplicate=True)
def add_custom_roles_for_reports():
for report_name in ('GST Sales Register', 'GST Purchase Register',
@@ -114,7 +111,7 @@
def add_print_formats():
frappe.reload_doc("regional", "print_format", "gst_tax_invoice")
- frappe.reload_doc("accounts", "print_format", "gst_pos_invoice")
+ frappe.reload_doc("selling", "print_format", "gst_pos_invoice")
frappe.reload_doc("accounts", "print_format", "GST E-Invoice")
frappe.db.set_value("Print Format", "GST POS Invoice", "disabled", 0)
@@ -610,15 +607,6 @@
dict(fieldname='hra_column_break', fieldtype='Column Break', insert_after='hra_component'),
dict(fieldname='arrear_component', label='Arrear Component',
fieldtype='Link', options='Salary Component', insert_after='hra_column_break'),
- dict(fieldname='non_profit_section', label='Non Profit Settings',
- fieldtype='Section Break', insert_after='arrear_component', collapsible=1),
- dict(fieldname='company_80g_number', label='80G Number',
- fieldtype='Data', insert_after='non_profit_section'),
- dict(fieldname='with_effect_from', label='80G With Effect From',
- fieldtype='Date', insert_after='company_80g_number'),
- dict(fieldname='non_profit_column_break', fieldtype='Column Break', insert_after='with_effect_from'),
- dict(fieldname='pan_details', label='PAN Number',
- fieldtype='Data', insert_after='non_profit_column_break')
],
'Employee Tax Exemption Declaration':[
dict(fieldname='hra_section', label='HRA Exemption',
@@ -713,22 +701,6 @@
'mandatory_depends_on': 'eval:in_list(["SEZ", "Overseas", "Deemed Export"], doc.gst_category)'
}
],
- 'Member': [
- {
- 'fieldname': 'pan_number',
- 'label': 'PAN Details',
- 'fieldtype': 'Data',
- 'insert_after': 'email_id'
- }
- ],
- 'Donor': [
- {
- 'fieldname': 'pan_number',
- 'label': 'PAN Details',
- 'fieldtype': 'Data',
- 'insert_after': 'email'
- }
- ],
'Finance Book': [
{
'fieldname': 'for_income_tax',
diff --git a/erpnext/regional/india/utils.py b/erpnext/regional/india/utils.py
index 8715ef5..d443f9c 100644
--- a/erpnext/regional/india/utils.py
+++ b/erpnext/regional/india/utils.py
@@ -219,7 +219,6 @@
if not party_details.place_of_supply: return party_details
if not party_details.company_gstin: return party_details
- if not party_details.supplier_gstin: return party_details
if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
diff --git a/erpnext/regional/print_format/80g_certificate_for_donation/80g_certificate_for_donation.json b/erpnext/regional/print_format/80g_certificate_for_donation/80g_certificate_for_donation.json
deleted file mode 100644
index a8da0bd..0000000
--- a/erpnext/regional/print_format/80g_certificate_for_donation/80g_certificate_for_donation.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "absolute_value": 0,
- "align_labels_right": 0,
- "creation": "2021-02-22 00:17:33.878581",
- "css": ".details {\n font-size: 15px;\n font-family: Tahoma, sans-serif;;\n line-height: 150%;\n}\n\n.certificate-footer {\n font-size: 15px;\n font-family: Tahoma, sans-serif;\n line-height: 140%;\n margin-top: 120px;\n}\n\n.company-address {\n color: #666666;\n font-size: 15px;\n font-family: Tahoma, sans-serif;;\n}",
- "custom_format": 1,
- "default_print_language": "en",
- "disabled": 0,
- "doc_type": "Tax Exemption 80G Certificate",
- "docstatus": 0,
- "doctype": "Print Format",
- "font": "Default",
- "html": "{% if letter_head and not no_letterhead -%}\n <div class=\"letter-head\">{{ letter_head }}</div>\n{%- endif %}\n\n<div>\n <h3 class=\"text-center\">{{ doc.company }} 80G Donor Certificate</h3>\n</div>\n<br><br>\n\n<div class=\"details\">\n <p> <b>{{ _(\"Certificate No. : \") }}</b> {{ doc.name }} </p>\n <p>\n \t<b>{{ _(\"Date\") }} :</b> {{ doc.get_formatted(\"date\") }}<br>\n </p>\n <br><br>\n \n <div>\n\n This is to confirm that the {{ doc.company }} received an amount of <b>{{doc.get_formatted(\"amount\")}}</b>\n from <b>{{ doc.donor_name }}</b>\n {% if doc.pan_number -%}\n bearing PAN Number {{ doc.member_pan_number }}\n {%- endif %}\n\n via the Mode of Payment {{doc.mode_of_payment}}\n\n {% if doc.razorpay_payment_id -%}\n bearing RazorPay Payment ID {{ doc.razorpay_payment_id }}\n {%- endif %}\n\n on {{ doc.get_formatted(\"date_of_donation\") }}\n <br><br>\n \n <p>\n We thank you for your contribution towards the corpus of the {{ doc.company }} and helping support our work.\n </p>\n\n </div>\n</div>\n\n<br><br>\n<p class=\"company-address text-left\"> {{doc.company_address_display }}</p>\n\n<div class=\"certificate-footer text-center\">\n <p><i>Computer generated receipt - Does not require signature</i></p><br>\n \n {% if doc.company_pan_number %}\n <p>\n <b>{{ doc.company }}'s PAN Account No :</b> {{ doc.company_pan_number }}\n <p><br>\n {% endif %}\n \n <p>\n <b>80G Number : </b> {{ doc.company_80g_number }}\n {% if doc.company_80g_wef %}\n ( w.e.f. {{ doc.get_formatted('company_80g_wef') }} )\n {% endif %}\n </p><br>\n</div>",
- "idx": 0,
- "line_breaks": 0,
- "modified": "2021-02-22 00:20:08.516600",
- "modified_by": "Administrator",
- "module": "Regional",
- "name": "80G Certificate for Donation",
- "owner": "Administrator",
- "print_format_builder": 0,
- "print_format_type": "Jinja",
- "raw_printing": 0,
- "show_section_headings": 0,
- "standard": "Yes"
-}
\ No newline at end of file
diff --git a/erpnext/regional/print_format/80g_certificate_for_donation/__init__.py b/erpnext/regional/print_format/80g_certificate_for_donation/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/regional/print_format/80g_certificate_for_donation/__init__.py
+++ /dev/null
diff --git a/erpnext/regional/print_format/80g_certificate_for_membership/80g_certificate_for_membership.json b/erpnext/regional/print_format/80g_certificate_for_membership/80g_certificate_for_membership.json
deleted file mode 100644
index f1b15aa..0000000
--- a/erpnext/regional/print_format/80g_certificate_for_membership/80g_certificate_for_membership.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "absolute_value": 0,
- "align_labels_right": 0,
- "creation": "2021-02-15 16:53:55.026611",
- "css": ".details {\n font-size: 15px;\n font-family: Tahoma, sans-serif;;\n line-height: 150%;\n}\n\n.certificate-footer {\n font-size: 15px;\n font-family: Tahoma, sans-serif;\n line-height: 140%;\n margin-top: 120px;\n}\n\n.company-address {\n color: #666666;\n font-size: 15px;\n font-family: Tahoma, sans-serif;;\n}",
- "custom_format": 1,
- "default_print_language": "en",
- "disabled": 0,
- "doc_type": "Tax Exemption 80G Certificate",
- "docstatus": 0,
- "doctype": "Print Format",
- "font": "Default",
- "html": "{% if letter_head and not no_letterhead -%}\n <div class=\"letter-head\">{{ letter_head }}</div>\n{%- endif %}\n\n<div>\n <h3 class=\"text-center\">{{ doc.company }} Members 80G Donor Certificate</h3>\n <h3 class=\"text-center\">Financial Cycle {{ doc.fiscal_year }}</h3>\n</div>\n<br><br>\n\n<div class=\"details\">\n <p> <b>{{ _(\"Certificate No. : \") }}</b> {{ doc.name }} </p>\n <p>\n \t<b>{{ _(\"Date\") }} :</b> {{ doc.get_formatted(\"date\") }}<br>\n </p>\n <br><br>\n \n <div>\n This is to confirm that the {{ doc.company }} received a total amount of <b>{{doc.get_formatted(\"total\")}}</b>\n from <b>{{ doc.member_name }}</b>\n {% if doc.pan_number -%}\n bearing PAN Number {{ doc.member_pan_number }}\n {%- endif %}\n as per the payment details given below:\n \n <br><br>\n <table class=\"table table-bordered table-condensed\">\n \t<thead>\n \t\t<tr>\n \t\t\t<th >{{ _(\"Date\") }}</th>\n \t\t\t<th class=\"text-right\">{{ _(\"Amount\") }}</th>\n \t\t\t<th class=\"text-right\">{{ _(\"Invoice ID\") }}</th>\n \t\t</tr>\n \t</thead>\n \t<tbody>\n \t\t{%- for payment in doc.payments -%}\n \t\t<tr>\n \t\t\t<td> {{ payment.date }} </td>\n \t\t\t<td class=\"text-right\">{{ payment.get_formatted(\"amount\") }}</td>\n \t\t\t<td class=\"text-right\">{{ payment.invoice_id }}</td>\n \t\t</tr>\n \t\t{%- endfor -%}\n \t</tbody>\n </table>\n \n <br>\n \n <p>\n We thank you for your contribution towards the corpus of the {{ doc.company }} and helping support our work.\n </p>\n\n </div>\n</div>\n\n<br><br>\n<p class=\"company-address text-left\"> {{doc.company_address_display }}</p>\n\n<div class=\"certificate-footer text-center\">\n <p><i>Computer generated receipt - Does not require signature</i></p><br>\n \n {% if doc.company_pan_number %}\n <p>\n <b>{{ doc.company }}'s PAN Account No :</b> {{ doc.company_pan_number }}\n <p><br>\n {% endif %}\n \n <p>\n <b>80G Number : </b> {{ doc.company_80g_number }}\n {% if doc.company_80g_wef %}\n ( w.e.f. {{ doc.get_formatted('company_80g_wef') }} )\n {% endif %}\n </p><br>\n</div>",
- "idx": 0,
- "line_breaks": 0,
- "modified": "2021-02-21 23:29:00.778973",
- "modified_by": "Administrator",
- "module": "Regional",
- "name": "80G Certificate for Membership",
- "owner": "Administrator",
- "print_format_builder": 0,
- "print_format_type": "Jinja",
- "raw_printing": 0,
- "show_section_headings": 0,
- "standard": "Yes"
-}
\ No newline at end of file
diff --git a/erpnext/regional/print_format/80g_certificate_for_membership/__init__.py b/erpnext/regional/print_format/80g_certificate_for_membership/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/erpnext/regional/print_format/80g_certificate_for_membership/__init__.py
+++ /dev/null
diff --git a/erpnext/regional/report/datev/datev.js b/erpnext/regional/report/datev/datev.js
index 4124e3d..03c729e 100644
--- a/erpnext/regional/report/datev/datev.js
+++ b/erpnext/regional/report/datev/datev.js
@@ -40,7 +40,11 @@
});
query_report.page.add_menu_item(__("Download DATEV File"), () => {
- const filters = JSON.stringify(query_report.get_values());
+ const filters = encodeURIComponent(
+ JSON.stringify(
+ query_report.get_values()
+ )
+ );
window.open(`/api/method/erpnext.regional.report.datev.datev.download_datev_csv?filters=${filters}`);
});
diff --git a/erpnext/regional/report/gstr_1/gstr_1.js b/erpnext/regional/report/gstr_1/gstr_1.js
index 4b98978..9999a6d 100644
--- a/erpnext/regional/report/gstr_1/gstr_1.js
+++ b/erpnext/regional/report/gstr_1/gstr_1.js
@@ -17,7 +17,7 @@
"fieldtype": "Link",
"options": "Address",
"get_query": function () {
- var company = frappe.query_report.get_filter_value('company');
+ let company = frappe.query_report.get_filter_value('company');
if (company) {
return {
"query": 'frappe.contacts.doctype.address.address.address_query',
@@ -27,6 +27,11 @@
}
},
{
+ "fieldname": "company_gstin",
+ "label": __("Company GSTIN"),
+ "fieldtype": "Select"
+ },
+ {
"fieldname": "from_date",
"label": __("From Date"),
"fieldtype": "Date",
@@ -60,10 +65,21 @@
}
],
onload: function (report) {
+ let filters = report.get_values();
+
+ frappe.call({
+ method: 'erpnext.regional.report.gstr_1.gstr_1.get_company_gstins',
+ args: {
+ company: filters.company
+ },
+ callback: function(r) {
+ frappe.query_report.page.fields_dict.company_gstin.df.options = r.message;
+ frappe.query_report.page.fields_dict.company_gstin.refresh();
+ }
+ });
+
report.page.add_inner_button(__("Download as JSON"), function () {
- var filters = report.get_values();
-
frappe.call({
method: 'erpnext.regional.report.gstr_1.gstr_1.get_json',
args: {
diff --git a/erpnext/regional/report/gstr_1/gstr_1.py b/erpnext/regional/report/gstr_1/gstr_1.py
index e50ff18..8fcb6bb 100644
--- a/erpnext/regional/report/gstr_1/gstr_1.py
+++ b/erpnext/regional/report/gstr_1/gstr_1.py
@@ -28,7 +28,7 @@
posting_date,
base_grand_total,
base_rounded_total,
- COALESCE(NULLIF(customer_gstin,''), NULLIF(billing_address_gstin, '')) as customer_gstin,
+ NULLIF(billing_address_gstin, '') as billing_address_gstin,
place_of_supply,
ecommerce_gstin,
reverse_charge,
@@ -253,13 +253,14 @@
for opts in (("company", " and company=%(company)s"),
("from_date", " and posting_date>=%(from_date)s"),
("to_date", " and posting_date<=%(to_date)s"),
- ("company_address", " and company_address=%(company_address)s")):
+ ("company_address", " and company_address=%(company_address)s"),
+ ("company_gstin", " and company_gstin=%(company_gstin)s")):
if self.filters.get(opts[0]):
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 AND is_debit_note !=1"
+ conditions += "AND IFNULL(gst_category, '') in ('Registered Regular', 'Registered Composition', 'Deemed Export', 'SEZ') AND is_return != 1 AND is_debit_note !=1"
if self.filters.get("type_of_business") in ("B2C Large", "B2C Small"):
b2c_limit = frappe.db.get_single_value('GST Settings', 'b2c_limit')
@@ -383,7 +384,7 @@
for invoice, items in self.invoice_items.items():
if invoice not in self.items_based_on_tax_rate and invoice not in unidentified_gst_accounts_invoice \
and self.invoices.get(invoice, {}).get('export_type') == "Without Payment of Tax" \
- and self.invoices.get(invoice, {}).get('gst_category') == "Overseas":
+ and self.invoices.get(invoice, {}).get('gst_category') in ("Overseas", "SEZ"):
self.items_based_on_tax_rate.setdefault(invoice, {}).setdefault(0, items.keys())
def get_columns(self):
@@ -409,7 +410,7 @@
if self.filters.get("type_of_business") == "B2B":
self.invoice_columns = [
{
- "fieldname": "customer_gstin",
+ "fieldname": "billing_address_gstin",
"label": "GSTIN/UIN of Recipient",
"fieldtype": "Data",
"width": 150
@@ -516,7 +517,7 @@
elif self.filters.get("type_of_business") == "CDNR-REG":
self.invoice_columns = [
{
- "fieldname": "customer_gstin",
+ "fieldname": "billing_address_gstin",
"label": "GSTIN/UIN of Recipient",
"fieldtype": "Data",
"width": 150
@@ -817,7 +818,7 @@
res = {}
if filters["type_of_business"] == "B2B":
for item in report_data[:-1]:
- res.setdefault(item["customer_gstin"], {}).setdefault(item["invoice_number"],[]).append(item)
+ res.setdefault(item["billing_address_gstin"], {}).setdefault(item["invoice_number"],[]).append(item)
out = get_b2b_json(res, gstin)
gst_json["b2b"] = out
@@ -841,7 +842,7 @@
gst_json["exp"] = out
elif filters["type_of_business"] == "CDNR-REG":
for item in report_data[:-1]:
- res.setdefault(item["customer_gstin"], {}).setdefault(item["invoice_number"],[]).append(item)
+ res.setdefault(item["billing_address_gstin"], {}).setdefault(item["invoice_number"],[]).append(item)
out = get_cdnr_reg_json(res, gstin)
gst_json["cdnr"] = out
@@ -875,7 +876,7 @@
}
def get_b2b_json(res, gstin):
- inv_type, out = {"Registered Regular": "R", "Deemed Export": "DE", "URD": "URD", "SEZ": "SEZ"}, []
+ out = []
for gst_in in res:
b2b_item, inv = {"ctin": gst_in, "inv": []}, []
if not gst_in: continue
@@ -889,7 +890,7 @@
inv_item = get_basic_invoice_detail(invoice[0])
inv_item["pos"] = "%02d" % int(invoice[0]["place_of_supply"].split('-')[0])
inv_item["rchrg"] = invoice[0]["reverse_charge"]
- inv_item["inv_typ"] = inv_type.get(invoice[0].get("gst_category", ""),"")
+ inv_item["inv_typ"] = get_invoice_type(invoice[0])
if inv_item["pos"]=="00": continue
inv_item["itms"] = []
@@ -1044,7 +1045,7 @@
"ntty": invoice[0]["document_type"],
"pos": "%02d" % int(invoice[0]["place_of_supply"].split('-')[0]),
"rchrg": invoice[0]["reverse_charge"],
- "inv_typ": get_invoice_type_for_cdnr(invoice[0])
+ "inv_typ": get_invoice_type(invoice[0])
}
inv_item["itms"] = []
@@ -1069,7 +1070,7 @@
"val": abs(flt(items[0]["invoice_value"])),
"ntty": items[0]["document_type"],
"pos": "%02d" % int(items[0]["place_of_supply"].split('-')[0]),
- "typ": get_invoice_type_for_cdnrur(items[0])
+ "typ": get_invoice_type(items[0])
}
inv_item["itms"] = []
@@ -1110,29 +1111,21 @@
return out
-def get_invoice_type_for_cdnr(row):
- if row.get('gst_category') == 'SEZ':
- if row.get('export_type') == 'WPAY':
- invoice_type = 'SEWP'
- else:
- invoice_type = 'SEWOP'
- elif row.get('gst_category') == 'Deemed Export':
- invoice_type = 'DE'
- elif row.get('gst_category') == 'Registered Regular':
- invoice_type = 'R'
+def get_invoice_type(row):
+ gst_category = row.get('gst_category')
- return invoice_type
+ if gst_category == 'SEZ':
+ return 'SEWP' if row.get('export_type') == 'WPAY' else 'SEWOP'
-def get_invoice_type_for_cdnrur(row):
- if row.get('gst_category') == 'Overseas':
- if row.get('export_type') == 'WPAY':
- invoice_type = 'EXPWP'
- else:
- invoice_type = 'EXPWOP'
- elif row.get('gst_category') == 'Unregistered':
- invoice_type = 'B2CL'
+ if gst_category == 'Overseas':
+ return 'EXPWP' if row.get('export_type') == 'WPAY' else 'EXPWOP'
- return invoice_type
+ return ({
+ 'Deemed Export': 'DE',
+ 'Registered Regular': 'R',
+ 'Registered Composition': 'R',
+ 'Unregistered': 'B2CL'
+ }).get(gst_category)
def get_basic_invoice_detail(row):
return {
@@ -1154,7 +1147,7 @@
# calculate tax amount added
tax = flt((row["taxable_value"]*rate)/100.0, 2)
frappe.errprint([tax, tax/2])
- if row.get("customer_gstin") and gstin[0:2] == row["customer_gstin"][0:2]:
+ if row.get("billing_address_gstin") and gstin[0:2] == row["billing_address_gstin"][0:2]:
itm_det.update({"camt": flt(tax/2.0, 2), "samt": flt(tax/2.0, 2)})
else:
itm_det.update({"iamt": tax})
@@ -1199,4 +1192,24 @@
if invoice_detail.place_of_supply.split("-")[0] != invoice_detail.company_gstin[:2]:
return True
else:
- return False
\ No newline at end of file
+ return False
+
+
+@frappe.whitelist()
+def get_company_gstins(company):
+ address = frappe.qb.DocType("Address")
+ links = frappe.qb.DocType("Dynamic Link")
+
+ addresses = frappe.qb.from_(address).inner_join(links).on(
+ address.name == links.parent
+ ).select(
+ address.gstin
+ ).where(
+ links.link_doctype == 'Company'
+ ).where(
+ links.link_name == company
+ ).run(as_dict=1)
+
+ address_list = [''] + [d.gstin for d in addresses]
+
+ return address_list
\ No newline at end of file
diff --git a/erpnext/regional/saudi_arabia/setup.py b/erpnext/regional/saudi_arabia/setup.py
index 15d524d..d2ef6f3 100644
--- a/erpnext/regional/saudi_arabia/setup.py
+++ b/erpnext/regional/saudi_arabia/setup.py
@@ -102,7 +102,7 @@
]
}
- create_custom_fields(custom_fields, update=True)
+ create_custom_fields(custom_fields, ignore_validate=True, update=True)
def update_regional_tax_settings(country, company):
create_ksa_vat_setting(company)
diff --git a/erpnext/selling/doctype/customer/customer.py b/erpnext/selling/doctype/customer/customer.py
index 7742f26..634c481 100644
--- a/erpnext/selling/doctype/customer/customer.py
+++ b/erpnext/selling/doctype/customer/customer.py
@@ -218,7 +218,9 @@
else:
company_record.append(limit.company)
- outstanding_amt = get_customer_outstanding(self.name, limit.company)
+ outstanding_amt = get_customer_outstanding(
+ self.name, limit.company, ignore_outstanding_sales_order=limit.bypass_credit_limit_check
+ )
if flt(limit.credit_limit) < outstanding_amt:
frappe.throw(_("""New credit limit is less than current outstanding amount for the customer. Credit limit has to be atleast {0}""").format(outstanding_amt))
diff --git a/erpnext/selling/doctype/customer/test_customer.py b/erpnext/selling/doctype/customer/test_customer.py
index 5301fd0..165ee81 100644
--- a/erpnext/selling/doctype/customer/test_customer.py
+++ b/erpnext/selling/doctype/customer/test_customer.py
@@ -4,12 +4,13 @@
import frappe
from frappe.test_runner import make_test_records
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import flt
from erpnext.accounts.party import get_due_date
from erpnext.exceptions import PartyDisabled, PartyFrozen
from erpnext.selling.doctype.customer.customer import get_credit_limit, get_customer_outstanding
-from erpnext.tests.utils import ERPNextTestCase, create_test_contact_and_address
+from erpnext.tests.utils import create_test_contact_and_address
test_ignore = ["Price List"]
test_dependencies = ['Payment Term', 'Payment Terms Template']
@@ -17,7 +18,7 @@
-class TestCustomer(ERPNextTestCase):
+class TestCustomer(FrappeTestCase):
def setUp(self):
if not frappe.get_value('Item', '_Test Item'):
make_test_records('Item')
diff --git a/erpnext/selling/doctype/party_specific_item/test_party_specific_item.py b/erpnext/selling/doctype/party_specific_item/test_party_specific_item.py
index b951044..9b672b4 100644
--- a/erpnext/selling/doctype/party_specific_item/test_party_specific_item.py
+++ b/erpnext/selling/doctype/party_specific_item/test_party_specific_item.py
@@ -1,12 +1,10 @@
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
-import unittest
-
import frappe
+from frappe.tests.utils import FrappeTestCase
from erpnext.controllers.queries import item_query
-from erpnext.tests.utils import ERPNextTestCase
test_dependencies = ['Item', 'Customer', 'Supplier']
@@ -18,7 +16,7 @@
psi.based_on_value = args.get('based_on_value')
psi.insert()
-class TestPartySpecificItem(ERPNextTestCase):
+class TestPartySpecificItem(FrappeTestCase):
def setUp(self):
self.customer = frappe.get_last_doc("Customer")
self.supplier = frappe.get_last_doc("Supplier")
diff --git a/erpnext/selling/doctype/quotation/quotation.js b/erpnext/selling/doctype/quotation/quotation.js
index 0e1a915..34e9a52 100644
--- a/erpnext/selling/doctype/quotation/quotation.js
+++ b/erpnext/selling/doctype/quotation/quotation.js
@@ -40,7 +40,6 @@
erpnext.selling.QuotationController = class QuotationController extends erpnext.selling.SellingController {
onload(doc, dt, dn) {
- var me = this;
super.onload(doc, dt, dn);
}
party_name() {
diff --git a/erpnext/selling/doctype/quotation/quotation_list.js b/erpnext/selling/doctype/quotation/quotation_list.js
index b631685..4c8f9c4 100644
--- a/erpnext/selling/doctype/quotation/quotation_list.js
+++ b/erpnext/selling/doctype/quotation/quotation_list.js
@@ -12,6 +12,14 @@
};
};
}
+
+ listview.page.add_action_item(__("Sales Order"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Quotation", "Sales Order");
+ });
+
+ listview.page.add_action_item(__("Sales Invoice"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Quotation", "Sales Invoice");
+ });
},
get_indicator: function(doc) {
diff --git a/erpnext/selling/doctype/quotation/test_quotation.py b/erpnext/selling/doctype/quotation/test_quotation.py
index 4357201..a749d9e 100644
--- a/erpnext/selling/doctype/quotation/test_quotation.py
+++ b/erpnext/selling/doctype/quotation/test_quotation.py
@@ -2,14 +2,13 @@
# License: GNU General Public License v3. See license.txt
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import add_days, add_months, flt, getdate, nowdate
-from erpnext.tests.utils import ERPNextTestCase
-
test_dependencies = ["Product Bundle"]
-class TestQuotation(ERPNextTestCase):
+class TestQuotation(FrappeTestCase):
def test_make_quotation_without_terms(self):
quotation = make_quotation(do_not_save=1)
self.assertFalse(quotation.get('payment_schedule'))
diff --git a/erpnext/selling/doctype/sales_order/sales_order.js b/erpnext/selling/doctype/sales_order/sales_order.js
index eb98e6c..f80eaf2 100644
--- a/erpnext/selling/doctype/sales_order/sales_order.js
+++ b/erpnext/selling/doctype/sales_order/sales_order.js
@@ -562,6 +562,7 @@
var me = this;
var dialog = new frappe.ui.Dialog({
title: __("Select Items"),
+ size: "large",
fields: [
{
"fieldtype": "Check",
@@ -663,7 +664,8 @@
} else {
let po_items = [];
me.frm.doc.items.forEach(d => {
- let pending_qty = (flt(d.stock_qty) - flt(d.ordered_qty)) / flt(d.conversion_factor);
+ let ordered_qty = me.get_ordered_qty(d, me.frm.doc);
+ let pending_qty = (flt(d.stock_qty) - ordered_qty) / flt(d.conversion_factor);
if (pending_qty > 0) {
po_items.push({
"doctype": "Sales Order Item",
@@ -689,6 +691,24 @@
dialog.show();
}
+ get_ordered_qty(item, so) {
+ let ordered_qty = item.ordered_qty;
+ if (so.packed_items) {
+ // calculate ordered qty based on packed items in case of product bundle
+ let packed_items = so.packed_items.filter(
+ (pi) => pi.parent_detail_docname == item.name
+ );
+ if (packed_items) {
+ ordered_qty = packed_items.reduce(
+ (sum, pi) => sum + flt(pi.ordered_qty),
+ 0
+ );
+ ordered_qty = ordered_qty / packed_items.length;
+ }
+ }
+ return ordered_qty;
+ }
+
hold_sales_order(){
var me = this;
var d = new frappe.ui.Dialog({
diff --git a/erpnext/selling/doctype/sales_order/sales_order.py b/erpnext/selling/doctype/sales_order/sales_order.py
index 0f5b1e3..abbb3c9 100755
--- a/erpnext/selling/doctype/sales_order/sales_order.py
+++ b/erpnext/selling/doctype/sales_order/sales_order.py
@@ -877,6 +877,9 @@
target.stock_qty = (flt(source.stock_qty) - flt(source.ordered_qty))
target.project = source_parent.project
+ def update_item_for_packed_item(source, target, source_parent):
+ target.qty = flt(source.qty) - flt(source.ordered_qty)
+
# po = frappe.get_list("Purchase Order", filters={"sales_order":source_name, "supplier":supplier, "docstatus": ("<", "2")})
doc = get_mapped_doc("Sales Order", source_name, {
"Sales Order": {
@@ -920,6 +923,7 @@
"Packed Item": {
"doctype": "Purchase Order Item",
"field_map": [
+ ["name", "sales_order_packed_item"],
["parent", "sales_order"],
["uom", "uom"],
["conversion_factor", "conversion_factor"],
@@ -934,6 +938,7 @@
"supplier",
"pricing_rules"
],
+ "postprocess": update_item_for_packed_item,
"condition": lambda doc: doc.parent_item in items_to_map
}
}, target_doc, set_missing_values)
diff --git a/erpnext/selling/doctype/sales_order/sales_order_list.js b/erpnext/selling/doctype/sales_order/sales_order_list.js
index 26d96d5..4691190 100644
--- a/erpnext/selling/doctype/sales_order/sales_order_list.js
+++ b/erpnext/selling/doctype/sales_order/sales_order_list.js
@@ -16,7 +16,7 @@
return [__("Overdue"), "red",
"per_delivered,<,100|delivery_date,<,Today|status,!=,Closed"];
} else if (flt(doc.grand_total) === 0) {
- // not delivered (zero-amount order)
+ // not delivered (zeroount order)
return [__("To Deliver"), "orange",
"per_delivered,<,100|grand_total,=,0|status,!=,Closed"];
} else if (flt(doc.per_billed, 6) < 100) {
@@ -48,5 +48,17 @@
listview.call_for_selected_items(method, {"status": "Submitted"});
});
+ listview.page.add_action_item(__("Sales Invoice"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Sales Order", "Sales Invoice");
+ });
+
+ listview.page.add_action_item(__("Delivery Note"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Sales Order", "Delivery Note");
+ });
+
+ listview.page.add_action_item(__("Advance Payment"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Sales Order", "Advance Payment");
+ });
+
}
};
diff --git a/erpnext/selling/doctype/sales_order/test_sales_order.py b/erpnext/selling/doctype/sales_order/test_sales_order.py
index acf048e..b528479 100644
--- a/erpnext/selling/doctype/sales_order/test_sales_order.py
+++ b/erpnext/selling/doctype/sales_order/test_sales_order.py
@@ -6,7 +6,8 @@
import frappe
import frappe.permissions
from frappe.core.doctype.user_permission.test_user_permission import create_user
-from frappe.utils import add_days, flt, getdate, nowdate
+from frappe.tests.utils import FrappeTestCase
+from frappe.utils import add_days, flt, getdate, nowdate, today
from erpnext.controllers.accounts_controller import update_child_qty_rate
from erpnext.maintenance.doctype.maintenance_schedule.test_maintenance_schedule import (
@@ -27,10 +28,9 @@
)
from erpnext.stock.doctype.item.test_item import make_item
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
-from erpnext.tests.utils import ERPNextTestCase
-class TestSalesOrder(ERPNextTestCase):
+class TestSalesOrder(FrappeTestCase):
@classmethod
def setUpClass(cls):
@@ -959,6 +959,42 @@
self.assertEqual(purchase_order.items[0].item_code, "_Test Bundle Item 1")
self.assertEqual(purchase_order.items[1].item_code, "_Test Bundle Item 2")
+ def test_purchase_order_updates_packed_item_ordered_qty(self):
+ """
+ Tests if the packed item's `ordered_qty` is updated with the quantity of the Purchase Order
+ """
+ from erpnext.selling.doctype.sales_order.sales_order import make_purchase_order
+
+ product_bundle = make_item("_Test Product Bundle", {"is_stock_item": 0})
+ make_item("_Test Bundle Item 1", {"is_stock_item": 1})
+ make_item("_Test Bundle Item 2", {"is_stock_item": 1})
+
+ make_product_bundle("_Test Product Bundle",
+ ["_Test Bundle Item 1", "_Test Bundle Item 2"])
+
+ so_items = [
+ {
+ "item_code": product_bundle.item_code,
+ "warehouse": "",
+ "qty": 2,
+ "rate": 400,
+ "delivered_by_supplier": 1,
+ "supplier": '_Test Supplier'
+ }
+ ]
+
+ so = make_sales_order(item_list=so_items)
+
+ purchase_order = make_purchase_order(so.name, selected_items=so_items)
+ purchase_order.supplier = "_Test Supplier"
+ purchase_order.set_warehouse = "_Test Warehouse - _TC"
+ purchase_order.save()
+ purchase_order.submit()
+
+ so.reload()
+ self.assertEqual(so.packed_items[0].ordered_qty, 2)
+ self.assertEqual(so.packed_items[1].ordered_qty, 2)
+
def test_reserved_qty_for_closing_so(self):
bin = frappe.get_all("Bin", filters={"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC"},
fields=["reserved_qty"])
@@ -1399,6 +1435,48 @@
so.load_from_db()
self.assertEqual(so.billing_status, 'Fully Billed')
+ def test_so_back_updated_from_wo_via_mr(self):
+ "SO -> MR (Manufacture) -> WO. Test if WO Qty is updated in SO."
+ from erpnext.manufacturing.doctype.work_order.work_order import (
+ make_stock_entry as make_se_from_wo,
+ )
+ from erpnext.stock.doctype.material_request.material_request import raise_work_orders
+
+ so = make_sales_order(item_list=[{"item_code": "_Test FG Item","qty": 2, "rate":100}])
+
+ mr = make_material_request(so.name)
+ mr.material_request_type = "Manufacture"
+ mr.schedule_date = today()
+ mr.submit()
+
+ # WO from MR
+ wo_name = raise_work_orders(mr.name)[0]
+ wo = frappe.get_doc("Work Order", wo_name)
+ wo.wip_warehouse = "Work In Progress - _TC"
+ wo.skip_transfer = True
+
+ self.assertEqual(wo.sales_order, so.name)
+ self.assertEqual(wo.sales_order_item, so.items[0].name)
+
+ wo.submit()
+ make_stock_entry(item_code="_Test Item", # Stock RM
+ target="Work In Progress - _TC",
+ qty=4, basic_rate=100
+ )
+ make_stock_entry(item_code="_Test Item Home Desktop 100", # Stock RM
+ target="Work In Progress - _TC",
+ qty=4, basic_rate=100
+ )
+
+ se = frappe.get_doc(make_se_from_wo(wo.name, "Manufacture", 2))
+ se.submit() # Finish WO
+
+ mr.reload()
+ wo.reload()
+ so.reload()
+ self.assertEqual(so.items[0].work_order_qty, wo.produced_qty)
+ self.assertEqual(mr.status, "Manufactured")
+
def automatically_fetch_payment_terms(enable=1):
accounts_settings = frappe.get_doc("Accounts Settings")
accounts_settings.automatically_fetch_payment_terms = enable
diff --git a/erpnext/selling/doctype/sales_order_item/sales_order_item.json b/erpnext/selling/doctype/sales_order_item/sales_order_item.json
index 95f6c4e..7e55499 100644
--- a/erpnext/selling/doctype/sales_order_item/sales_order_item.json
+++ b/erpnext/selling/doctype/sales_order_item/sales_order_item.json
@@ -793,6 +793,7 @@
},
{
"default": "0",
+ "fetch_from": "item_code.grant_commission",
"fieldname": "grant_commission",
"fieldtype": "Check",
"label": "Grant Commission",
@@ -802,7 +803,7 @@
"idx": 1,
"istable": 1,
"links": [],
- "modified": "2021-10-05 12:27:25.014789",
+ "modified": "2022-02-24 14:41:57.325799",
"modified_by": "Administrator",
"module": "Selling",
"name": "Sales Order Item",
@@ -811,5 +812,6 @@
"permissions": [],
"sort_field": "modified",
"sort_order": "DESC",
+ "states": [],
"track_changes": 1
}
\ No newline at end of file
diff --git a/erpnext/selling/page/point_of_sale/pos_payment.js b/erpnext/selling/page/point_of_sale/pos_payment.js
index b9b6559..1e9f6d7 100644
--- a/erpnext/selling/page/point_of_sale/pos_payment.js
+++ b/erpnext/selling/page/point_of_sale/pos_payment.js
@@ -169,6 +169,24 @@
}
});
+ frappe.ui.form.on('POS Invoice', 'coupon_code', (frm) => {
+ if (!frm.doc.ignore_pricing_rule && frm.doc.coupon_code) {
+ frappe.run_serially([
+ () => frm.doc.ignore_pricing_rule=1,
+ () => frm.trigger('ignore_pricing_rule'),
+ () => frm.doc.ignore_pricing_rule=0,
+ () => frm.trigger('apply_pricing_rule'),
+ () => frm.save(),
+ () => this.update_totals_section(frm.doc)
+ ]);
+ } else if (frm.doc.ignore_pricing_rule && frm.doc.coupon_code) {
+ frappe.show_alert({
+ message: __("Ignore Pricing Rule is enabled. Cannot apply coupon code."),
+ indicator: "orange"
+ });
+ }
+ });
+
this.setup_listener_for_payments();
this.$payment_modes.on('click', '.shortcut', function() {
diff --git a/erpnext/selling/report/item_wise_sales_history/item_wise_sales_history.py b/erpnext/selling/report/item_wise_sales_history/item_wise_sales_history.py
index 4a245e1..56e1eb5 100644
--- a/erpnext/selling/report/item_wise_sales_history/item_wise_sales_history.py
+++ b/erpnext/selling/report/item_wise_sales_history/item_wise_sales_history.py
@@ -156,24 +156,24 @@
customer_record = customer_details.get(record.customer)
item_record = item_details.get(record.item_code)
row = {
- "item_code": record.item_code,
- "item_name": item_record.item_name,
- "item_group": item_record.item_group,
- "description": record.description,
- "quantity": record.qty,
- "uom": record.uom,
- "rate": record.base_rate,
- "amount": record.base_amount,
- "sales_order": record.name,
- "transaction_date": record.transaction_date,
- "customer": record.customer,
- "customer_name": customer_record.customer_name,
- "customer_group": customer_record.customer_group,
- "territory": record.territory,
- "project": record.project,
- "delivered_quantity": flt(record.delivered_qty),
- "billed_amount": flt(record.billed_amt),
- "company": record.company
+ "item_code": record.get('item_code'),
+ "item_name": item_record.get('item_name'),
+ "item_group": item_record.get('item_group'),
+ "description": record.get('description'),
+ "quantity": record.get('qty'),
+ "uom": record.get('uom'),
+ "rate": record.get('base_rate'),
+ "amount": record.get('base_amount'),
+ "sales_order": record.get('name'),
+ "transaction_date": record.get('transaction_date'),
+ "customer": record.get('customer'),
+ "customer_name": customer_record.get('customer_name'),
+ "customer_group": customer_record.get('customer_group'),
+ "territory": record.get('territory'),
+ "project": record.get('project'),
+ "delivered_quantity": flt(record.get('delivered_qty')),
+ "billed_amount": flt(record.get('billed_amt')),
+ "company": record.get('company')
}
data.append(row)
diff --git a/erpnext/non_profit/doctype/chapter/__init__.py b/erpnext/selling/report/payment_terms_status_for_sales_order/__init__.py
similarity index 100%
rename from erpnext/non_profit/doctype/chapter/__init__.py
rename to erpnext/selling/report/payment_terms_status_for_sales_order/__init__.py
diff --git a/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.js b/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.js
new file mode 100644
index 0000000..0e36b3f
--- /dev/null
+++ b/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.js
@@ -0,0 +1,84 @@
+// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+/* eslint-disable */
+
+function get_filters() {
+ let filters = [
+ {
+ "fieldname":"company",
+ "label": __("Company"),
+ "fieldtype": "Link",
+ "options": "Company",
+ "default": frappe.defaults.get_user_default("Company"),
+ "reqd": 1
+ },
+ {
+ "fieldname":"period_start_date",
+ "label": __("Start Date"),
+ "fieldtype": "Date",
+ "reqd": 1,
+ "default": frappe.datetime.add_months(frappe.datetime.get_today(), -1)
+ },
+ {
+ "fieldname":"period_end_date",
+ "label": __("End Date"),
+ "fieldtype": "Date",
+ "reqd": 1,
+ "default": frappe.datetime.get_today()
+ },
+ {
+ "fieldname":"sales_order",
+ "label": __("Sales Order"),
+ "fieldtype": "MultiSelectList",
+ "width": 100,
+ "options": "Sales Order",
+ "get_data": function(txt) {
+ return frappe.db.get_link_options("Sales Order", txt, this.filters());
+ },
+ "filters": () => {
+ return {
+ docstatus: 1,
+ payment_terms_template: ['not in', ['']],
+ company: frappe.query_report.get_filter_value("company"),
+ transaction_date: ['between', [frappe.query_report.get_filter_value("period_start_date"), frappe.query_report.get_filter_value("period_end_date")]]
+ }
+ },
+ on_change: function(){
+ frappe.query_report.refresh();
+ }
+ }
+ ]
+
+ return filters;
+}
+
+frappe.query_reports["Payment Terms Status for Sales Order"] = {
+ "filters": get_filters(),
+ "formatter": function(value, row, column, data, default_formatter){
+ if(column.fieldname == 'invoices' && value) {
+ invoices = value.split(',');
+ const invoice_formatter = (prev_value, curr_value) => {
+ if(prev_value != "") {
+ return prev_value + ", " + default_formatter(curr_value, row, column, data);
+ }
+ else {
+ return default_formatter(curr_value, row, column, data);
+ }
+ }
+ return invoices.reduce(invoice_formatter, "")
+ }
+ else if (column.fieldname == 'paid_amount' && value){
+ formatted_value = default_formatter(value, row, column, data);
+ if(value > 0) {
+ formatted_value = "<span style='color:green;'>" + formatted_value + "</span>"
+ }
+ return formatted_value;
+ }
+ else if (column.fieldname == 'status' && value == 'Completed'){
+ return "<span style='color:green;'>" + default_formatter(value, row, column, data) + "</span>";
+ }
+
+ return default_formatter(value, row, column, data);
+ },
+
+};
diff --git a/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.json b/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.json
new file mode 100644
index 0000000..850fa4d
--- /dev/null
+++ b/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.json
@@ -0,0 +1,38 @@
+{
+ "add_total_row": 1,
+ "columns": [],
+ "creation": "2021-12-28 10:39:34.533964",
+ "disable_prepared_report": 0,
+ "disabled": 0,
+ "docstatus": 0,
+ "doctype": "Report",
+ "filters": [],
+ "idx": 0,
+ "is_standard": "Yes",
+ "modified": "2021-12-30 10:42:06.058457",
+ "modified_by": "Administrator",
+ "module": "Selling",
+ "name": "Payment Terms Status for Sales Order",
+ "owner": "Administrator",
+ "prepared_report": 0,
+ "ref_doctype": "Sales Order",
+ "report_name": "Payment Terms Status for Sales Order",
+ "report_type": "Script Report",
+ "roles": [
+ {
+ "role": "Sales User"
+ },
+ {
+ "role": "Sales Manager"
+ },
+ {
+ "role": "Maintenance User"
+ },
+ {
+ "role": "Accounts User"
+ },
+ {
+ "role": "Stock User"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.py b/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.py
new file mode 100644
index 0000000..e6a56ee
--- /dev/null
+++ b/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.py
@@ -0,0 +1,205 @@
+# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
+# License: MIT. See LICENSE
+
+import frappe
+from frappe import _, qb, query_builder
+from frappe.query_builder import functions
+
+
+def get_columns():
+ columns = [
+ {
+ "label": _("Sales Order"),
+ "fieldname": "name",
+ "fieldtype": "Link",
+ "options": "Sales Order",
+ },
+ {
+ "label": _("Posting Date"),
+ "fieldname": "submitted",
+ "fieldtype": "Date",
+ },
+ {
+ "label": _("Payment Term"),
+ "fieldname": "payment_term",
+ "fieldtype": "Data",
+ },
+ {
+ "label": _("Description"),
+ "fieldname": "description",
+ "fieldtype": "Data",
+ },
+ {
+ "label": _("Due Date"),
+ "fieldname": "due_date",
+ "fieldtype": "Date",
+ },
+ {
+ "label": _("Invoice Portion"),
+ "fieldname": "invoice_portion",
+ "fieldtype": "Percent",
+ },
+ {
+ "label": _("Payment Amount"),
+ "fieldname": "base_payment_amount",
+ "fieldtype": "Currency",
+ "options": "currency",
+ },
+ {
+ "label": _("Paid Amount"),
+ "fieldname": "paid_amount",
+ "fieldtype": "Currency",
+ "options": "currency",
+ },
+ {
+ "label": _("Invoices"),
+ "fieldname": "invoices",
+ "fieldtype": "Link",
+ "options": "Sales Invoice",
+ },
+ {
+ "label": _("Status"),
+ "fieldname": "status",
+ "fieldtype": "Data",
+ },
+ {
+ "label": _("Currency"),
+ "fieldname": "currency",
+ "fieldtype": "Currency",
+ "hidden": 1
+ }
+ ]
+ return columns
+
+
+def get_conditions(filters):
+ """
+ Convert filter options to conditions used in query
+ """
+ filters = frappe._dict(filters) if filters else frappe._dict({})
+ conditions = frappe._dict({})
+
+ conditions.company = filters.company or frappe.defaults.get_user_default("company")
+ conditions.end_date = filters.period_end_date or frappe.utils.today()
+ conditions.start_date = filters.period_start_date or frappe.utils.add_months(
+ conditions.end_date, -1
+ )
+ conditions.sales_order = filters.sales_order or []
+
+ return conditions
+
+
+def get_so_with_invoices(filters):
+ """
+ Get Sales Order with payment terms template with their associated Invoices
+ """
+ sorders = []
+
+ so = qb.DocType("Sales Order")
+ ps = qb.DocType("Payment Schedule")
+ datediff = query_builder.CustomFunction("DATEDIFF", ["cur_date", "due_date"])
+ ifelse = query_builder.CustomFunction("IF", ["condition", "then", "else"])
+
+ conditions = get_conditions(filters)
+ query_so = (
+ qb.from_(so)
+ .join(ps)
+ .on(ps.parent == so.name)
+ .select(
+ so.name,
+ so.transaction_date.as_("submitted"),
+ ifelse(datediff(ps.due_date, functions.CurDate()) < 0, "Overdue", "Unpaid").as_("status"),
+ ps.payment_term,
+ ps.description,
+ ps.due_date,
+ ps.invoice_portion,
+ ps.base_payment_amount,
+ ps.paid_amount,
+ )
+ .where(
+ (so.docstatus == 1)
+ & (so.payment_terms_template != "NULL")
+ & (so.company == conditions.company)
+ & (so.transaction_date[conditions.start_date : conditions.end_date])
+ )
+ .orderby(so.name, so.transaction_date, ps.due_date)
+ )
+
+ if conditions.sales_order != []:
+ query_so = query_so.where(so.name.isin(conditions.sales_order))
+
+ sorders = query_so.run(as_dict=True)
+
+ invoices = []
+ if sorders != []:
+ soi = qb.DocType("Sales Order Item")
+ si = qb.DocType("Sales Invoice")
+ sii = qb.DocType("Sales Invoice Item")
+ query_inv = (
+ qb.from_(sii)
+ .right_join(si)
+ .on(si.name == sii.parent)
+ .inner_join(soi)
+ .on(soi.name == sii.so_detail)
+ .select(sii.sales_order, sii.parent.as_("invoice"), si.base_grand_total.as_("invoice_amount"))
+ .where((sii.sales_order.isin([x.name for x in sorders])) & (si.docstatus == 1))
+ .groupby(sii.parent)
+ )
+ invoices = query_inv.run(as_dict=True)
+
+ return sorders, invoices
+
+
+def set_payment_terms_statuses(sales_orders, invoices, filters):
+ """
+ compute status for payment terms with associated sales invoice using FIFO
+ """
+
+ for so in sales_orders:
+ so.currency = frappe.get_cached_value('Company', filters.get('company'), 'default_currency')
+ so.invoices = ""
+ for inv in [x for x in invoices if x.sales_order == so.name and x.invoice_amount > 0]:
+ if so.base_payment_amount - so.paid_amount > 0:
+ amount = so.base_payment_amount - so.paid_amount
+ if inv.invoice_amount >= amount:
+ inv.invoice_amount -= amount
+ so.paid_amount += amount
+ so.invoices += "," + inv.invoice
+ so.status = "Completed"
+ break
+ else:
+ so.paid_amount += inv.invoice_amount
+ inv.invoice_amount = 0
+ so.invoices += "," + inv.invoice
+ so.status = "Partly Paid"
+
+ return sales_orders, invoices
+
+
+def prepare_chart(s_orders):
+ if len(set([x.name for x in s_orders])) == 1:
+ chart = {
+ "data": {
+ "labels": [term.payment_term for term in s_orders],
+ "datasets": [
+ {"name": "Payment Amount", "values": [x.base_payment_amount for x in s_orders],},
+ {"name": "Paid Amount", "values": [x.paid_amount for x in s_orders],},
+ ],
+ },
+ "type": "bar",
+ }
+ return chart
+
+
+def execute(filters=None):
+ columns = get_columns()
+ sales_orders, so_invoices = get_so_with_invoices(filters)
+ sales_orders, so_invoices = set_payment_terms_statuses(sales_orders, so_invoices, filters)
+
+ prepare_chart(sales_orders)
+
+ data = sales_orders
+ message = []
+ chart = prepare_chart(sales_orders)
+
+ return columns, data, message, chart
diff --git a/erpnext/selling/report/payment_terms_status_for_sales_order/test_payment_terms_status_for_sales_order.py b/erpnext/selling/report/payment_terms_status_for_sales_order/test_payment_terms_status_for_sales_order.py
new file mode 100644
index 0000000..f7f8a5d
--- /dev/null
+++ b/erpnext/selling/report/payment_terms_status_for_sales_order/test_payment_terms_status_for_sales_order.py
@@ -0,0 +1,198 @@
+import datetime
+
+import frappe
+from frappe.tests.utils import FrappeTestCase
+from frappe.utils import add_days
+
+from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice
+from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
+from erpnext.selling.report.payment_terms_status_for_sales_order.payment_terms_status_for_sales_order import (
+ execute,
+)
+from erpnext.stock.doctype.item.test_item import create_item
+
+test_dependencies = ["Sales Order", "Item", "Sales Invoice", "Payment Terms Template"]
+
+
+class TestPaymentTermsStatusForSalesOrder(FrappeTestCase):
+ def create_payment_terms_template(self):
+ # create template for 50-50 payments
+ template = None
+ if frappe.db.exists("Payment Terms Template", "_Test 50-50"):
+ template = frappe.get_doc("Payment Terms Template", "_Test 50-50")
+ else:
+ template = frappe.get_doc(
+ {
+ "doctype": "Payment Terms Template",
+ "template_name": "_Test 50-50",
+ "terms": [
+ {
+ "doctype": "Payment Terms Template Detail",
+ "due_date_based_on": "Day(s) after invoice date",
+ "payment_term_name": "_Test 50% on 15 Days",
+ "description": "_Test 50-50",
+ "invoice_portion": 50,
+ "credit_days": 15,
+ },
+ {
+ "doctype": "Payment Terms Template Detail",
+ "due_date_based_on": "Day(s) after invoice date",
+ "payment_term_name": "_Test 50% on 30 Days",
+ "description": "_Test 50-50",
+ "invoice_portion": 50,
+ "credit_days": 30,
+ },
+ ],
+ }
+ )
+ template.insert()
+ self.template = template
+
+ def test_payment_terms_status(self):
+ self.create_payment_terms_template()
+ item = create_item(item_code="_Test Excavator", is_stock_item=0)
+ so = make_sales_order(
+ transaction_date="2021-06-15",
+ delivery_date=add_days("2021-06-15", -30),
+ item=item.item_code,
+ qty=10,
+ rate=100000,
+ do_not_save=True,
+ )
+ so.po_no = ""
+ so.taxes_and_charges = ""
+ so.taxes = ""
+ so.payment_terms_template = self.template.name
+ so.save()
+ so.submit()
+
+ # make invoice with 60% of the total sales order value
+ sinv = make_sales_invoice(so.name)
+ sinv.taxes_and_charges = ""
+ sinv.taxes = ""
+ sinv.items[0].qty = 6
+ sinv.insert()
+ sinv.submit()
+ columns, data, message, chart = execute(
+ {
+ "company": "_Test Company",
+ "period_start_date": "2021-06-01",
+ "period_end_date": "2021-06-30",
+ "sales_order": [so.name],
+ }
+ )
+
+ expected_value = [
+ {
+ "name": so.name,
+ "submitted": datetime.date(2021, 6, 15),
+ "status": "Completed",
+ "payment_term": None,
+ "description": "_Test 50-50",
+ "due_date": datetime.date(2021, 6, 30),
+ "invoice_portion": 50.0,
+ "currency": "INR",
+ "base_payment_amount": 500000.0,
+ "paid_amount": 500000.0,
+ "invoices": ","+sinv.name,
+ },
+ {
+ "name": so.name,
+ "submitted": datetime.date(2021, 6, 15),
+ "status": "Partly Paid",
+ "payment_term": None,
+ "description": "_Test 50-50",
+ "due_date": datetime.date(2021, 7, 15),
+ "invoice_portion": 50.0,
+ "currency": "INR",
+ "base_payment_amount": 500000.0,
+ "paid_amount": 100000.0,
+ "invoices": ","+sinv.name,
+ },
+ ]
+ self.assertEqual(data, expected_value)
+
+ def create_exchange_rate(self, date):
+ # make an entry in Currency Exchange list. serves as a static exchange rate
+ if frappe.db.exists({'doctype': "Currency Exchange",'date': date,'from_currency': 'USD', 'to_currency':'INR'}):
+ return
+ else:
+ doc = frappe.get_doc({
+ 'doctype': "Currency Exchange",
+ 'date': date,
+ 'from_currency': 'USD',
+ 'to_currency': frappe.get_cached_value("Company", '_Test Company','default_currency'),
+ 'exchange_rate': 70,
+ 'for_buying': True,
+ 'for_selling': True
+ })
+ doc.insert()
+
+ def test_alternate_currency(self):
+ transaction_date = "2021-06-15"
+ self.create_payment_terms_template()
+ self.create_exchange_rate(transaction_date)
+ item = create_item(item_code="_Test Excavator", is_stock_item=0)
+ so = make_sales_order(
+ transaction_date=transaction_date,
+ currency="USD",
+ delivery_date=add_days(transaction_date, -30),
+ item=item.item_code,
+ qty=10,
+ rate=10000,
+ do_not_save=True,
+ )
+ so.po_no = ""
+ so.taxes_and_charges = ""
+ so.taxes = ""
+ so.payment_terms_template = self.template.name
+ so.save()
+ so.submit()
+
+ # make invoice with 60% of the total sales order value
+ sinv = make_sales_invoice(so.name)
+ sinv.currency = "USD"
+ sinv.taxes_and_charges = ""
+ sinv.taxes = ""
+ sinv.items[0].qty = 6
+ sinv.insert()
+ sinv.submit()
+ columns, data, message, chart = execute(
+ {
+ "company": "_Test Company",
+ "period_start_date": "2021-06-01",
+ "period_end_date": "2021-06-30",
+ "sales_order": [so.name],
+ }
+ )
+
+ # report defaults to company currency.
+ expected_value = [
+ {
+ "name": so.name,
+ "submitted": datetime.date(2021, 6, 15),
+ "status": "Completed",
+ "payment_term": None,
+ "description": "_Test 50-50",
+ "due_date": datetime.date(2021, 6, 30),
+ "invoice_portion": 50.0,
+ "currency": frappe.get_cached_value("Company", '_Test Company','default_currency'),
+ "base_payment_amount": 3500000.0,
+ "paid_amount": 3500000.0,
+ "invoices": ","+sinv.name,
+ },
+ {
+ "name": so.name,
+ "submitted": datetime.date(2021, 6, 15),
+ "status": "Partly Paid",
+ "payment_term": None,
+ "description": "_Test 50-50",
+ "due_date": datetime.date(2021, 7, 15),
+ "invoice_portion": 50.0,
+ "currency": frappe.get_cached_value("Company", '_Test Company','default_currency'),
+ "base_payment_amount": 3500000.0,
+ "paid_amount": 700000.0,
+ "invoices": ","+sinv.name,
+ },
+ ]
+ self.assertEqual(data, expected_value)
diff --git a/erpnext/selling/report/pending_so_items_for_purchase_request/test_pending_so_items_for_purchase_request.py b/erpnext/selling/report/pending_so_items_for_purchase_request/test_pending_so_items_for_purchase_request.py
index d62915f..16162ac 100644
--- a/erpnext/selling/report/pending_so_items_for_purchase_request/test_pending_so_items_for_purchase_request.py
+++ b/erpnext/selling/report/pending_so_items_for_purchase_request/test_pending_so_items_for_purchase_request.py
@@ -2,6 +2,7 @@
# For license information, please see license.txt
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import add_months, nowdate
from erpnext.selling.doctype.sales_order.sales_order import make_material_request
@@ -9,10 +10,9 @@
from erpnext.selling.report.pending_so_items_for_purchase_request.pending_so_items_for_purchase_request import (
execute,
)
-from erpnext.tests.utils import ERPNextTestCase
-class TestPendingSOItemsForPurchaseRequest(ERPNextTestCase):
+class TestPendingSOItemsForPurchaseRequest(FrappeTestCase):
def test_result_for_partial_material_request(self):
so = make_sales_order()
mr=make_material_request(so.name)
diff --git a/erpnext/selling/report/sales_analytics/test_analytics.py b/erpnext/selling/report/sales_analytics/test_analytics.py
index f56cce2..564f48f 100644
--- a/erpnext/selling/report/sales_analytics/test_analytics.py
+++ b/erpnext/selling/report/sales_analytics/test_analytics.py
@@ -3,13 +3,13 @@
import frappe
+from frappe.tests.utils import FrappeTestCase
from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
from erpnext.selling.report.sales_analytics.sales_analytics import execute
-from erpnext.tests.utils import ERPNextTestCase
-class TestAnalytics(ERPNextTestCase):
+class TestAnalytics(FrappeTestCase):
def test_sales_analytics(self):
frappe.db.sql("delete from `tabSales Order` where company='_Test Company 2'")
diff --git a/erpnext/selling/sales_common.js b/erpnext/selling/sales_common.js
index 16e3847..98131f9 100644
--- a/erpnext/selling/sales_common.js
+++ b/erpnext/selling/sales_common.js
@@ -227,11 +227,11 @@
},
callback:function(r){
if (in_list(['Delivery Note', 'Sales Invoice'], doc.doctype)) {
-
if (doc.doctype === 'Sales Invoice' && (!doc.update_stock)) return;
-
- me.set_batch_number(cdt, cdn);
- me.batch_no(doc, cdt, cdn);
+ if (has_batch_no) {
+ me.set_batch_number(cdt, cdn);
+ me.batch_no(doc, cdt, cdn);
+ }
}
}
});
diff --git a/erpnext/setup/doctype/company/company.py b/erpnext/setup/doctype/company/company.py
index 95b1e8b..36ad8fe 100644
--- a/erpnext/setup/doctype/company/company.py
+++ b/erpnext/setup/doctype/company/company.py
@@ -3,7 +3,6 @@
import json
-import os
import frappe
import frappe.defaults
@@ -422,14 +421,14 @@
return " - ".join(parts)
def install_country_fixtures(company, country):
- path = frappe.get_app_path('erpnext', 'regional', frappe.scrub(country))
- if os.path.exists(path.encode("utf-8")):
- try:
- module_name = "erpnext.regional.{0}.setup.setup".format(frappe.scrub(country))
- frappe.get_attr(module_name)(company, False)
- except Exception as e:
- frappe.log_error()
- frappe.throw(_("Failed to setup defaults for country {0}. Please contact support.").format(frappe.bold(country)))
+ try:
+ module_name = f"erpnext.regional.{frappe.scrub(country)}.setup.setup"
+ frappe.get_attr(module_name)(company, False)
+ except ImportError:
+ pass
+ except Exception:
+ frappe.log_error()
+ frappe.throw(_("Failed to setup defaults for country {0}. Please contact support.").format(frappe.bold(country)))
def update_company_current_month_sales(company):
diff --git a/erpnext/setup/doctype/item_group/item_group.js b/erpnext/setup/doctype/item_group/item_group.js
index 885d874..f570c2f 100644
--- a/erpnext/setup/doctype/item_group/item_group.js
+++ b/erpnext/setup/doctype/item_group/item_group.js
@@ -14,6 +14,16 @@
]
}
}
+ frm.fields_dict['item_group_defaults'].grid.get_field("default_discount_account").get_query = function(doc, cdt, cdn) {
+ const row = locals[cdt][cdn];
+ return {
+ filters: {
+ 'report_type': 'Profit and Loss',
+ 'company': row.company,
+ "is_group": 0
+ }
+ };
+ }
frm.fields_dict["item_group_defaults"].grid.get_field("expense_account").get_query = function(doc, cdt, cdn) {
const row = locals[cdt][cdn];
return {
diff --git a/erpnext/setup/doctype/item_group/item_group.json b/erpnext/setup/doctype/item_group/item_group.json
index 3e0680f..50f923d 100644
--- a/erpnext/setup/doctype/item_group/item_group.json
+++ b/erpnext/setup/doctype/item_group/item_group.json
@@ -20,12 +20,14 @@
"sec_break_taxes",
"taxes",
"sb9",
- "show_in_website",
"route",
- "weightage",
- "slideshow",
"website_title",
"description",
+ "show_in_website",
+ "include_descendants",
+ "column_break_16",
+ "weightage",
+ "slideshow",
"website_specifications",
"website_filters_section",
"filter_fields",
@@ -111,7 +113,7 @@
},
{
"default": "0",
- "description": "Check this if you want to show in website",
+ "description": "Make Item Group visible in website",
"fieldname": "show_in_website",
"fieldtype": "Check",
"label": "Show in Website"
@@ -124,6 +126,7 @@
"unique": 1
},
{
+ "depends_on": "show_in_website",
"fieldname": "weightage",
"fieldtype": "Int",
"label": "Weightage"
@@ -186,6 +189,8 @@
"report_hide": 1
},
{
+ "collapsible": 1,
+ "depends_on": "show_in_website",
"fieldname": "website_filters_section",
"fieldtype": "Section Break",
"label": "Website Filters"
@@ -203,9 +208,22 @@
"options": "Website Attribute"
},
{
+ "depends_on": "show_in_website",
"fieldname": "website_title",
"fieldtype": "Data",
"label": "Title"
+ },
+ {
+ "fieldname": "column_break_16",
+ "fieldtype": "Column Break"
+ },
+ {
+ "default": "0",
+ "depends_on": "show_in_website",
+ "description": "Include Website Items belonging to child Item Groups",
+ "fieldname": "include_descendants",
+ "fieldtype": "Check",
+ "label": "Include Descendants"
}
],
"icon": "fa fa-sitemap",
@@ -214,11 +232,12 @@
"is_tree": 1,
"links": [],
"max_attachments": 3,
- "modified": "2021-02-18 13:40:30.049650",
+ "modified": "2022-03-09 12:27:11.055782",
"modified_by": "Administrator",
"module": "Setup",
"name": "Item Group",
"name_case": "Title Case",
+ "naming_rule": "By fieldname",
"nsm_parent_field": "parent_item_group",
"owner": "Administrator",
"permissions": [
@@ -285,5 +304,6 @@
"search_fields": "parent_item_group",
"show_name_in_global_search": 1,
"sort_field": "modified",
- "sort_order": "DESC"
+ "sort_order": "DESC",
+ "states": []
}
\ No newline at end of file
diff --git a/erpnext/setup/doctype/item_group/item_group.py b/erpnext/setup/doctype/item_group/item_group.py
index 4f92240..5c7194b 100644
--- a/erpnext/setup/doctype/item_group/item_group.py
+++ b/erpnext/setup/doctype/item_group/item_group.py
@@ -111,7 +111,7 @@
from erpnext.stock.doctype.item.item import validate_item_default_company_links
validate_item_default_company_links(self.item_group_defaults)
-def get_child_groups_for_website(item_group_name, immediate=False):
+def get_child_groups_for_website(item_group_name, immediate=False, include_self=False):
"""Returns child item groups *excluding* passed group."""
item_group = frappe.get_cached_value("Item Group", item_group_name, ["lft", "rgt"], as_dict=1)
filters = {
@@ -123,6 +123,12 @@
if immediate:
filters["parent_item_group"] = item_group_name
+ if include_self:
+ filters.update({
+ "lft": [">=", item_group.lft],
+ "rgt": ["<=", item_group.rgt]
+ })
+
return frappe.get_all(
"Item Group",
filters=filters,
diff --git a/erpnext/setup/setup_wizard/operations/install_fixtures.py b/erpnext/setup/setup_wizard/operations/install_fixtures.py
index cd2738a..cefa0f3 100644
--- a/erpnext/setup/setup_wizard/operations/install_fixtures.py
+++ b/erpnext/setup/setup_wizard/operations/install_fixtures.py
@@ -195,10 +195,8 @@
{'doctype': "Party Type", "party_type": "Customer", "account_type": "Receivable"},
{'doctype': "Party Type", "party_type": "Supplier", "account_type": "Payable"},
{'doctype': "Party Type", "party_type": "Employee", "account_type": "Payable"},
- {'doctype': "Party Type", "party_type": "Member", "account_type": "Receivable"},
{'doctype': "Party Type", "party_type": "Shareholder", "account_type": "Payable"},
{'doctype': "Party Type", "party_type": "Student", "account_type": "Receivable"},
- {'doctype': "Party Type", "party_type": "Donor", "account_type": "Receivable"},
{'doctype': "Opportunity Type", "name": _("Sales")},
{'doctype': "Opportunity Type", "name": _("Support")},
diff --git a/erpnext/setup/utils.py b/erpnext/setup/utils.py
index 4441bb9..a4f2207 100644
--- a/erpnext/setup/utils.py
+++ b/erpnext/setup/utils.py
@@ -155,7 +155,7 @@
doc = frappe.new_doc(r.get("doctype"))
doc.update(r)
try:
- doc.insert(ignore_permissions=True)
+ doc.insert(ignore_permissions=True, ignore_if_duplicate=True)
except frappe.DuplicateEntryError as e:
# pass DuplicateEntryError and continue
if e.args and e.args[0]==doc.doctype and e.args[1]==doc.name:
diff --git a/erpnext/stock/dashboard/item_dashboard.js b/erpnext/stock/dashboard/item_dashboard.js
index 37e9e89..c9d5f61 100644
--- a/erpnext/stock/dashboard/item_dashboard.js
+++ b/erpnext/stock/dashboard/item_dashboard.js
@@ -213,7 +213,14 @@
label: __('Target Warehouse'),
fieldtype: 'Link',
options: 'Warehouse',
- reqd: 1
+ reqd: 1,
+ get_query() {
+ return {
+ filters: {
+ is_group: 0
+ }
+ }
+ }
},
{
fieldname: 'qty',
@@ -252,52 +259,21 @@
dialog.get_field('target').refresh();
}
- dialog.set_primary_action(__('Submit'), function () {
- var values = dialog.get_values();
- if (!values) {
- return;
- }
- if (source && values.qty > actual_qty) {
- frappe.msgprint(__('Quantity must be less than or equal to {0}', [actual_qty]));
- return;
- }
- if (values.source === values.target) {
- frappe.msgprint(__('Source and target warehouse must be different'));
- }
-
- frappe.call({
- method: 'erpnext.stock.doctype.stock_entry.stock_entry_utils.make_stock_entry',
- args: values,
- btn: dialog.get_primary_btn(),
- freeze: true,
- freeze_message: __('Creating Stock Entry'),
- callback: function (r) {
- frappe.show_alert(__('Stock Entry {0} created',
- ['<a href="/app/stock-entry/' + r.message.name + '">' + r.message.name + '</a>']));
- dialog.hide();
- callback(r);
- },
+ dialog.set_primary_action(__('Create Stock Entry'), function () {
+ frappe.model.with_doctype('Stock Entry', function () {
+ let doc = frappe.model.get_new_doc('Stock Entry');
+ doc.from_warehouse = dialog.get_value('source');
+ doc.to_warehouse = dialog.get_value('target');
+ doc.stock_entry_type = doc.from_warehouse ? "Material Transfer" : "Material Receipt";
+ let row = frappe.model.add_child(doc, 'items');
+ row.item_code = dialog.get_value('item_code');
+ row.s_warehouse = dialog.get_value('source');
+ row.t_warehouse = dialog.get_value('target');
+ row.qty = dialog.get_value('qty');
+ row.conversion_factor = 1;
+ row.transfer_qty = dialog.get_value('qty');
+ row.basic_rate = dialog.get_value('rate');
+ frappe.set_route('Form', doc.doctype, doc.name);
});
});
-
- $('<p style="margin-left: 10px;"><a class="link-open text-muted small">' +
- __("Add more items or open full form") + '</a></p>')
- .appendTo(dialog.body)
- .find('.link-open')
- .on('click', function () {
- frappe.model.with_doctype('Stock Entry', function () {
- var doc = frappe.model.get_new_doc('Stock Entry');
- doc.from_warehouse = dialog.get_value('source');
- doc.to_warehouse = dialog.get_value('target');
- var row = frappe.model.add_child(doc, 'items');
- row.item_code = dialog.get_value('item_code');
- row.f_warehouse = dialog.get_value('target');
- row.t_warehouse = dialog.get_value('target');
- row.qty = dialog.get_value('qty');
- row.conversion_factor = 1;
- row.transfer_qty = dialog.get_value('qty');
- row.basic_rate = dialog.get_value('rate');
- frappe.set_route('Form', doc.doctype, doc.name);
- });
- });
};
diff --git a/erpnext/stock/doctype/batch/batch.json b/erpnext/stock/doctype/batch/batch.json
index fc4cf1d..967c572 100644
--- a/erpnext/stock/doctype/batch/batch.json
+++ b/erpnext/stock/doctype/batch/batch.json
@@ -9,6 +9,8 @@
"field_order": [
"sb_disabled",
"disabled",
+ "column_break_24",
+ "use_batchwise_valuation",
"sb_batch",
"batch_id",
"item",
@@ -186,6 +188,18 @@
"fieldtype": "Float",
"label": "Produced Qty",
"read_only": 1
+ },
+ {
+ "fieldname": "column_break_24",
+ "fieldtype": "Column Break"
+ },
+ {
+ "default": "0",
+ "fieldname": "use_batchwise_valuation",
+ "fieldtype": "Check",
+ "label": "Use Batch-wise Valuation",
+ "read_only": 1,
+ "set_only_once": 1
}
],
"icon": "fa fa-archive",
@@ -193,10 +207,11 @@
"image_field": "image",
"links": [],
"max_attachments": 5,
- "modified": "2021-07-08 16:22:01.343105",
+ "modified": "2022-02-21 08:08:23.999236",
"modified_by": "Administrator",
"module": "Stock",
"name": "Batch",
+ "naming_rule": "By fieldname",
"owner": "Administrator",
"permissions": [
{
@@ -217,6 +232,7 @@
"quick_entry": 1,
"sort_field": "modified",
"sort_order": "DESC",
+ "states": [],
"title_field": "batch_id",
"track_changes": 1
}
\ No newline at end of file
diff --git a/erpnext/stock/doctype/batch/batch.py b/erpnext/stock/doctype/batch/batch.py
index 96751d6..c9b4c14 100644
--- a/erpnext/stock/doctype/batch/batch.py
+++ b/erpnext/stock/doctype/batch/batch.py
@@ -110,11 +110,18 @@
def validate(self):
self.item_has_batch_enabled()
+ self.set_batchwise_valuation()
def item_has_batch_enabled(self):
if frappe.db.get_value("Item", self.item, "has_batch_no") == 0:
frappe.throw(_("The selected item cannot have Batch"))
+ def set_batchwise_valuation(self):
+ from erpnext.stock.stock_ledger import get_valuation_method
+
+ if self.is_new() and get_valuation_method(self.item) != "Moving Average":
+ self.use_batchwise_valuation = 1
+
def before_save(self):
has_expiry_date, shelf_life_in_days = frappe.db.get_value('Item', self.item, ['has_expiry_date', 'shelf_life_in_days'])
if not self.expiry_date and has_expiry_date and shelf_life_in_days:
diff --git a/erpnext/stock/doctype/batch/test_batch.py b/erpnext/stock/doctype/batch/test_batch.py
index 0a663c2..5763753 100644
--- a/erpnext/stock/doctype/batch/test_batch.py
+++ b/erpnext/stock/doctype/batch/test_batch.py
@@ -1,17 +1,25 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
+import json
+
import frappe
from frappe.exceptions import ValidationError
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import cint, flt
+from frappe.utils.data import add_to_date, getdate
from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import make_purchase_invoice
from erpnext.stock.doctype.batch.batch import UnableToSelectBatchError, get_batch_no, get_batch_qty
+from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
+from erpnext.stock.doctype.stock_reconciliation.test_stock_reconciliation import (
+ create_stock_reconciliation,
+)
from erpnext.stock.get_item_details import get_item_details
-from erpnext.tests.utils import ERPNextTestCase
+from erpnext.stock.stock_ledger import get_valuation_rate
-class TestBatch(ERPNextTestCase):
+class TestBatch(FrappeTestCase):
def test_item_has_batch_enabled(self):
self.assertRaises(ValidationError, frappe.get_doc({
"doctype": "Batch",
@@ -300,6 +308,105 @@
details = get_item_details(args)
self.assertEqual(details.get('price_list_rate'), 400)
+
+ def test_basic_batch_wise_valuation(self, batch_qty = 100):
+ item_code = "_TestBatchWiseVal"
+ warehouse = "_Test Warehouse - _TC"
+ self.make_batch_item(item_code)
+
+ rates = [42, 420]
+
+ batches = {}
+ for rate in rates:
+ se = make_stock_entry(item_code=item_code, qty=10, rate=rate, target=warehouse)
+ batches[se.items[0].batch_no] = rate
+
+ LOW, HIGH = list(batches.keys())
+
+ # consume things out of order
+ consumption_plan = [
+ (HIGH, 1),
+ (LOW, 2),
+ (HIGH, 2),
+ (HIGH, 4),
+ (LOW, 6),
+ ]
+
+ stock_value = sum(rates) * 10
+ qty_after_transaction = 20
+ for batch, qty in consumption_plan:
+ # consume out of order
+ se = make_stock_entry(item_code=item_code, source=warehouse, qty=qty, batch_no=batch)
+
+ sle = frappe.get_last_doc("Stock Ledger Entry", {"is_cancelled": 0, "voucher_no": se.name})
+
+ stock_value_difference = sle.actual_qty * batches[sle.batch_no]
+ self.assertAlmostEqual(sle.stock_value_difference, stock_value_difference)
+
+ stock_value += stock_value_difference
+ self.assertAlmostEqual(sle.stock_value, stock_value)
+
+ qty_after_transaction += sle.actual_qty
+ self.assertAlmostEqual(sle.qty_after_transaction, qty_after_transaction)
+ self.assertAlmostEqual(sle.valuation_rate, stock_value / qty_after_transaction)
+
+ self.assertEqual(json.loads(sle.stock_queue), []) # queues don't apply on batched items
+
+ def test_moving_batch_valuation_rates(self):
+ item_code = "_TestBatchWiseVal"
+ warehouse = "_Test Warehouse - _TC"
+ self.make_batch_item(item_code)
+
+ def assertValuation(expected):
+ actual = get_valuation_rate(item_code, warehouse, "voucher_type", "voucher_no", batch_no=batch_no)
+ self.assertAlmostEqual(actual, expected)
+
+ se = make_stock_entry(item_code=item_code, qty=100, rate=10, target=warehouse)
+ batch_no = se.items[0].batch_no
+ assertValuation(10)
+
+ # consumption should never affect current valuation rate
+ make_stock_entry(item_code=item_code, qty=20, source=warehouse)
+ assertValuation(10)
+
+ make_stock_entry(item_code=item_code, qty=30, source=warehouse)
+ assertValuation(10)
+
+ # 50 * 10 = 500 current value, add more item with higher valuation
+ make_stock_entry(item_code=item_code, qty=50, rate=20, target=warehouse, batch_no=batch_no)
+ assertValuation(15)
+
+ # consuming again shouldn't do anything
+ make_stock_entry(item_code=item_code, qty=20, source=warehouse)
+ assertValuation(15)
+
+ # reset rate with stock reconiliation
+ create_stock_reconciliation(item_code=item_code, warehouse=warehouse, qty=10, rate=25, batch_no=batch_no)
+ assertValuation(25)
+
+ make_stock_entry(item_code=item_code, qty=20, rate=20, target=warehouse, batch_no=batch_no)
+ assertValuation((20 * 20 + 10 * 25) / (10 + 20))
+
+
+ def test_update_batch_properties(self):
+ item_code = "_TestBatchWiseVal"
+ self.make_batch_item(item_code)
+
+ se = make_stock_entry(item_code=item_code, qty=100, rate=10, target="_Test Warehouse - _TC")
+ batch_no = se.items[0].batch_no
+ batch = frappe.get_doc("Batch", batch_no)
+
+ expiry_date = add_to_date(batch.manufacturing_date, days=30)
+
+ batch.expiry_date = expiry_date
+ batch.save()
+
+ batch.reload()
+
+ self.assertEqual(getdate(batch.expiry_date), getdate(expiry_date))
+
+
+
def create_batch(item_code, rate, create_item_price_for_batch):
pi = make_purchase_invoice(company="_Test Company",
warehouse= "Stores - _TC", cost_center = "Main - _TC", update_stock=1,
@@ -326,14 +433,13 @@
def make_new_batch(**args):
args = frappe._dict(args)
- try:
+ if frappe.db.exists("Batch", args.batch_id):
+ batch = frappe.get_doc("Batch", args.batch_id)
+ else:
batch = frappe.get_doc({
"doctype": "Batch",
"batch_id": args.batch_id,
"item": args.item_code,
}).insert()
- except frappe.DuplicateEntryError:
- batch = frappe.get_doc("Batch", args.batch_id)
-
return batch
diff --git a/erpnext/stock/doctype/bin/bin.py b/erpnext/stock/doctype/bin/bin.py
index c34e9d0..3bc15a8 100644
--- a/erpnext/stock/doctype/bin/bin.py
+++ b/erpnext/stock/doctype/bin/bin.py
@@ -20,43 +20,12 @@
+ flt(self.indented_qty) + flt(self.planned_qty) - flt(self.reserved_qty)
- flt(self.reserved_qty_for_production) - flt(self.reserved_qty_for_sub_contract))
- def get_first_sle(self):
- sle = frappe.qb.DocType("Stock Ledger Entry")
- first_sle = (
- frappe.qb.from_(sle)
- .select("*")
- .where((sle.item_code == self.item_code) & (sle.warehouse == self.warehouse))
- .orderby(sle.posting_date, sle.posting_time, sle.creation)
- .limit(1)
- ).run(as_dict=True)
-
- return first_sle and first_sle[0] or None
-
def update_reserved_qty_for_production(self):
'''Update qty reserved for production from Production Item tables
in open work orders'''
+ from erpnext.manufacturing.doctype.work_order.work_order import get_reserved_qty_for_production
- wo = frappe.qb.DocType("Work Order")
- wo_item = frappe.qb.DocType("Work Order Item")
-
- self.reserved_qty_for_production = (
- frappe.qb
- .from_(wo)
- .from_(wo_item)
- .select(Sum(Case()
- .when(wo.skip_transfer == 0, wo_item.required_qty - wo_item.transferred_qty)
- .else_(wo_item.required_qty - wo_item.consumed_qty))
- )
- .where(
- (wo_item.item_code == self.item_code)
- & (wo_item.parent == wo.name)
- & (wo.docstatus == 1)
- & (wo_item.source_warehouse == self.warehouse)
- & (wo.status.notin(["Stopped", "Completed"]))
- & ((wo_item.required_qty > wo_item.transferred_qty)
- | (wo_item.required_qty > wo_item.consumed_qty))
- )
- ).run()[0][0] or 0.0
+ self.reserved_qty_for_production = get_reserved_qty_for_production(self.item_code, self.warehouse)
self.set_projected_qty()
@@ -126,13 +95,6 @@
frappe.db.add_unique("Bin", ["item_code", "warehouse"], constraint_name="unique_item_warehouse")
-def update_stock(bin_name, args, allow_negative_stock=False, via_landed_cost_voucher=False):
- """WARNING: This function is deprecated. Inline this function instead of using it."""
- from erpnext.stock.stock_ledger import repost_current_voucher
-
- repost_current_voucher(args, allow_negative_stock, via_landed_cost_voucher)
- update_qty(bin_name, args)
-
def get_bin_details(bin_name):
return frappe.db.get_value('Bin', bin_name, ['actual_qty', 'ordered_qty',
'reserved_qty', 'indented_qty', 'planned_qty', 'reserved_qty_for_production',
diff --git a/erpnext/stock/doctype/bin/test_bin.py b/erpnext/stock/doctype/bin/test_bin.py
index 250126c..ec0d8a8 100644
--- a/erpnext/stock/doctype/bin/test_bin.py
+++ b/erpnext/stock/doctype/bin/test_bin.py
@@ -2,13 +2,13 @@
# See license.txt
import frappe
+from frappe.tests.utils import FrappeTestCase
from erpnext.stock.doctype.item.test_item import make_item
from erpnext.stock.utils import _create_bin
-from erpnext.tests.utils import ERPNextTestCase
-class TestBin(ERPNextTestCase):
+class TestBin(FrappeTestCase):
def test_concurrent_inserts(self):
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.py b/erpnext/stock/doctype/delivery_note/delivery_note.py
index d1e2244..2a4d639 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.py
@@ -339,17 +339,35 @@
frappe.throw(_("Could not create Credit Note automatically, please uncheck 'Issue Credit Note' and submit again"))
def update_billed_amount_based_on_so(so_detail, update_modified=True):
+ from frappe.query_builder.functions import Sum
+
# Billed against Sales Order directly
- billed_against_so = frappe.db.sql("""select sum(amount) from `tabSales Invoice Item`
- where so_detail=%s and (dn_detail is null or dn_detail = '') and docstatus=1""", so_detail)
+ si = frappe.qb.DocType("Sales Invoice").as_("si")
+ si_item = frappe.qb.DocType("Sales Invoice Item").as_("si_item")
+ sum_amount = Sum(si_item.amount).as_("amount")
+
+ billed_against_so = frappe.qb.from_(si).from_(si_item).select(sum_amount).where(
+ (si_item.parent == si.name) &
+ (si_item.so_detail == so_detail) &
+ ((si_item.dn_detail.isnull()) | (si_item.dn_detail == '')) &
+ (si_item.docstatus == 1) &
+ (si.update_stock == 0)
+ ).run()
billed_against_so = billed_against_so and billed_against_so[0][0] or 0
# Get all Delivery Note Item rows against the Sales Order Item row
- dn_details = frappe.db.sql("""select dn_item.name, dn_item.amount, dn_item.si_detail, dn_item.parent
- from `tabDelivery Note Item` dn_item, `tabDelivery Note` dn
- where dn.name=dn_item.parent and dn_item.so_detail=%s
- and dn.docstatus=1 and dn.is_return = 0
- order by dn.posting_date asc, dn.posting_time asc, dn.name asc""", so_detail, as_dict=1)
+
+ dn = frappe.qb.DocType("Delivery Note").as_("dn")
+ dn_item = frappe.qb.DocType("Delivery Note Item").as_("dn_item")
+
+ dn_details = frappe.qb.from_(dn).from_(dn_item).select(dn_item.name, dn_item.amount, dn_item.si_detail, dn_item.parent, dn_item.stock_qty, dn_item.returned_qty).where(
+ (dn.name == dn_item.parent) &
+ (dn_item.so_detail == so_detail) &
+ (dn.docstatus == 1) &
+ (dn.is_return == 0)
+ ).orderby(
+ dn.posting_date, dn.posting_time, dn.name
+ ).run(as_dict=True)
updated_dn = []
for dnd in dn_details:
@@ -367,7 +385,11 @@
# Distribute billed amount directly against SO between DNs based on FIFO
if billed_against_so and billed_amt_agianst_dn < dnd.amount:
- pending_to_bill = flt(dnd.amount) - billed_amt_agianst_dn
+ if dnd.returned_qty:
+ pending_to_bill = flt(dnd.amount) * (dnd.stock_qty - dnd.returned_qty) / dnd.stock_qty
+ else:
+ pending_to_bill = flt(dnd.amount)
+ pending_to_bill -= billed_amt_agianst_dn
if pending_to_bill <= billed_against_so:
billed_amt_agianst_dn += pending_to_bill
billed_against_so -= pending_to_bill
@@ -586,7 +608,18 @@
"validation": {
"docstatus": ["=", 0]
}
+ },
+
+ "Delivery Note Item": {
+ "doctype": "Packing Slip Item",
+ "field_map": {
+ "item_code": "item_code",
+ "item_name": "item_name",
+ "description": "description",
+ "qty": "qty",
+ }
}
+
}, target_doc)
return doclist
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note_list.js b/erpnext/stock/doctype/delivery_note/delivery_note_list.js
index 0402898..9e6f3bc 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note_list.js
+++ b/erpnext/stock/doctype/delivery_note/delivery_note_list.js
@@ -14,7 +14,7 @@
return [__("Completed"), "green", "per_billed,=,100"];
}
},
- onload: function (doclist) {
+ onload: function (listview) {
const action = () => {
const selected_docs = doclist.get_checked_items();
const docnames = doclist.get_checked_items(true);
@@ -54,6 +54,16 @@
};
};
- doclist.page.add_actions_menu_item(__('Create Delivery Trip'), action, false);
+ // doclist.page.add_actions_menu_item(__('Create Delivery Trip'), action, false);
+
+ listview.page.add_action_item(__('Create Delivery Trip'), action);
+
+ listview.page.add_action_item(__("Sales Invoice"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Delivery Note", "Sales Invoice");
+ });
+
+ listview.page.add_action_item(__("Packaging Slip From Delivery Note"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Delivery Note", "Packing Slip");
+ });
}
};
diff --git a/erpnext/stock/doctype/delivery_note/test_delivery_note.py b/erpnext/stock/doctype/delivery_note/test_delivery_note.py
index bd18e78..16c8921 100644
--- a/erpnext/stock/doctype/delivery_note/test_delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/test_delivery_note.py
@@ -6,6 +6,7 @@
import json
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import cstr, flt, nowdate, nowtime
from erpnext.accounts.doctype.account.test_account import get_inventory_account
@@ -35,10 +36,9 @@
)
from erpnext.stock.doctype.warehouse.test_warehouse import get_warehouse
from erpnext.stock.stock_ledger import get_previous_sle
-from erpnext.tests.utils import ERPNextTestCase
-class TestDeliveryNote(ERPNextTestCase):
+class TestDeliveryNote(FrappeTestCase):
def test_over_billing_against_dn(self):
frappe.db.set_value("Stock Settings", None, "allow_negative_stock", 1)
diff --git a/erpnext/stock/doctype/delivery_note_item/delivery_note_item.json b/erpnext/stock/doctype/delivery_note_item/delivery_note_item.json
index 51c88be..f1f5d96 100644
--- a/erpnext/stock/doctype/delivery_note_item/delivery_note_item.json
+++ b/erpnext/stock/doctype/delivery_note_item/delivery_note_item.json
@@ -757,6 +757,7 @@
},
{
"default": "0",
+ "fetch_from": "item_code.grant_commission",
"fieldname": "grant_commission",
"fieldtype": "Check",
"label": "Grant Commission",
@@ -767,12 +768,14 @@
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
- "modified": "2021-10-06 12:12:44.018872",
+ "modified": "2022-02-24 14:42:20.211085",
"modified_by": "Administrator",
"module": "Stock",
"name": "Delivery Note Item",
+ "naming_rule": "Random",
"owner": "Administrator",
"permissions": [],
"sort_field": "modified",
- "sort_order": "DESC"
-}
+ "sort_order": "DESC",
+ "states": []
+}
\ No newline at end of file
diff --git a/erpnext/stock/doctype/delivery_trip/test_delivery_trip.py b/erpnext/stock/doctype/delivery_trip/test_delivery_trip.py
index 321f48b..dcdff4a 100644
--- a/erpnext/stock/doctype/delivery_trip/test_delivery_trip.py
+++ b/erpnext/stock/doctype/delivery_trip/test_delivery_trip.py
@@ -4,6 +4,7 @@
import unittest
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import add_days, flt, now_datetime, nowdate
import erpnext
@@ -12,10 +13,10 @@
make_expense_claim,
notify_customers,
)
-from erpnext.tests.utils import ERPNextTestCase, create_test_contact_and_address
+from erpnext.tests.utils import create_test_contact_and_address
-class TestDeliveryTrip(ERPNextTestCase):
+class TestDeliveryTrip(FrappeTestCase):
def setUp(self):
super().setUp()
driver = create_driver()
diff --git a/erpnext/stock/doctype/item/item.js b/erpnext/stock/doctype/item/item.js
index 2a30ca1..ffea9c2 100644
--- a/erpnext/stock/doctype/item/item.js
+++ b/erpnext/stock/doctype/item/item.js
@@ -545,7 +545,7 @@
let selected_attributes = {};
me.multiple_variant_dialog.$wrapper.find('.form-column').each((i, col) => {
if(i===0) return;
- let attribute_name = $(col).find('label').html();
+ let attribute_name = $(col).find('label').html().trim();
selected_attributes[attribute_name] = [];
let checked_opts = $(col).find('.checkbox input');
checked_opts.each((i, opt) => {
@@ -594,7 +594,7 @@
const increment = r.message.increment;
let values = [];
- for(var i = from; i <= to; i += increment) {
+ for(var i = from; i <= to; i = flt(i + increment, 6)) {
values.push(i);
}
attr_val_fields[d.attribute] = values;
diff --git a/erpnext/stock/doctype/item/item.json b/erpnext/stock/doctype/item/item.json
index e71cdb3..c797187 100644
--- a/erpnext/stock/doctype/item/item.json
+++ b/erpnext/stock/doctype/item/item.json
@@ -48,6 +48,7 @@
"warranty_period",
"weight_per_unit",
"weight_uom",
+ "allow_negative_stock",
"reorder_section",
"reorder_levels",
"unit_of_measure_conversion",
@@ -346,7 +347,7 @@
"fieldname": "valuation_method",
"fieldtype": "Select",
"label": "Valuation Method",
- "options": "\nFIFO\nMoving Average"
+ "options": "\nFIFO\nMoving Average\nLIFO"
},
{
"depends_on": "is_stock_item",
@@ -907,6 +908,12 @@
"fieldname": "is_grouped_asset",
"fieldtype": "Check",
"label": "Create Grouped Asset"
+ },
+ {
+ "default": "0",
+ "fieldname": "allow_negative_stock",
+ "fieldtype": "Check",
+ "label": "Allow Negative Stock"
}
],
"icon": "fa fa-tag",
@@ -914,7 +921,7 @@
"image_field": "image",
"index_web_pages_for_search": 1,
"links": [],
- "modified": "2022-01-18 12:57:54.273202",
+ "modified": "2022-02-11 08:07:46.663220",
"modified_by": "Administrator",
"module": "Stock",
"name": "Item",
@@ -987,4 +994,4 @@
"states": [],
"title_field": "item_name",
"track_changes": 1
-}
\ No newline at end of file
+}
diff --git a/erpnext/stock/doctype/item/item.py b/erpnext/stock/doctype/item/item.py
index b9e8b3f..494fb3b 100644
--- a/erpnext/stock/doctype/item/item.py
+++ b/erpnext/stock/doctype/item/item.py
@@ -398,6 +398,7 @@
if merge:
self.validate_properties_before_merge(new_name)
+ self.validate_duplicate_product_bundles_before_merge(old_name, new_name)
self.validate_duplicate_website_item_before_merge(old_name, new_name)
def after_rename(self, old_name, new_name, merge):
@@ -462,6 +463,20 @@
msg += ": \n" + ", ".join([self.meta.get_label(fld) for fld in field_list])
frappe.throw(msg, title=_("Cannot Merge"), exc=DataValidationError)
+ def validate_duplicate_product_bundles_before_merge(self, old_name, new_name):
+ "Block merge if both old and new items have product bundles."
+ old_bundle = frappe.get_value("Product Bundle",filters={"new_item_code": old_name})
+ new_bundle = frappe.get_value("Product Bundle",filters={"new_item_code": new_name})
+
+ if old_bundle and new_bundle:
+ bundle_link = get_link_to_form("Product Bundle", old_bundle)
+ old_name, new_name = frappe.bold(old_name), frappe.bold(new_name)
+
+ msg = _("Please delete Product Bundle {0}, before merging {1} into {2}").format(
+ bundle_link, old_name, new_name
+ )
+ frappe.throw(msg, title=_("Cannot Merge"), exc=DataValidationError)
+
def validate_duplicate_website_item_before_merge(self, old_name, new_name):
"""
Block merge if both old and new items have website items against them.
@@ -479,8 +494,9 @@
old_web_item = [d.get("name") for d in web_items if d.get("item_code") == old_name][0]
web_item_link = get_link_to_form("Website Item", old_web_item)
+ old_name, new_name = frappe.bold(old_name), frappe.bold(new_name)
- msg = f"Please delete linked Website Item {frappe.bold(web_item_link)} before merging {old_name} and {new_name}"
+ msg = f"Please delete linked Website Item {frappe.bold(web_item_link)} before merging {old_name} into {new_name}"
frappe.throw(_(msg), title=_("Cannot Merge"), exc=DataValidationError)
def set_last_purchase_rate(self, new_name):
diff --git a/erpnext/stock/doctype/item/test_item.py b/erpnext/stock/doctype/item/test_item.py
index fc45ba9..d7671b1 100644
--- a/erpnext/stock/doctype/item/test_item.py
+++ b/erpnext/stock/doctype/item/test_item.py
@@ -6,6 +6,8 @@
import frappe
from frappe.test_runner import make_test_objects
+from frappe.tests.utils import FrappeTestCase, change_settings
+from frappe.utils import add_days, today
from erpnext.controllers.item_variant import (
InvalidItemAttributeValueError,
@@ -14,6 +16,7 @@
get_variant,
)
from erpnext.stock.doctype.item.item import (
+ DataValidationError,
InvalidBarcode,
StockExistsForTemplate,
get_item_attribute,
@@ -23,7 +26,6 @@
)
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
from erpnext.stock.get_item_details import get_item_details
-from erpnext.tests.utils import ERPNextTestCase, change_settings
test_ignore = ["BOM"]
test_dependencies = ["Warehouse", "Item Group", "Item Tax Template", "Brand", "Item Attribute"]
@@ -51,7 +53,7 @@
return item
-class TestItem(ERPNextTestCase):
+class TestItem(FrappeTestCase):
def setUp(self):
super().setUp()
frappe.flags.attribute_values = None
@@ -387,6 +389,26 @@
self.assertTrue(frappe.db.get_value("Bin",
{"item_code": "Test Item for Merging 2", "warehouse": "_Test Warehouse 1 - _TC"}))
+ def test_item_merging_with_product_bundle(self):
+ from erpnext.selling.doctype.product_bundle.test_product_bundle import make_product_bundle
+
+ create_item("Test Item Bundle Item 1", is_stock_item=False)
+ create_item("Test Item Bundle Item 2", is_stock_item=False)
+ create_item("Test Item inside Bundle")
+ bundle_items = ["Test Item inside Bundle"]
+
+ # make bundles for both items
+ bundle1 = make_product_bundle("Test Item Bundle Item 1", bundle_items, qty=2)
+ make_product_bundle("Test Item Bundle Item 2", bundle_items, qty=2)
+
+ with self.assertRaises(DataValidationError):
+ frappe.rename_doc("Item", "Test Item Bundle Item 1", "Test Item Bundle Item 2", merge=True)
+
+ bundle1.delete()
+ frappe.rename_doc("Item", "Test Item Bundle Item 1", "Test Item Bundle Item 2", merge=True)
+
+ self.assertFalse(frappe.db.exists("Item", "Test Item Bundle Item 1"))
+
def test_uom_conversion_factor(self):
if frappe.db.exists('Item', 'Test Item UOM'):
frappe.delete_doc('Item', 'Test Item UOM')
@@ -608,6 +630,45 @@
item.item_group = "All Item Groups"
item.save() # if item code saved without item_code then series worked
+ @change_settings("Stock Settings", {"allow_negative_stock": 0})
+ def test_item_wise_negative_stock(self):
+ """ When global settings are disabled check that item that allows
+ negative stock can still consume material in all known stock
+ transactions that consume inventory."""
+ from erpnext.stock.stock_ledger import is_negative_stock_allowed
+
+ item = make_item("_TestNegativeItemSetting", {"allow_negative_stock": 1, "valuation_rate": 100})
+ self.assertTrue(is_negative_stock_allowed(item_code=item.name))
+
+ self.consume_item_code_with_differet_stock_transactions(item_code=item.name)
+
+ @change_settings("Stock Settings", {"allow_negative_stock": 0})
+ def test_backdated_negative_stock(self):
+ """ same as test above but backdated entries """
+ from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
+ item = make_item("_TestNegativeItemSetting", {"allow_negative_stock": 1, "valuation_rate": 100})
+
+ # create a future entry so all new entries are backdated
+ make_stock_entry(qty=1, item_code=item.name, target="_Test Warehouse - _TC", posting_date = add_days(today(), 5))
+ self.consume_item_code_with_differet_stock_transactions(item_code=item.name)
+
+
+ def consume_item_code_with_differet_stock_transactions(self, item_code, warehouse="_Test Warehouse - _TC"):
+ from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
+ from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
+ from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import make_purchase_receipt
+ from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
+
+ typical_args = {"item_code": item_code, "warehouse": warehouse}
+
+ create_delivery_note(**typical_args)
+ create_sales_invoice(update_stock=1, **typical_args)
+ make_stock_entry(item_code=item_code, source=warehouse, qty=1, purpose="Material Issue")
+ make_stock_entry(item_code=item_code, source=warehouse, target="Stores - _TC", qty=1)
+ # standalone return
+ make_purchase_receipt(is_return=True, qty=-1, **typical_args)
+
+
def set_item_variant_settings(fields):
doc = frappe.get_doc('Item Variant Settings')
diff --git a/erpnext/stock/doctype/item_alternative/test_item_alternative.py b/erpnext/stock/doctype/item_alternative/test_item_alternative.py
index 3976af4..501c1c1 100644
--- a/erpnext/stock/doctype/item_alternative/test_item_alternative.py
+++ b/erpnext/stock/doctype/item_alternative/test_item_alternative.py
@@ -4,6 +4,7 @@
import json
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import flt
from erpnext.buying.doctype.purchase_order.purchase_order import (
@@ -18,10 +19,9 @@
from erpnext.stock.doctype.stock_reconciliation.test_stock_reconciliation import (
create_stock_reconciliation,
)
-from erpnext.tests.utils import ERPNextTestCase
-class TestItemAlternative(ERPNextTestCase):
+class TestItemAlternative(FrappeTestCase):
def setUp(self):
super().setUp()
make_items()
diff --git a/erpnext/stock/doctype/item_attribute/test_item_attribute.py b/erpnext/stock/doctype/item_attribute/test_item_attribute.py
index 0b7ca25..055c22e 100644
--- a/erpnext/stock/doctype/item_attribute/test_item_attribute.py
+++ b/erpnext/stock/doctype/item_attribute/test_item_attribute.py
@@ -6,11 +6,12 @@
test_records = frappe.get_test_records('Item Attribute')
+from frappe.tests.utils import FrappeTestCase
+
from erpnext.stock.doctype.item_attribute.item_attribute import ItemAttributeIncrementError
-from erpnext.tests.utils import ERPNextTestCase
-class TestItemAttribute(ERPNextTestCase):
+class TestItemAttribute(FrappeTestCase):
def setUp(self):
super().setUp()
if frappe.db.exists("Item Attribute", "_Test_Length"):
diff --git a/erpnext/stock/doctype/item_price/test_item_price.py b/erpnext/stock/doctype/item_price/test_item_price.py
index f81770e..6ceba3f 100644
--- a/erpnext/stock/doctype/item_price/test_item_price.py
+++ b/erpnext/stock/doctype/item_price/test_item_price.py
@@ -4,13 +4,13 @@
import frappe
from frappe.test_runner import make_test_records_for_doctype
+from frappe.tests.utils import FrappeTestCase
from erpnext.stock.doctype.item_price.item_price import ItemPriceDuplicateItem
from erpnext.stock.get_item_details import get_price_list_rate_for, process_args
-from erpnext.tests.utils import ERPNextTestCase
-class TestItemPrice(ERPNextTestCase):
+class TestItemPrice(FrappeTestCase):
def setUp(self):
super().setUp()
frappe.db.sql("delete from `tabItem Price`")
diff --git a/erpnext/stock/doctype/landed_cost_voucher/test_landed_cost_voucher.py b/erpnext/stock/doctype/landed_cost_voucher/test_landed_cost_voucher.py
index df8cadd..6dc4fee 100644
--- a/erpnext/stock/doctype/landed_cost_voucher/test_landed_cost_voucher.py
+++ b/erpnext/stock/doctype/landed_cost_voucher/test_landed_cost_voucher.py
@@ -4,20 +4,21 @@
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import add_to_date, flt, now
from erpnext.accounts.doctype.account.test_account import create_account, get_inventory_account
from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import make_purchase_invoice
from erpnext.accounts.utils import update_gl_entries_after
from erpnext.assets.doctype.asset.test_asset import create_asset_category, create_fixed_asset_item
+from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import (
get_gl_entries,
make_purchase_receipt,
)
-from erpnext.tests.utils import ERPNextTestCase
-class TestLandedCostVoucher(ERPNextTestCase):
+class TestLandedCostVoucher(FrappeTestCase):
def test_landed_cost_voucher(self):
frappe.db.set_value("Buying Settings", None, "allow_multiple_items", 1)
@@ -177,6 +178,53 @@
self.assertEqual(serial_no.purchase_rate - serial_no_rate, 5.0)
self.assertEqual(serial_no.warehouse, "Stores - TCP1")
+ def test_serialized_lcv_delivered(self):
+ """In some cases you'd want to deliver before you can know all the
+ landed costs, this should be allowed for serial nos too.
+
+ Case:
+ - receipt a serial no @ X rate
+ - delivery the serial no @ X rate
+ - add LCV to receipt X + Y
+ - LCV should be successful
+ - delivery should reflect X+Y valuation.
+ """
+ serial_no = "LCV_TEST_SR_NO"
+ item_code = "_Test Serialized Item"
+ warehouse = "Stores - TCP1"
+
+ pr = make_purchase_receipt(company="_Test Company with perpetual inventory",
+ warehouse=warehouse, qty=1, rate=200,
+ item_code=item_code, serial_no=serial_no)
+
+ serial_no_rate = frappe.db.get_value("Serial No", serial_no, "purchase_rate")
+
+ # deliver it before creating LCV
+ dn = create_delivery_note(item_code=item_code,
+ company='_Test Company with perpetual inventory', warehouse='Stores - TCP1',
+ serial_no=serial_no, qty=1, rate=500,
+ cost_center = 'Main - TCP1', expense_account = "Cost of Goods Sold - TCP1")
+
+ charges = 10
+ create_landed_cost_voucher("Purchase Receipt", pr.name, pr.company, charges=charges)
+
+ new_purchase_rate = serial_no_rate + charges
+
+ serial_no = frappe.db.get_value("Serial No", serial_no,
+ ["warehouse", "purchase_rate"], as_dict=1)
+
+ self.assertEqual(serial_no.purchase_rate, new_purchase_rate)
+
+ stock_value_difference = frappe.db.get_value("Stock Ledger Entry",
+ filters={
+ "voucher_no": dn.name,
+ "voucher_type": dn.doctype,
+ "is_cancelled": 0 # LCV cancels with same name.
+ },
+ fieldname="stock_value_difference")
+
+ # reposting should update the purchase rate in future delivery
+ self.assertEqual(stock_value_difference, -new_purchase_rate)
def test_landed_cost_voucher_for_odd_numbers (self):
pr = make_purchase_receipt(company="_Test Company with perpetual inventory", warehouse = "Stores - TCP1", supplier_warehouse = "Work in Progress - TCP1", do_not_save=True)
diff --git a/erpnext/stock/doctype/material_request/material_request.py b/erpnext/stock/doctype/material_request/material_request.py
index 103e8d6..51209ac 100644
--- a/erpnext/stock/doctype/material_request/material_request.py
+++ b/erpnext/stock/doctype/material_request/material_request.py
@@ -56,14 +56,13 @@
if actual_so_qty and (flt(so_items[so_no][item]) + already_indented > actual_so_qty):
frappe.throw(_("Material Request of maximum {0} can be made for Item {1} against Sales Order {2}").format(actual_so_qty - already_indented, item, so_no))
- # Validate
- # ---------------------
def validate(self):
super(MaterialRequest, self).validate()
self.validate_schedule_date()
self.check_for_on_hold_or_closed_status('Sales Order', 'sales_order')
self.validate_uom_is_integer("uom", "qty")
+ self.validate_material_request_type()
if not self.status:
self.status = "Draft"
@@ -83,6 +82,12 @@
self.reset_default_field_value("set_warehouse", "items", "warehouse")
self.reset_default_field_value("set_from_warehouse", "items", "from_warehouse")
+ def validate_material_request_type(self):
+ """ Validate fields in accordance with selected type """
+
+ if self.material_request_type != "Customer Provided":
+ self.customer = None
+
def set_title(self):
'''Set title as comma separated list of items'''
if not self.title:
@@ -533,6 +538,7 @@
"stock_uom": d.stock_uom,
"expected_delivery_date": d.schedule_date,
"sales_order": d.sales_order,
+ "sales_order_item": d.get("sales_order_item"),
"bom_no": get_item_details(d.item_code).bom_no,
"material_request": mr.name,
"material_request_item": d.name,
diff --git a/erpnext/stock/doctype/material_request/test_material_request.py b/erpnext/stock/doctype/material_request/test_material_request.py
index 383b0ae..866f3ab 100644
--- a/erpnext/stock/doctype/material_request/test_material_request.py
+++ b/erpnext/stock/doctype/material_request/test_material_request.py
@@ -6,6 +6,7 @@
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import flt, today
from erpnext.stock.doctype.item.test_item import create_item
@@ -15,10 +16,9 @@
make_supplier_quotation,
raise_work_orders,
)
-from erpnext.tests.utils import ERPNextTestCase
-class TestMaterialRequest(ERPNextTestCase):
+class TestMaterialRequest(FrappeTestCase):
def test_make_purchase_order(self):
mr = frappe.copy_doc(test_records[0]).insert()
@@ -626,13 +626,13 @@
mr.schedule_date = today()
if not frappe.db.get_value('UOM Conversion Detail',
- {'parent': item.item_code, 'uom': 'Kg'}):
- item_doc = frappe.get_doc('Item', item.item_code)
- item_doc.append('uoms', {
- 'uom': 'Kg',
- 'conversion_factor': 5
- })
- item_doc.save(ignore_permissions=True)
+ {'parent': item.item_code, 'uom': 'Kg'}):
+ item_doc = frappe.get_doc('Item', item.item_code)
+ item_doc.append('uoms', {
+ 'uom': 'Kg',
+ 'conversion_factor': 5
+ })
+ item_doc.save(ignore_permissions=True)
item.uom = 'Kg'
for item in mr.items:
diff --git a/erpnext/stock/doctype/packed_item/packed_item.json b/erpnext/stock/doctype/packed_item/packed_item.json
index d2d4789..d6e2e9c 100644
--- a/erpnext/stock/doctype/packed_item/packed_item.json
+++ b/erpnext/stock/doctype/packed_item/packed_item.json
@@ -26,6 +26,7 @@
"section_break_13",
"actual_qty",
"projected_qty",
+ "ordered_qty",
"column_break_16",
"incoming_rate",
"page_break",
@@ -224,13 +225,21 @@
"label": "Rate",
"print_hide": 1,
"read_only": 1
+ },
+ {
+ "allow_on_submit": 1,
+ "fieldname": "ordered_qty",
+ "fieldtype": "Float",
+ "label": "Ordered Qty",
+ "no_copy": 1,
+ "read_only": 1
}
],
"idx": 1,
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
- "modified": "2022-01-28 16:03:30.780111",
+ "modified": "2022-02-22 12:57:45.325488",
"modified_by": "Administrator",
"module": "Stock",
"name": "Packed Item",
diff --git a/erpnext/stock/doctype/packed_item/test_packed_item.py b/erpnext/stock/doctype/packed_item/test_packed_item.py
index 5cbaa1e..94268a8 100644
--- a/erpnext/stock/doctype/packed_item/test_packed_item.py
+++ b/erpnext/stock/doctype/packed_item/test_packed_item.py
@@ -1,42 +1,45 @@
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
+from frappe.tests.utils import FrappeTestCase, change_settings
+from frappe.utils import add_to_date, nowdate
+
from erpnext.selling.doctype.product_bundle.test_product_bundle import make_product_bundle
from erpnext.selling.doctype.sales_order.sales_order import make_delivery_note
from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
from erpnext.stock.doctype.item.test_item import make_item
-from erpnext.tests.utils import ERPNextTestCase, change_settings
+from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import get_gl_entries
+from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
-class TestPackedItem(ERPNextTestCase):
+class TestPackedItem(FrappeTestCase):
"Test impact on Packed Items table in various scenarios."
@classmethod
def setUpClass(cls) -> None:
- make_item("_Test Product Bundle X", {"is_stock_item": 0})
- make_item("_Test Bundle Item 1", {"is_stock_item": 1})
- make_item("_Test Bundle Item 2", {"is_stock_item": 1})
+ super().setUpClass()
+ cls.bundle = "_Test Product Bundle X"
+ cls.bundle_items = ["_Test Bundle Item 1", "_Test Bundle Item 2"]
+ make_item(cls.bundle, {"is_stock_item": 0})
+ for item in cls.bundle_items:
+ make_item(item, {"is_stock_item": 1})
+
make_item("_Test Normal Stock Item", {"is_stock_item": 1})
- make_product_bundle(
- "_Test Product Bundle X",
- ["_Test Bundle Item 1", "_Test Bundle Item 2"],
- qty=2
- )
+ make_product_bundle(cls.bundle, cls.bundle_items, qty=2)
def test_adding_bundle_item(self):
"Test impact on packed items if bundle item row is added."
- so = make_sales_order(item_code = "_Test Product Bundle X", qty=1,
+ so = make_sales_order(item_code = self.bundle, qty=1,
do_not_submit=True)
self.assertEqual(so.items[0].qty, 1)
self.assertEqual(len(so.packed_items), 2)
- self.assertEqual(so.packed_items[0].item_code, "_Test Bundle Item 1")
+ self.assertEqual(so.packed_items[0].item_code, self.bundle_items[0])
self.assertEqual(so.packed_items[0].qty, 2)
def test_updating_bundle_item(self):
"Test impact on packed items if bundle item row is updated."
- so = make_sales_order(item_code = "_Test Product Bundle X", qty=1,
- do_not_submit=True)
+ so = make_sales_order(item_code=self.bundle, qty=1, do_not_submit=True)
so.items[0].qty = 2 # change qty
so.save()
@@ -55,7 +58,7 @@
so_items = []
for qty in [2, 4, 6, 8]:
so_items.append({
- "item_code": "_Test Product Bundle X",
+ "item_code": self.bundle,
"qty": qty,
"rate": 400,
"warehouse": "_Test Warehouse - _TC"
@@ -66,7 +69,7 @@
# check alternate rows for qty
self.assertEqual(len(so.packed_items), 8)
- self.assertEqual(so.packed_items[1].item_code, "_Test Bundle Item 2")
+ self.assertEqual(so.packed_items[1].item_code, self.bundle_items[1])
self.assertEqual(so.packed_items[1].qty, 4)
self.assertEqual(so.packed_items[3].qty, 8)
self.assertEqual(so.packed_items[5].qty, 12)
@@ -94,8 +97,7 @@
@change_settings("Selling Settings", {"editable_bundle_item_rates": 1})
def test_bundle_item_cumulative_price(self):
"Test if Bundle Item rate is cumulative from packed items."
- so = make_sales_order(item_code = "_Test Product Bundle X", qty=2,
- do_not_submit=True)
+ so = make_sales_order(item_code=self.bundle, qty=2, do_not_submit=True)
so.packed_items[0].rate = 150
so.packed_items[1].rate = 200
@@ -109,7 +111,7 @@
so_items = []
for qty in [2, 4]:
so_items.append({
- "item_code": "_Test Product Bundle X",
+ "item_code": self.bundle,
"qty": qty,
"rate": 400,
"warehouse": "_Test Warehouse - _TC"
@@ -124,4 +126,33 @@
self.assertEqual(len(dn.packed_items), 4)
self.assertEqual(dn.packed_items[2].qty, 6)
- self.assertEqual(dn.packed_items[3].qty, 6)
\ No newline at end of file
+ self.assertEqual(dn.packed_items[3].qty, 6)
+
+ def test_reposting_packed_items(self):
+ warehouse = "Stores - TCP1"
+ company = "_Test Company with perpetual inventory"
+
+ today = nowdate()
+ yesterday = add_to_date(today, days=-1, as_string=True)
+
+ for item in self.bundle_items:
+ make_stock_entry(item_code=item, to_warehouse=warehouse, qty=10, rate=100, posting_date=today)
+
+ so = make_sales_order(item_code = self.bundle, qty=1, company=company, warehouse=warehouse)
+
+ dn = make_delivery_note(so.name)
+ dn.save()
+ dn.submit()
+
+ gles = get_gl_entries(dn.doctype, dn.name)
+ credit_before_repost = sum(gle.credit for gle in gles)
+
+ # backdated stock entry
+ for item in self.bundle_items:
+ make_stock_entry(item_code=item, to_warehouse=warehouse, qty=10, rate=200, posting_date=yesterday)
+
+ # assert correct reposting
+ gles = get_gl_entries(dn.doctype, dn.name)
+ credit_after_reposting = sum(gle.credit for gle in gles)
+ self.assertNotEqual(credit_before_repost, credit_after_reposting)
+ self.assertAlmostEqual(credit_after_reposting, 2 * credit_before_repost)
diff --git a/erpnext/stock/doctype/packing_slip/test_packing_slip.py b/erpnext/stock/doctype/packing_slip/test_packing_slip.py
index 5eb6b73..bc405b2 100644
--- a/erpnext/stock/doctype/packing_slip/test_packing_slip.py
+++ b/erpnext/stock/doctype/packing_slip/test_packing_slip.py
@@ -4,7 +4,7 @@
import unittest
# test_records = frappe.get_test_records('Packing Slip')
-from erpnext.tests.utils import ERPNextTestCase
+from frappe.tests.utils import FrappeTestCase
class TestPackingSlip(unittest.TestCase):
diff --git a/erpnext/stock/doctype/pick_list/pick_list.py b/erpnext/stock/doctype/pick_list/pick_list.py
index 5484a11..b2eaecb 100644
--- a/erpnext/stock/doctype/pick_list/pick_list.py
+++ b/erpnext/stock/doctype/pick_list/pick_list.py
@@ -272,9 +272,9 @@
and IFNULL(batch.`expiry_date`, '2200-01-01') > %(today)s
{warehouse_condition}
GROUP BY
- `warehouse`,
- `batch_no`,
- `item_code`
+ sle.`warehouse`,
+ sle.`batch_no`,
+ sle.`item_code`
HAVING `qty` > 0
ORDER BY IFNULL(batch.`expiry_date`, '2200-01-01'), batch.`creation`
""".format(warehouse_condition=warehouse_condition), { #nosec
diff --git a/erpnext/stock/doctype/pick_list/test_pick_list.py b/erpnext/stock/doctype/pick_list/test_pick_list.py
index 41e3150..f3b6b89 100644
--- a/erpnext/stock/doctype/pick_list/test_pick_list.py
+++ b/erpnext/stock/doctype/pick_list/test_pick_list.py
@@ -6,16 +6,17 @@
test_dependencies = ['Item', 'Sales Invoice', 'Stock Entry', 'Batch']
+from frappe.tests.utils import FrappeTestCase
+
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.purchase_receipt.test_purchase_receipt import make_purchase_receipt
from erpnext.stock.doctype.stock_reconciliation.stock_reconciliation import (
EmptyStockReconciliationItemsError,
)
-from erpnext.tests.utils import ERPNextTestCase
-class TestPickList(ERPNextTestCase):
+class TestPickList(FrappeTestCase):
def test_pick_list_picks_warehouse_for_each_item(self):
try:
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
index ffdf8c4..33e40c8 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -288,9 +288,6 @@
{"voucher_type": "Purchase Receipt", "voucher_no": self.name,
"voucher_detail_no": d.name, "warehouse": d.warehouse, "is_cancelled": 0}, "stock_value_difference")
- if not stock_value_diff:
- continue
-
warehouse_account_name = warehouse_account[d.warehouse]["account"]
warehouse_account_currency = warehouse_account[d.warehouse]["account_currency"]
supplier_warehouse_account = warehouse_account.get(self.supplier_warehouse, {}).get("account")
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt_list.js b/erpnext/stock/doctype/purchase_receipt/purchase_receipt_list.js
index 77711de..4029f0c 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt_list.js
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt_list.js
@@ -13,5 +13,13 @@
} else if (flt(doc.grand_total) === 0 || flt(doc.per_billed, 2) === 100) {
return [__("Completed"), "green", "per_billed,=,100"];
}
+ },
+
+ onload: function(listview) {
+
+ listview.page.add_action_item(__("Purchase Invoice"), ()=>{
+ erpnext.bulk_transaction_processing.create(listview, "Purchase Receipt", "Purchase Invoice");
+ });
}
+
};
diff --git a/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
index b87d920..fa28f22 100644
--- a/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
@@ -4,8 +4,10 @@
import json
import unittest
+from collections import defaultdict
import frappe
+from frappe.tests.utils import FrappeTestCase, change_settings
from frappe.utils import add_days, cint, cstr, flt, today
import erpnext
@@ -16,10 +18,9 @@
from erpnext.stock.doctype.serial_no.serial_no import SerialNoDuplicateError, get_serial_nos
from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
from erpnext.stock.stock_ledger import SerialNoExistsInFutureTransaction
-from erpnext.tests.utils import ERPNextTestCase
-class TestPurchaseReceipt(ERPNextTestCase):
+class TestPurchaseReceipt(FrappeTestCase):
def setUp(self):
frappe.db.set_value("Buying Settings", None, "allow_multiple_items", 1)
@@ -160,6 +161,15 @@
qty=abs(existing_bin_qty)
)
+ existing_bin_qty, existing_bin_stock_value = frappe.db.get_value(
+ "Bin",
+ {
+ "item_code": "_Test Item",
+ "warehouse": "_Test Warehouse - _TC"
+ },
+ ["actual_qty", "stock_value"]
+ )
+
pr = make_purchase_receipt()
stock_value_difference = frappe.db.get_value(
@@ -1387,6 +1397,36 @@
automatically_fetch_payment_terms(enable=0)
+ @change_settings("Stock Settings", {"allow_negative_stock": 1})
+ def test_neg_to_positive(self):
+ from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
+
+ item_code = "_TestNegToPosItem"
+ warehouse = "Stores - TCP1"
+ company = "_Test Company with perpetual inventory"
+ account = "Stock Received But Not Billed - TCP1"
+
+ make_item(item_code)
+ se = make_stock_entry(item_code=item_code, from_warehouse=warehouse, qty=50, do_not_save=True, rate=0)
+ se.items[0].allow_zero_valuation_rate = 1
+ se.save()
+ se.submit()
+
+ pr = make_purchase_receipt(
+ qty=50,
+ rate=1,
+ item_code=item_code,
+ warehouse=warehouse,
+ get_taxes_and_charges=True,
+ company=company,
+ )
+ gles = get_gl_entries(pr.doctype, pr.name)
+
+ for gle in gles:
+ if gle.account == account:
+ self.assertEqual(gle.credit, 50)
+
+
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
@@ -1509,6 +1549,7 @@
"conversion_factor": args.conversion_factor or 1.0,
"stock_qty": flt(qty) * (flt(args.conversion_factor) or 1.0),
"serial_no": args.serial_no,
+ "batch_no": args.batch_no,
"stock_uom": args.stock_uom or "_Test UOM",
"uom": uom,
"cost_center": args.cost_center or frappe.get_cached_value('Company', pr.company, 'cost_center'),
diff --git a/erpnext/stock/doctype/putaway_rule/putaway_rule.py b/erpnext/stock/doctype/putaway_rule/putaway_rule.py
index 523ba12..4e472a9 100644
--- a/erpnext/stock/doctype/putaway_rule/putaway_rule.py
+++ b/erpnext/stock/doctype/putaway_rule/putaway_rule.py
@@ -9,7 +9,7 @@
import frappe
from frappe import _
from frappe.model.document import Document
-from frappe.utils import cint, floor, flt, nowdate
+from frappe.utils import cint, cstr, floor, flt, nowdate
from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
from erpnext.stock.utils import get_stock_balance
@@ -142,11 +142,44 @@
if items_not_accomodated:
show_unassigned_items_message(items_not_accomodated)
- items[:] = updated_table if updated_table else items # modify items table
+ if updated_table and _items_changed(items, updated_table, doctype):
+ items[:] = updated_table
+ frappe.msgprint(_("Applied putaway rules."), alert=True)
if sync and json.loads(sync): # sync with client side
return items
+def _items_changed(old, new, doctype: str) -> bool:
+ """ Check if any items changed by application of putaway rules.
+
+ If not, changing item table can have side effects since `name` items also changes.
+ """
+ if len(old) != len(new):
+ return True
+
+ old = [frappe._dict(item) if isinstance(item, dict) else item for item in old]
+
+ if doctype == "Stock Entry":
+ compare_keys = ("item_code", "t_warehouse", "transfer_qty", "serial_no")
+ sort_key = lambda item: (item.item_code, cstr(item.t_warehouse), # noqa
+ flt(item.transfer_qty), cstr(item.serial_no))
+ else:
+ # purchase receipt / invoice
+ compare_keys = ("item_code", "warehouse", "stock_qty", "received_qty", "serial_no")
+ sort_key = lambda item: (item.item_code, cstr(item.warehouse), # noqa
+ flt(item.stock_qty), flt(item.received_qty), cstr(item.serial_no))
+
+ old_sorted = sorted(old, key=sort_key)
+ new_sorted = sorted(new, key=sort_key)
+
+ # Once sorted by all relevant keys both tables should align if they are same.
+ for old_item, new_item in zip(old_sorted, new_sorted):
+ for key in compare_keys:
+ if old_item.get(key) != new_item.get(key):
+ return True
+ return False
+
+
def get_ordered_putaway_rules(item_code, company, source_warehouse=None):
"""Returns an ordered list of putaway rules to apply on an item."""
filters = {
diff --git a/erpnext/stock/doctype/putaway_rule/test_putaway_rule.py b/erpnext/stock/doctype/putaway_rule/test_putaway_rule.py
index bd4d811..4e8d71f 100644
--- a/erpnext/stock/doctype/putaway_rule/test_putaway_rule.py
+++ b/erpnext/stock/doctype/putaway_rule/test_putaway_rule.py
@@ -2,6 +2,7 @@
# See license.txt
import frappe
+from frappe.tests.utils import FrappeTestCase
from erpnext.stock.doctype.batch.test_batch import make_new_batch
from erpnext.stock.doctype.item.test_item import make_item
@@ -9,10 +10,9 @@
from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
from erpnext.stock.get_item_details import get_conversion_factor
-from erpnext.tests.utils import ERPNextTestCase
-class TestPutawayRule(ERPNextTestCase):
+class TestPutawayRule(FrappeTestCase):
def setUp(self):
if not frappe.db.exists("Item", "_Rice"):
make_item("_Rice", {
@@ -35,6 +35,18 @@
new_uom.uom_name = "Bag"
new_uom.save()
+ def assertUnchangedItemsOnResave(self, doc):
+ """ Check if same items remain even after reapplication of rules.
+
+ This is required since some business logic like subcontracting
+ depends on `name` of items to be same if item isn't changed.
+ """
+ doc.reload()
+ old_items = {d.name for d in doc.items}
+ doc.save()
+ new_items = {d.name for d in doc.items}
+ self.assertSetEqual(old_items, new_items)
+
def test_putaway_rules_priority(self):
"""Test if rule is applied by priority, irrespective of free space."""
rule_1 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_1, capacity=200,
@@ -50,6 +62,8 @@
self.assertEqual(pr.items[1].qty, 100)
self.assertEqual(pr.items[1].warehouse, self.warehouse_2)
+ self.assertUnchangedItemsOnResave(pr)
+
pr.delete()
rule_1.delete()
rule_2.delete()
@@ -162,6 +176,8 @@
# leftover space was for 500 kg (0.5 Bag)
# Since Bag is a whole UOM, 1(out of 2) Bag will be unassigned
+ self.assertUnchangedItemsOnResave(pr)
+
pr.delete()
rule_1.delete()
rule_2.delete()
@@ -196,6 +212,8 @@
self.assertEqual(pr.items[1].warehouse, self.warehouse_1)
self.assertEqual(pr.items[1].putaway_rule, rule_1.name)
+ self.assertUnchangedItemsOnResave(pr)
+
pr.delete()
rule_1.delete()
@@ -239,6 +257,8 @@
self.assertEqual(stock_entry_item.qty, 100) # unassigned 100 out of 200 Kg
self.assertEqual(stock_entry_item.putaway_rule, rule_2.name)
+ self.assertUnchangedItemsOnResave(stock_entry)
+
stock_entry.delete()
rule_1.delete()
rule_2.delete()
@@ -294,6 +314,8 @@
self.assertEqual(stock_entry.items[2].qty, 200)
self.assertEqual(stock_entry.items[2].putaway_rule, rule_2.name)
+ self.assertUnchangedItemsOnResave(stock_entry)
+
stock_entry.delete()
rule_1.delete()
rule_2.delete()
@@ -344,6 +366,8 @@
self.assertEqual(stock_entry.items[1].serial_no, "\n".join(serial_nos[3:]))
self.assertEqual(stock_entry.items[1].batch_no, "BOTTL-BATCH-1")
+ self.assertUnchangedItemsOnResave(stock_entry)
+
stock_entry.delete()
pr.cancel()
rule_1.delete()
@@ -366,6 +390,8 @@
self.assertEqual(stock_entry_item.qty, 100)
self.assertEqual(stock_entry_item.putaway_rule, rule_1.name)
+ self.assertUnchangedItemsOnResave(stock_entry)
+
stock_entry.delete()
rule_1.delete()
rule_2.delete()
diff --git a/erpnext/stock/doctype/quality_inspection/test_quality_inspection.py b/erpnext/stock/doctype/quality_inspection/test_quality_inspection.py
index 308c628..601ca05 100644
--- a/erpnext/stock/doctype/quality_inspection/test_quality_inspection.py
+++ b/erpnext/stock/doctype/quality_inspection/test_quality_inspection.py
@@ -2,6 +2,7 @@
# See license.txt
import frappe
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import nowdate
from erpnext.controllers.stock_controller import (
@@ -13,12 +14,11 @@
from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
from erpnext.stock.doctype.item.test_item import create_item
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
-from erpnext.tests.utils import ERPNextTestCase
# test_records = frappe.get_test_records('Quality Inspection')
-class TestQualityInspection(ERPNextTestCase):
+class TestQualityInspection(FrappeTestCase):
def setUp(self):
super().setUp()
create_item("_Test Item with QA")
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 01c5e3e..977d470 100644
--- a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
+++ b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
@@ -13,7 +13,7 @@
check_if_stock_and_account_balance_synced,
update_gl_entries_after,
)
-from erpnext.stock.stock_ledger import repost_future_sle
+from erpnext.stock.stock_ledger import get_items_to_be_repost, repost_future_sle
class RepostItemValuation(Document):
@@ -138,13 +138,20 @@
if doc.based_on == 'Transaction':
ref_doc = frappe.get_doc(doc.voucher_type, doc.voucher_no)
- items, warehouses = ref_doc.get_items_and_warehouses()
+ doc_items, doc_warehouses = ref_doc.get_items_and_warehouses()
+
+ sles = get_items_to_be_repost(doc.voucher_type, doc.voucher_no)
+ sle_items = [sle.item_code for sle in sles]
+ sle_warehouse = [sle.warehouse for sle in sles]
+
+ items = list(set(doc_items).union(set(sle_items)))
+ warehouses = list(set(doc_warehouses).union(set(sle_warehouse)))
else:
items = [doc.item_code]
warehouses = [doc.warehouse]
update_gl_entries_after(doc.posting_date, doc.posting_time,
- warehouses, items, company=doc.company)
+ for_warehouses=warehouses, for_items=items, company=doc.company)
def notify_error_to_stock_managers(doc, traceback):
recipients = get_users_with_role("Stock Manager")
diff --git a/erpnext/stock/doctype/serial_no/test_serial_no.py b/erpnext/stock/doctype/serial_no/test_serial_no.py
index f8cea71..057a7d4 100644
--- a/erpnext/stock/doctype/serial_no/test_serial_no.py
+++ b/erpnext/stock/doctype/serial_no/test_serial_no.py
@@ -18,11 +18,12 @@
test_dependencies = ["Item"]
test_records = frappe.get_test_records('Serial No')
+from frappe.tests.utils import FrappeTestCase
+
from erpnext.stock.doctype.serial_no.serial_no import *
-from erpnext.tests.utils import ERPNextTestCase
-class TestSerialNo(ERPNextTestCase):
+class TestSerialNo(FrappeTestCase):
def tearDown(self):
frappe.db.rollback()
diff --git a/erpnext/stock/doctype/shipment/test_shipment.py b/erpnext/stock/doctype/shipment/test_shipment.py
index afe8218..317abb6 100644
--- a/erpnext/stock/doctype/shipment/test_shipment.py
+++ b/erpnext/stock/doctype/shipment/test_shipment.py
@@ -4,12 +4,12 @@
from datetime import date, timedelta
import frappe
+from frappe.tests.utils import FrappeTestCase
from erpnext.stock.doctype.delivery_note.delivery_note import make_shipment
-from erpnext.tests.utils import ERPNextTestCase
-class TestShipment(ERPNextTestCase):
+class TestShipment(FrappeTestCase):
def test_shipment_from_delivery_note(self):
delivery_note = create_test_delivery_note()
delivery_note.submit()
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.js b/erpnext/stock/doctype/stock_entry/stock_entry.js
index c4b8131..324ca7a 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.js
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.js
@@ -425,6 +425,7 @@
'posting_time' : frm.doc.posting_time,
'warehouse' : cstr(item.s_warehouse) || cstr(item.t_warehouse),
'serial_no' : item.serial_no,
+ 'batch_no' : item.batch_no,
'company' : frm.doc.company,
'qty' : item.s_warehouse ? -1*flt(item.transfer_qty) : flt(item.transfer_qty),
'voucher_type' : frm.doc.doctype,
@@ -457,6 +458,7 @@
'warehouse': cstr(child.s_warehouse) || cstr(child.t_warehouse),
'transfer_qty': child.transfer_qty,
'serial_no': child.serial_no,
+ 'batch_no': child.batch_no,
'qty': child.s_warehouse ? -1* child.transfer_qty : child.transfer_qty,
'posting_date': frm.doc.posting_date,
'posting_time': frm.doc.posting_time,
@@ -627,6 +629,12 @@
frm.events.set_serial_no(frm, cdt, cdn, () => {
frm.events.get_warehouse_details(frm, cdt, cdn);
});
+
+ // set allow_zero_valuation_rate to 0 if s_warehouse is selected.
+ let item = frappe.get_doc(cdt, cdn);
+ if (item.s_warehouse) {
+ item.allow_zero_valuation_rate = 0;
+ }
},
t_warehouse: function(frm, cdt, cdn) {
@@ -680,6 +688,7 @@
'warehouse' : cstr(d.s_warehouse) || cstr(d.t_warehouse),
'transfer_qty' : d.transfer_qty,
'serial_no' : d.serial_no,
+ 'batch_no' : d.batch_no,
'bom_no' : d.bom_no,
'expense_account' : d.expense_account,
'cost_center' : d.cost_center,
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.py b/erpnext/stock/doctype/stock_entry/stock_entry.py
index a2ef7b4..99cf4de 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.py
@@ -433,9 +433,10 @@
)
def set_actual_qty(self):
- allow_negative_stock = cint(frappe.db.get_value("Stock Settings", None, "allow_negative_stock"))
+ from erpnext.stock.stock_ledger import is_negative_stock_allowed
for d in self.get('items'):
+ allow_negative_stock = is_negative_stock_allowed(item_code=d.item_code)
previous_sle = get_previous_sle({
"item_code": d.item_code,
"warehouse": d.s_warehouse or d.t_warehouse,
@@ -509,7 +510,7 @@
d.basic_rate = get_valuation_rate(d.item_code, d.t_warehouse,
self.doctype, self.name, d.allow_zero_valuation_rate,
currency=erpnext.get_company_currency(self.company), company=self.company,
- raise_error_if_no_rate=raise_error_if_no_rate)
+ raise_error_if_no_rate=raise_error_if_no_rate, batch_no=d.batch_no)
d.basic_rate = flt(d.basic_rate, d.precision("basic_rate"))
if d.is_process_loss:
@@ -540,6 +541,7 @@
"posting_time": self.posting_time,
"qty": item.s_warehouse and -1*flt(item.transfer_qty) or flt(item.transfer_qty),
"serial_no": item.serial_no,
+ "batch_no": item.batch_no,
"voucher_type": self.doctype,
"voucher_no": self.name,
"company": self.company,
@@ -1115,7 +1117,7 @@
self.set_actual_qty()
self.update_items_for_process_loss()
self.validate_customer_provided_item()
- self.calculate_rate_and_amount()
+ self.calculate_rate_and_amount(raise_error_if_no_rate=False)
def set_scrap_items(self):
if self.purpose != "Send to Subcontractor" and self.purpose in ["Manufacture", "Repack"]:
diff --git a/erpnext/stock/doctype/stock_entry/test_stock_entry.py b/erpnext/stock/doctype/stock_entry/test_stock_entry.py
index 306f2c3..54c0e43 100644
--- a/erpnext/stock/doctype/stock_entry/test_stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/test_stock_entry.py
@@ -6,6 +6,7 @@
import frappe
from frappe.permissions import add_user_permission, remove_user_permission
+from frappe.tests.utils import FrappeTestCase, change_settings
from frappe.utils import flt, nowdate, nowtime
from erpnext.accounts.doctype.account.test_account import get_inventory_account
@@ -28,7 +29,6 @@
create_stock_reconciliation,
)
from erpnext.stock.stock_ledger import NegativeStockError, get_previous_sle
-from erpnext.tests.utils import ERPNextTestCase, change_settings
def get_sle(**args):
@@ -42,8 +42,9 @@
order by timestamp(posting_date, posting_time) desc, creation desc limit 1"""% condition,
values, as_dict=1)
-class TestStockEntry(ERPNextTestCase):
+class TestStockEntry(FrappeTestCase):
def tearDown(self):
+ frappe.db.rollback()
frappe.set_user("Administrator")
frappe.db.set_value("Manufacturing Settings", None, "material_consumption", "0")
@@ -565,6 +566,7 @@
st1.set_stock_entry_type()
st1.insert()
st1.submit()
+ st1.cancel()
frappe.set_user("Administrator")
remove_user_permission("Warehouse", "_Test Warehouse 1 - _TC", "test@example.com")
@@ -689,6 +691,8 @@
bom_no = frappe.db.get_value("BOM", {"item": "_Test Variant Item",
"is_default": 1, "docstatus": 1})
+ make_item_variant() # make variant of _Test Variant Item if absent
+
work_order = frappe.new_doc("Work Order")
work_order.update({
"company": "_Test Company",
@@ -1023,13 +1027,10 @@
# Check if FG cost is calculated based on RM total cost
# RM total cost = 200, FG rate = 200/4(FG qty) = 50
- self.assertEqual(se.items[1].basic_rate, 50)
+ self.assertEqual(se.items[1].basic_rate, flt(se.items[0].basic_rate/4))
self.assertEqual(se.value_difference, 0.0)
self.assertEqual(se.total_incoming_value, se.total_outgoing_value)
- # teardown
- se.delete()
-
@change_settings("Stock Settings", {"allow_negative_stock": 0})
def test_future_negative_sle(self):
# Initialize item, batch, warehouse, opening qty
@@ -1107,6 +1108,52 @@
posting_date='2021-09-02', # backdated consumption of 2nd batch
purpose='Material Issue')
+ def test_multi_batch_value_diff(self):
+ """ Test value difference on stock entry in case of multi-batch.
+ | Stock entry | batch | qty | rate | value diff on SE |
+ | --- | --- | --- | --- | --- |
+ | receipt | A | 1 | 10 | 30 |
+ | receipt | B | 1 | 20 | |
+ | issue | A | -1 | 10 | -30 (to assert after submit) |
+ | issue | B | -1 | 20 | |
+ """
+ from erpnext.stock.doctype.batch.test_batch import TestBatch
+
+ batch_nos = []
+
+ item_code = '_TestMultibatchFifo'
+ TestBatch.make_batch_item(item_code)
+ warehouse = '_Test Warehouse - _TC'
+ receipt = make_stock_entry(
+ item_code=item_code,
+ qty=1,
+ rate=10,
+ to_warehouse=warehouse,
+ purpose='Material Receipt',
+ do_not_save=True
+ )
+ receipt.append("items", frappe.copy_doc(receipt.items[0], ignore_no_copy=False).update({"basic_rate": 20}) )
+ receipt.save()
+ receipt.submit()
+ batch_nos.extend(row.batch_no for row in receipt.items)
+ self.assertEqual(receipt.value_difference, 30)
+
+ issue = make_stock_entry(
+ item_code=item_code,
+ qty=1,
+ from_warehouse=warehouse,
+ purpose='Material Issue',
+ do_not_save=True
+ )
+ issue.append("items", frappe.copy_doc(issue.items[0], ignore_no_copy=False))
+ for row, batch_no in zip(issue.items, batch_nos):
+ row.batch_no = batch_no
+ issue.save()
+ issue.submit()
+
+ issue.reload() # reload because reposting current voucher updates rate
+ self.assertEqual(issue.value_difference, -30)
+
def make_serialized_item(**args):
args = frappe._dict(args)
se = frappe.copy_doc(test_records[0])
diff --git a/erpnext/stock/doctype/stock_entry_detail/stock_entry_detail.json b/erpnext/stock/doctype/stock_entry_detail/stock_entry_detail.json
index df65706..83aed90 100644
--- a/erpnext/stock/doctype/stock_entry_detail/stock_entry_detail.json
+++ b/erpnext/stock/doctype/stock_entry_detail/stock_entry_detail.json
@@ -1,7 +1,7 @@
{
"actions": [],
"autoname": "hash",
- "creation": "2013-03-29 18:22:12",
+ "creation": "2022-02-05 00:17:49.860824",
"doctype": "DocType",
"document_type": "Other",
"editable_grid": 1,
@@ -340,13 +340,13 @@
"label": "More Information"
},
{
- "allow_on_submit": 1,
"default": "0",
"fieldname": "allow_zero_valuation_rate",
"fieldtype": "Check",
"label": "Allow Zero Valuation Rate",
"no_copy": 1,
- "print_hide": 1
+ "print_hide": 1,
+ "read_only_depends_on": "eval:doc.s_warehouse"
},
{
"allow_on_submit": 1,
@@ -556,12 +556,14 @@
"index_web_pages_for_search": 1,
"istable": 1,
"links": [],
- "modified": "2021-06-22 16:47:11.268975",
+ "modified": "2022-02-26 00:51:24.963653",
"modified_by": "Administrator",
"module": "Stock",
"name": "Stock Entry Detail",
+ "naming_rule": "Random",
"owner": "Administrator",
"permissions": [],
"sort_field": "modified",
- "sort_order": "ASC"
+ "sort_order": "ASC",
+ "states": []
}
\ No newline at end of file
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 a1030d5..684a8d4 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
@@ -1,8 +1,13 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
+import json
+from operator import itemgetter
+from uuid import uuid4
+
import frappe
from frappe.core.page.permission_manager.permission_manager import reset
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import add_days, today
from erpnext.stock.doctype.delivery_note.test_delivery_note import (
@@ -20,10 +25,9 @@
create_stock_reconciliation,
)
from erpnext.stock.stock_ledger import get_previous_sle
-from erpnext.tests.utils import ERPNextTestCase
-class TestStockLedgerEntry(ERPNextTestCase):
+class TestStockLedgerEntry(FrappeTestCase):
def setUp(self):
items = create_items()
reset('Stock Entry')
@@ -349,6 +353,392 @@
frappe.set_user("Administrator")
user.remove_roles("Stock Manager")
+ def test_batchwise_item_valuation_moving_average(self):
+ item, warehouses, batches = setup_item_valuation_test(valuation_method="Moving Average")
+
+ # Incoming Entries for Stock Value check
+ pr_entry_list = [
+ (item, warehouses[0], batches[0], 1, 100),
+ (item, warehouses[0], batches[1], 1, 50),
+ (item, warehouses[0], batches[0], 1, 150),
+ (item, warehouses[0], batches[1], 1, 100),
+ ]
+ prs = create_purchase_receipt_entries_for_batchwise_item_valuation_test(pr_entry_list)
+ sle_details = fetch_sle_details_for_doc_list(prs, ['stock_value'])
+ sv_list = [d['stock_value'] for d in sle_details]
+ expected_sv = [100, 150, 300, 400]
+ self.assertEqual(expected_sv, sv_list, "Incorrect 'Stock Value' values")
+
+ # Outgoing Entries for Stock Value Difference check
+ dn_entry_list = [
+ (item, warehouses[0], batches[1], 1, 200),
+ (item, warehouses[0], batches[0], 1, 200),
+ (item, warehouses[0], batches[1], 1, 200),
+ (item, warehouses[0], batches[0], 1, 200)
+ ]
+ dns = create_delivery_note_entries_for_batchwise_item_valuation_test(dn_entry_list)
+ sle_details = fetch_sle_details_for_doc_list(dns, ['stock_value_difference'])
+ svd_list = [-1 * d['stock_value_difference'] for d in sle_details]
+ expected_incoming_rates = expected_abs_svd = [75, 125, 75, 125]
+
+ self.assertEqual(expected_abs_svd, svd_list, "Incorrect 'Stock Value Difference' values")
+ for dn, incoming_rate in zip(dns, expected_incoming_rates):
+ self.assertEqual(
+ dn.items[0].incoming_rate, incoming_rate,
+ "Incorrect 'Incoming Rate' values fetched for DN items"
+ )
+
+
+ def assertSLEs(self, doc, expected_sles, sle_filters=None):
+ """ Compare sorted SLEs, useful for vouchers that create multiple SLEs for same line"""
+
+ filters = {"voucher_no": doc.name, "voucher_type": doc.doctype, "is_cancelled": 0}
+ if sle_filters:
+ filters.update(sle_filters)
+ sles = frappe.get_all("Stock Ledger Entry", fields=["*"], filters=filters,
+ order_by="timestamp(posting_date, posting_time), creation")
+
+ for exp_sle, act_sle in zip(expected_sles, sles):
+ for k, v in exp_sle.items():
+ act_value = act_sle[k]
+ if k == "stock_queue":
+ act_value = json.loads(act_value)
+ if act_value and act_value[0][0] == 0:
+ # ignore empty fifo bins
+ continue
+
+ self.assertEqual(v, act_value, msg=f"{k} doesn't match \n{exp_sle}\n{act_sle}")
+
+
+ def test_batchwise_item_valuation_stock_reco(self):
+ item, warehouses, batches = setup_item_valuation_test()
+ state = {
+ "stock_value" : 0.0,
+ "qty": 0.0
+ }
+ def update_invariants(exp_sles):
+ for sle in exp_sles:
+ state["stock_value"] += sle["stock_value_difference"]
+ state["qty"] += sle["actual_qty"]
+ sle["stock_value"] = state["stock_value"]
+ sle["qty_after_transaction"] = state["qty"]
+
+ osr1 = create_stock_reconciliation(warehouse=warehouses[0], item_code=item, qty=10, rate=100, batch_no=batches[1])
+ expected_sles = [
+ {"actual_qty": 10, "stock_value_difference": 1000},
+ ]
+ update_invariants(expected_sles)
+ self.assertSLEs(osr1, expected_sles)
+
+ osr2 = create_stock_reconciliation(warehouse=warehouses[0], item_code=item, qty=13, rate=200, batch_no=batches[0])
+ expected_sles = [
+ {"actual_qty": 13, "stock_value_difference": 200*13},
+ ]
+ update_invariants(expected_sles)
+ self.assertSLEs(osr2, expected_sles)
+
+ sr1 = create_stock_reconciliation(warehouse=warehouses[0], item_code=item, qty=5, rate=50, batch_no=batches[1])
+
+ expected_sles = [
+ {"actual_qty": -10, "stock_value_difference": -10 * 100},
+ {"actual_qty": 5, "stock_value_difference": 250}
+ ]
+ update_invariants(expected_sles)
+ self.assertSLEs(sr1, expected_sles)
+
+ sr2 = create_stock_reconciliation(warehouse=warehouses[0], item_code=item, qty=20, rate=75, batch_no=batches[0])
+ expected_sles = [
+ {"actual_qty": -13, "stock_value_difference": -13 * 200},
+ {"actual_qty": 20, "stock_value_difference": 20 * 75}
+ ]
+ update_invariants(expected_sles)
+ self.assertSLEs(sr2, expected_sles)
+
+ def test_batch_wise_valuation_across_warehouse(self):
+ item_code, warehouses, batches = setup_item_valuation_test()
+ source = warehouses[0]
+ target = warehouses[1]
+
+ unrelated_batch = make_stock_entry(item_code=item_code, target=source, batch_no=batches[1],
+ qty=5, rate=10)
+ self.assertSLEs(unrelated_batch, [
+ {"actual_qty": 5, "stock_value_difference": 10 * 5},
+ ])
+
+ reciept = make_stock_entry(item_code=item_code, target=source, batch_no=batches[0], qty=5, rate=10)
+ self.assertSLEs(reciept, [
+ {"actual_qty": 5, "stock_value_difference": 10 * 5},
+ ])
+
+ transfer = make_stock_entry(item_code=item_code, source=source, target=target, batch_no=batches[0], qty=5)
+ self.assertSLEs(transfer, [
+ {"actual_qty": -5, "stock_value_difference": -10 * 5, "warehouse": source},
+ {"actual_qty": 5, "stock_value_difference": 10 * 5, "warehouse": target}
+ ])
+
+ backdated_receipt = make_stock_entry(item_code=item_code, target=source, batch_no=batches[0],
+ qty=5, rate=20, posting_date=add_days(today(), -1))
+ self.assertSLEs(backdated_receipt, [
+ {"actual_qty": 5, "stock_value_difference": 20 * 5},
+ ])
+
+ # check reposted average rate in *future* transfer
+ self.assertSLEs(transfer, [
+ {"actual_qty": -5, "stock_value_difference": -15 * 5, "warehouse": source, "stock_value": 15 * 5 + 10 * 5},
+ {"actual_qty": 5, "stock_value_difference": 15 * 5, "warehouse": target, "stock_value": 15 * 5}
+ ])
+
+ transfer_unrelated = make_stock_entry(item_code=item_code, source=source,
+ target=target, batch_no=batches[1], qty=5)
+ self.assertSLEs(transfer_unrelated, [
+ {"actual_qty": -5, "stock_value_difference": -10 * 5, "warehouse": source, "stock_value": 15 * 5},
+ {"actual_qty": 5, "stock_value_difference": 10 * 5, "warehouse": target, "stock_value": 15 * 5 + 10 * 5}
+ ])
+
+ def test_intermediate_average_batch_wise_valuation(self):
+ """ A batch has moving average up until posting time,
+ check if same is respected when backdated entry is inserted in middle"""
+ item_code, warehouses, batches = setup_item_valuation_test()
+ warehouse = warehouses[0]
+
+ batch = batches[0]
+
+ yesterday = make_stock_entry(item_code=item_code, target=warehouse, batch_no=batch,
+ qty=1, rate=10, posting_date=add_days(today(), -1))
+ self.assertSLEs(yesterday, [
+ {"actual_qty": 1, "stock_value_difference": 10},
+ ])
+
+ tomorrow = make_stock_entry(item_code=item_code, target=warehouse, batch_no=batches[0],
+ qty=1, rate=30, posting_date=add_days(today(), 1))
+ self.assertSLEs(tomorrow, [
+ {"actual_qty": 1, "stock_value_difference": 30},
+ ])
+
+ create_today = make_stock_entry(item_code=item_code, target=warehouse, batch_no=batches[0],
+ qty=1, rate=20)
+ self.assertSLEs(create_today, [
+ {"actual_qty": 1, "stock_value_difference": 20},
+ ])
+
+ consume_today = make_stock_entry(item_code=item_code, source=warehouse, batch_no=batches[0],
+ qty=1)
+ self.assertSLEs(consume_today, [
+ {"actual_qty": -1, "stock_value_difference": -15},
+ ])
+
+ consume_tomorrow = make_stock_entry(item_code=item_code, source=warehouse, batch_no=batches[0],
+ qty=2, posting_date=add_days(today(), 2))
+ self.assertSLEs(consume_tomorrow, [
+ {"stock_value_difference": -(30 + 15), "stock_value": 0, "qty_after_transaction": 0},
+ ])
+
+ def test_legacy_item_valuation_stock_entry(self):
+ columns = [
+ 'stock_value_difference',
+ 'stock_value',
+ 'actual_qty',
+ 'qty_after_transaction',
+ 'stock_queue',
+ ]
+ item, warehouses, batches = setup_item_valuation_test(use_batchwise_valuation=0)
+
+ def check_sle_details_against_expected(sle_details, expected_sle_details, detail, columns):
+ for i, (sle_vals, ex_sle_vals) in enumerate(zip(sle_details, expected_sle_details)):
+ for col, sle_val, ex_sle_val in zip(columns, sle_vals, ex_sle_vals):
+ if col == 'stock_queue':
+ sle_val = get_stock_value_from_q(sle_val)
+ ex_sle_val = get_stock_value_from_q(ex_sle_val)
+ self.assertEqual(
+ sle_val, ex_sle_val,
+ f"Incorrect {col} value on transaction #: {i} in {detail}"
+ )
+
+ # List used to defer assertions to prevent commits cause of error skipped rollback
+ details_list = []
+
+
+ # Test Material Receipt Entries
+ se_entry_list_mr = [
+ (item, None, warehouses[0], batches[0], 1, 50, "2021-01-21"),
+ (item, None, warehouses[0], batches[1], 1, 100, "2021-01-23"),
+ ]
+ ses = create_stock_entry_entries_for_batchwise_item_valuation_test(
+ se_entry_list_mr, "Material Receipt"
+ )
+ sle_details = fetch_sle_details_for_doc_list(ses, columns=columns, as_dict=0)
+ expected_sle_details = [
+ (50.0, 50.0, 1.0, 1.0, '[[1.0, 50.0]]'),
+ (100.0, 150.0, 1.0, 2.0, '[[1.0, 50.0], [1.0, 100.0]]'),
+ ]
+ details_list.append((
+ sle_details, expected_sle_details,
+ "Material Receipt Entries", columns
+ ))
+
+
+ # Test Material Issue Entries
+ se_entry_list_mi = [
+ (item, warehouses[0], None, batches[1], 1, None, "2021-01-29"),
+ ]
+ ses = create_stock_entry_entries_for_batchwise_item_valuation_test(
+ se_entry_list_mi, "Material Issue"
+ )
+ sle_details = fetch_sle_details_for_doc_list(ses, columns=columns, as_dict=0)
+ expected_sle_details = [
+ (-50.0, 100.0, -1.0, 1.0, '[[1, 100.0]]')
+ ]
+ details_list.append((
+ sle_details, expected_sle_details,
+ "Material Issue Entries", columns
+ ))
+
+
+ # Run assertions
+ for details in details_list:
+ check_sle_details_against_expected(*details)
+
+ def test_mixed_valuation_batches_fifo(self):
+ item_code, warehouses, batches = setup_item_valuation_test(use_batchwise_valuation=0)
+ warehouse = warehouses[0]
+
+ state = {
+ "qty": 0.0,
+ "stock_value": 0.0
+ }
+ def update_invariants(exp_sles):
+ for sle in exp_sles:
+ state["stock_value"] += sle["stock_value_difference"]
+ state["qty"] += sle["actual_qty"]
+ sle["stock_value"] = state["stock_value"]
+ sle["qty_after_transaction"] = state["qty"]
+ return exp_sles
+
+ old1 = make_stock_entry(item_code=item_code, target=warehouse, batch_no=batches[0],
+ qty=10, rate=10)
+ self.assertSLEs(old1, update_invariants([
+ {"actual_qty": 10, "stock_value_difference": 10*10, "stock_queue": [[10, 10]]},
+ ]))
+ old2 = make_stock_entry(item_code=item_code, target=warehouse, batch_no=batches[1],
+ qty=10, rate=20)
+ self.assertSLEs(old2, update_invariants([
+ {"actual_qty": 10, "stock_value_difference": 10*20, "stock_queue": [[10, 10], [10, 20]]},
+ ]))
+ old3 = make_stock_entry(item_code=item_code, target=warehouse, batch_no=batches[0],
+ qty=5, rate=15)
+
+ self.assertSLEs(old3, update_invariants([
+ {"actual_qty": 5, "stock_value_difference": 5*15, "stock_queue": [[10, 10], [10, 20], [5, 15]]},
+ ]))
+
+ new1 = make_stock_entry(item_code=item_code, target=warehouse, qty=10, rate=40)
+ batches.append(new1.items[0].batch_no)
+ # assert old queue remains
+ self.assertSLEs(new1, update_invariants([
+ {"actual_qty": 10, "stock_value_difference": 10*40, "stock_queue": [[10, 10], [10, 20], [5, 15]]},
+ ]))
+
+ new2 = make_stock_entry(item_code=item_code, target=warehouse, qty=10, rate=42)
+ batches.append(new2.items[0].batch_no)
+ self.assertSLEs(new2, update_invariants([
+ {"actual_qty": 10, "stock_value_difference": 10*42, "stock_queue": [[10, 10], [10, 20], [5, 15]]},
+ ]))
+
+ # consume old batch as per FIFO
+ consume_old1 = make_stock_entry(item_code=item_code, source=warehouse, qty=15, batch_no=batches[0])
+ self.assertSLEs(consume_old1, update_invariants([
+ {"actual_qty": -15, "stock_value_difference": -10*10 - 5*20, "stock_queue": [[5, 20], [5, 15]]},
+ ]))
+
+ # consume new batch as per batch
+ consume_new2 = make_stock_entry(item_code=item_code, source=warehouse, qty=10, batch_no=batches[-1])
+ self.assertSLEs(consume_new2, update_invariants([
+ {"actual_qty": -10, "stock_value_difference": -10*42, "stock_queue": [[5, 20], [5, 15]]},
+ ]))
+
+ # finish all old batches
+ consume_old2 = make_stock_entry(item_code=item_code, source=warehouse, qty=10, batch_no=batches[1])
+ self.assertSLEs(consume_old2, update_invariants([
+ {"actual_qty": -10, "stock_value_difference": -5*20 - 5*15, "stock_queue": []},
+ ]))
+
+ # finish all new batches
+ consume_new1 = make_stock_entry(item_code=item_code, source=warehouse, qty=10, batch_no=batches[-2])
+ self.assertSLEs(consume_new1, update_invariants([
+ {"actual_qty": -10, "stock_value_difference": -10*40, "stock_queue": []},
+ ]))
+
+ def test_fifo_dependent_consumption(self):
+ item = make_item("_TestFifoTransferRates")
+ source = "_Test Warehouse - _TC"
+ target = "Stores - _TC"
+
+ rates = [10 * i for i in range(1, 20)]
+
+ receipt = make_stock_entry(item_code=item.name, target=source, qty=10, do_not_save=True, rate=10)
+ for rate in rates[1:]:
+ row = frappe.copy_doc(receipt.items[0], ignore_no_copy=False)
+ row.basic_rate = rate
+ receipt.append("items", row)
+
+ receipt.save()
+ receipt.submit()
+
+ expected_queues = []
+ for idx, rate in enumerate(rates, start=1):
+ expected_queues.append(
+ {"stock_queue": [[10, 10 * i] for i in range(1, idx + 1)]}
+ )
+ self.assertSLEs(receipt, expected_queues)
+
+ transfer = make_stock_entry(item_code=item.name, source=source, target=target, qty=10, do_not_save=True, rate=10)
+ for rate in rates[1:]:
+ row = frappe.copy_doc(transfer.items[0], ignore_no_copy=False)
+ transfer.append("items", row)
+
+ transfer.save()
+ transfer.submit()
+
+ # same exact queue should be transferred
+ self.assertSLEs(transfer, expected_queues, sle_filters={"warehouse": target})
+
+ def test_fifo_multi_item_repack_consumption(self):
+ rm = make_item("_TestFifoRepackRM")
+ packed = make_item("_TestFifoRepackFinished")
+ warehouse = "_Test Warehouse - _TC"
+
+ rates = [10 * i for i in range(1, 5)]
+
+ receipt = make_stock_entry(item_code=rm.name, target=warehouse, qty=10, do_not_save=True, rate=10)
+ for rate in rates[1:]:
+ row = frappe.copy_doc(receipt.items[0], ignore_no_copy=False)
+ row.basic_rate = rate
+ receipt.append("items", row)
+
+ receipt.save()
+ receipt.submit()
+
+ repack = make_stock_entry(item_code=rm.name, source=warehouse, qty=10,
+ do_not_save=True, rate=10, purpose="Repack")
+ for rate in rates[1:]:
+ row = frappe.copy_doc(repack.items[0], ignore_no_copy=False)
+ repack.append("items", row)
+
+ repack.append("items", {
+ "item_code": packed.name,
+ "t_warehouse": warehouse,
+ "qty": 1,
+ "transfer_qty": 1,
+ })
+
+ repack.save()
+ repack.submit()
+
+ # same exact queue should be transferred
+ self.assertSLEs(repack, [
+ {"incoming_rate": sum(rates) * 10}
+ ], sle_filters={"item_code": packed.name})
+
def create_repack_entry(**args):
args = frappe._dict(args)
@@ -412,3 +802,118 @@
make_item(d, properties=properties)
return items
+
+def setup_item_valuation_test(valuation_method="FIFO", suffix=None, use_batchwise_valuation=1, batches_list=['X', 'Y']):
+ from erpnext.stock.doctype.batch.batch import make_batch
+ from erpnext.stock.doctype.item.test_item import make_item
+ from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
+
+ if not suffix:
+ suffix = get_unique_suffix()
+
+ item = make_item(
+ f"IV - Test Item {valuation_method} {suffix}",
+ dict(valuation_method=valuation_method, has_batch_no=1, create_new_batch=1)
+ )
+ warehouses = [create_warehouse(f"IV - Test Warehouse {i}") for i in ['J', 'K']]
+ batches = [f"IV - Test Batch {i} {valuation_method} {suffix}" for i in batches_list]
+
+ for i, batch_id in enumerate(batches):
+ if not frappe.db.exists("Batch", batch_id):
+ ubw = use_batchwise_valuation
+ if isinstance(use_batchwise_valuation, (list, tuple)):
+ ubw = use_batchwise_valuation[i]
+ batch = frappe.get_doc(frappe._dict(
+ doctype="Batch",
+ batch_id=batch_id,
+ item=item.item_code,
+ use_batchwise_valuation=ubw
+ )
+ ).insert()
+ batch.use_batchwise_valuation = ubw
+ batch.db_update()
+
+ return item.item_code, warehouses, batches
+
+def create_purchase_receipt_entries_for_batchwise_item_valuation_test(pr_entry_list):
+ from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import make_purchase_receipt
+ prs = []
+
+ for item, warehouse, batch_no, qty, rate in pr_entry_list:
+ pr = make_purchase_receipt(item=item, warehouse=warehouse, qty=qty, rate=rate, batch_no=batch_no)
+ prs.append(pr)
+
+ return prs
+
+def create_delivery_note_entries_for_batchwise_item_valuation_test(dn_entry_list):
+ from erpnext.selling.doctype.sales_order.sales_order import make_delivery_note
+ from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
+ dns = []
+ for item, warehouse, batch_no, qty, rate in dn_entry_list:
+ so = make_sales_order(
+ rate=rate,
+ qty=qty,
+ item=item,
+ warehouse=warehouse,
+ against_blanket_order=0
+ )
+
+ dn = make_delivery_note(so.name)
+ dn.items[0].batch_no = batch_no
+ dn.insert()
+ dn.submit()
+ dns.append(dn)
+ return dns
+
+def fetch_sle_details_for_doc_list(doc_list, columns, as_dict=1):
+ return frappe.db.sql(f"""
+ SELECT { ', '.join(columns)}
+ FROM `tabStock Ledger Entry`
+ WHERE
+ voucher_no IN %(voucher_nos)s
+ and docstatus = 1
+ ORDER BY timestamp(posting_date, posting_time) ASC, CREATION ASC
+ """, dict(
+ voucher_nos=[doc.name for doc in doc_list]
+ ), as_dict=as_dict)
+
+def get_stock_value_from_q(q):
+ return sum(r*q for r,q in json.loads(q))
+
+def create_stock_entry_entries_for_batchwise_item_valuation_test(se_entry_list, purpose):
+ ses = []
+ for item, source, target, batch, qty, rate, posting_date in se_entry_list:
+ args = dict(
+ item_code=item,
+ qty=qty,
+ company="_Test Company",
+ batch_no=batch,
+ posting_date=posting_date,
+ purpose=purpose
+ )
+
+ if purpose == "Material Receipt":
+ args.update(
+ dict(to_warehouse=target, rate=rate)
+ )
+
+ elif purpose == "Material Issue":
+ args.update(
+ dict(from_warehouse=source)
+ )
+
+ elif purpose == "Material Transfer":
+ args.update(
+ dict(from_warehouse=source, to_warehouse=target)
+ )
+
+ else:
+ raise ValueError(f"Invalid purpose: {purpose}")
+ ses.append(make_stock_entry(**args))
+
+ return ses
+
+def get_unique_suffix():
+ # Used to isolate valuation sensitive
+ # tests to prevent future tests from failing.
+ return str(uuid4())[:8].upper()
diff --git a/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.json b/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.json
index 3402972..a882a61 100644
--- a/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.json
+++ b/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.json
@@ -18,7 +18,6 @@
"items",
"section_break_9",
"expense_account",
- "reconciliation_json",
"column_break_13",
"difference_amount",
"amended_from",
@@ -112,15 +111,6 @@
"options": "Cost Center"
},
{
- "fieldname": "reconciliation_json",
- "fieldtype": "Long Text",
- "hidden": 1,
- "label": "Reconciliation JSON",
- "no_copy": 1,
- "print_hide": 1,
- "read_only": 1
- },
- {
"fieldname": "column_break_13",
"fieldtype": "Column Break"
},
@@ -155,7 +145,7 @@
"idx": 1,
"is_submittable": 1,
"links": [],
- "modified": "2021-11-30 01:33:51.437194",
+ "modified": "2022-02-06 14:28:19.043905",
"modified_by": "Administrator",
"module": "Stock",
"name": "Stock Reconciliation",
@@ -178,5 +168,6 @@
"search_fields": "posting_date",
"show_name_in_global_search": 1,
"sort_field": "modified",
- "sort_order": "DESC"
+ "sort_order": "DESC",
+ "states": []
}
\ No newline at end of file
diff --git a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
index 428370c..e6b252e 100644
--- a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
+++ b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
@@ -6,6 +6,7 @@
import frappe
+from frappe.tests.utils import FrappeTestCase, change_settings
from frappe.utils import add_days, cstr, flt, nowdate, nowtime, random_string
from erpnext.accounts.utils import get_stock_and_account_balance
@@ -19,14 +20,13 @@
from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
from erpnext.stock.stock_ledger import get_previous_sle, update_entries_after
from erpnext.stock.utils import get_incoming_rate, get_stock_value_on, get_valuation_method
-from erpnext.tests.utils import ERPNextTestCase, change_settings
-class TestStockReconciliation(ERPNextTestCase):
+class TestStockReconciliation(FrappeTestCase):
@classmethod
def setUpClass(cls):
- super().setUpClass()
create_batch_or_serial_no_items()
+ super().setUpClass()
frappe.db.set_value("Stock Settings", None, "allow_negative_stock", 1)
def tearDown(self):
@@ -200,7 +200,6 @@
def test_stock_reco_for_batch_item(self):
to_delete_records = []
- to_delete_serial_nos = []
# Add new serial nos
item_code = "Stock-Reco-batch-Item-1"
@@ -208,20 +207,22 @@
sr = create_stock_reconciliation(item_code=item_code,
warehouse = warehouse, qty=5, rate=200, do_not_submit=1)
- sr.save(ignore_permissions=True)
+ sr.save()
sr.submit()
- self.assertTrue(sr.items[0].batch_no)
+ batch_no = sr.items[0].batch_no
+ self.assertTrue(batch_no)
to_delete_records.append(sr.name)
sr1 = create_stock_reconciliation(item_code=item_code,
- warehouse = warehouse, qty=6, rate=300, batch_no=sr.items[0].batch_no)
+ warehouse = warehouse, qty=6, rate=300, batch_no=batch_no)
args = {
"item_code": item_code,
"warehouse": warehouse,
"posting_date": nowdate(),
"posting_time": nowtime(),
+ "batch_no": batch_no,
}
valuation_rate = get_incoming_rate(args)
@@ -230,7 +231,7 @@
sr2 = create_stock_reconciliation(item_code=item_code,
- warehouse = warehouse, qty=0, rate=0, batch_no=sr.items[0].batch_no)
+ warehouse = warehouse, qty=0, rate=0, batch_no=batch_no)
stock_value = get_stock_value_on(warehouse, nowdate(), item_code)
self.assertEqual(stock_value, 0)
diff --git a/erpnext/stock/doctype/stock_settings/stock_settings.json b/erpnext/stock/doctype/stock_settings/stock_settings.json
index 438ec16..ec7fb0f 100644
--- a/erpnext/stock/doctype/stock_settings/stock_settings.json
+++ b/erpnext/stock/doctype/stock_settings/stock_settings.json
@@ -99,7 +99,7 @@
"fieldname": "valuation_method",
"fieldtype": "Select",
"label": "Default Valuation Method",
- "options": "FIFO\nMoving Average"
+ "options": "FIFO\nMoving Average\nLIFO"
},
{
"description": "The percentage you are allowed to receive or deliver more against the quantity ordered. For example, if you have ordered 100 units, and your Allowance is 10%, then you are allowed to receive 110 units.",
@@ -346,7 +346,7 @@
"index_web_pages_for_search": 1,
"issingle": 1,
"links": [],
- "modified": "2022-02-04 15:33:43.692736",
+ "modified": "2022-02-05 15:33:43.692736",
"modified_by": "Administrator",
"module": "Stock",
"name": "Stock Settings",
diff --git a/erpnext/stock/doctype/stock_settings/test_stock_settings.py b/erpnext/stock/doctype/stock_settings/test_stock_settings.py
index 072b54b..1349671 100644
--- a/erpnext/stock/doctype/stock_settings/test_stock_settings.py
+++ b/erpnext/stock/doctype/stock_settings/test_stock_settings.py
@@ -4,11 +4,10 @@
import unittest
import frappe
-
-from erpnext.tests.utils import ERPNextTestCase
+from frappe.tests.utils import FrappeTestCase
-class TestStockSettings(ERPNextTestCase):
+class TestStockSettings(FrappeTestCase):
def setUp(self):
super().setUp()
frappe.db.set_value("Stock Settings", None, "clean_description_html", 0)
diff --git a/erpnext/stock/doctype/warehouse/test_warehouse.py b/erpnext/stock/doctype/warehouse/test_warehouse.py
index 26db264..cdb7719 100644
--- a/erpnext/stock/doctype/warehouse/test_warehouse.py
+++ b/erpnext/stock/doctype/warehouse/test_warehouse.py
@@ -3,17 +3,17 @@
import frappe
from frappe.test_runner import make_test_records
+from frappe.tests.utils import FrappeTestCase
from frappe.utils import cint
import erpnext
from erpnext.accounts.doctype.account.test_account import create_account, get_inventory_account
from erpnext.stock.doctype.item.test_item import create_item
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
-from erpnext.tests.utils import ERPNextTestCase
test_records = frappe.get_test_records('Warehouse')
-class TestWarehouse(ERPNextTestCase):
+class TestWarehouse(FrappeTestCase):
def setUp(self):
super().setUp()
if not frappe.get_value('Item', '_Test Item'):
diff --git a/erpnext/stock/doctype/warehouse/warehouse.json b/erpnext/stock/doctype/warehouse/warehouse.json
index 05076b5..c695d54 100644
--- a/erpnext/stock/doctype/warehouse/warehouse.json
+++ b/erpnext/stock/doctype/warehouse/warehouse.json
@@ -244,7 +244,7 @@
"idx": 1,
"is_tree": 1,
"links": [],
- "modified": "2021-12-03 04:40:06.414630",
+ "modified": "2022-03-01 02:37:48.034944",
"modified_by": "Administrator",
"module": "Stock",
"name": "Warehouse",
@@ -301,5 +301,7 @@
"show_name_in_global_search": 1,
"sort_field": "modified",
"sort_order": "DESC",
- "title_field": "warehouse_name"
+ "states": [],
+ "title_field": "warehouse_name",
+ "track_changes": 1
}
\ No newline at end of file
diff --git a/erpnext/stock/get_item_details.py b/erpnext/stock/get_item_details.py
index 06f8fa7..9bb41b9 100644
--- a/erpnext/stock/get_item_details.py
+++ b/erpnext/stock/get_item_details.py
@@ -6,6 +6,7 @@
import frappe
from frappe import _, throw
+from frappe.model import child_table_fields, default_fields
from frappe.model.meta import get_field_precision
from frappe.utils import add_days, add_months, cint, cstr, flt, getdate
@@ -119,8 +120,15 @@
out.rate = args.rate or out.price_list_rate
out.amount = flt(args.qty) * flt(out.rate)
+ out = remove_standard_fields(out)
return out
+def remove_standard_fields(details):
+ for key in child_table_fields + default_fields:
+ details.pop(key, None)
+ return details
+
+
def update_stock(args, out):
if (args.get("doctype") == "Delivery Note" or
(args.get("doctype") == "Sales Invoice" and args.get('update_stock'))) \
@@ -343,6 +351,7 @@
args.conversion_factor = out.conversion_factor
out.stock_qty = out.qty * out.conversion_factor
+ args.stock_qty = out.stock_qty
# calculate last purchase rate
if args.get('doctype') in purchase_doctypes:
@@ -358,7 +367,7 @@
if not out[d[1]]:
out[d[1]] = frappe.get_cached_value('Company', args.company, d[2]) if d[2] else None
- for fieldname in ("item_name", "item_group", "barcodes", "brand", "stock_uom"):
+ for fieldname in ("item_name", "item_group", "brand", "stock_uom"):
out[fieldname] = item.get(fieldname)
if args.get("manufacturer"):
diff --git a/erpnext/stock/report/stock_ageing/stock_ageing.py b/erpnext/stock/report/stock_ageing/stock_ageing.py
index e6dfc97..97a740e 100644
--- a/erpnext/stock/report/stock_ageing/stock_ageing.py
+++ b/erpnext/stock/report/stock_ageing/stock_ageing.py
@@ -12,6 +12,7 @@
from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Filters = frappe._dict
+precision = cint(frappe.db.get_single_value("System Settings", "float_precision"))
def execute(filters: Filters = None) -> Tuple:
to_date = filters["to_date"]
@@ -48,10 +49,13 @@
if filters.get("show_warehouse_wise_stock"):
row.append(details.warehouse)
- row.extend([item_dict.get("total_qty"), average_age,
+ row.extend([
+ flt(item_dict.get("total_qty"), precision),
+ average_age,
range1, range2, range3, above_range3,
earliest_age, latest_age,
- details.stock_uom])
+ details.stock_uom
+ ])
data.append(row)
@@ -79,13 +83,13 @@
qty = flt(item[0]) if not item_dict["has_serial_no"] else 1.0
if age <= filters.range1:
- range1 += qty
+ range1 = flt(range1 + qty, precision)
elif age <= filters.range2:
- range2 += qty
+ range2 = flt(range2 + qty, precision)
elif age <= filters.range3:
- range3 += qty
+ range3 = flt(range3 + qty, precision)
else:
- above_range3 += qty
+ above_range3 = flt(above_range3 + qty, precision)
return range1, range2, range3, above_range3
@@ -252,6 +256,7 @@
key, fifo_queue, transferred_item_key = self.__init_key_stores(d)
if d.voucher_type == "Stock Reconciliation":
+ # get difference in qty shift as actual qty
prev_balance_qty = self.item_details[key].get("qty_after_transaction", 0)
d.actual_qty = flt(d.qty_after_transaction) - flt(prev_balance_qty)
@@ -264,12 +269,16 @@
self.__update_balances(d, key)
+ if not self.filters.get("show_warehouse_wise_stock"):
+ # (Item 1, WH 1), (Item 1, WH 2) => (Item 1)
+ self.item_details = self.__aggregate_details_by_item(self.item_details)
+
return self.item_details
def __init_key_stores(self, row: Dict) -> Tuple:
"Initialise keys and FIFO Queue."
- key = (row.name, row.warehouse) if self.filters.get('show_warehouse_wise_stock') else row.name
+ key = (row.name, row.warehouse)
self.item_details.setdefault(key, {"details": row, "fifo_queue": []})
fifo_queue = self.item_details[key]["fifo_queue"]
@@ -281,14 +290,16 @@
def __compute_incoming_stock(self, row: Dict, fifo_queue: List, transfer_key: Tuple, serial_nos: List):
"Update FIFO Queue on inward stock."
- if self.transferred_item_details.get(transfer_key):
+ transfer_data = self.transferred_item_details.get(transfer_key)
+ if transfer_data:
# inward/outward from same voucher, item & warehouse
- slot = self.transferred_item_details[transfer_key].pop(0)
- fifo_queue.append(slot)
+ # eg: Repack with same item, Stock reco for batch item
+ # consume transfer data and add stock to fifo queue
+ self.__adjust_incoming_transfer_qty(transfer_data, fifo_queue, row)
else:
if not serial_nos:
- if fifo_queue and flt(fifo_queue[0][0]) < 0:
- # neutralize negative stock by adding positive stock
+ if fifo_queue and flt(fifo_queue[0][0]) <= 0:
+ # neutralize 0/negative stock by adding positive stock
fifo_queue[0][0] += flt(row.actual_qty)
fifo_queue[0][1] = row.posting_date
else:
@@ -319,7 +330,7 @@
elif not fifo_queue:
# negative stock, no balance but qty yet to consume
fifo_queue.append([-(qty_to_pop), row.posting_date])
- self.transferred_item_details[transfer_key].append([row.actual_qty, row.posting_date])
+ self.transferred_item_details[transfer_key].append([qty_to_pop, row.posting_date])
qty_to_pop = 0
else:
# qty to pop < slot qty, ample balance
@@ -328,6 +339,33 @@
self.transferred_item_details[transfer_key].append([qty_to_pop, slot[1]])
qty_to_pop = 0
+ def __adjust_incoming_transfer_qty(self, transfer_data: Dict, fifo_queue: List, row: Dict):
+ "Add previously removed stock back to FIFO Queue."
+ transfer_qty_to_pop = flt(row.actual_qty)
+
+ def add_to_fifo_queue(slot):
+ if fifo_queue and flt(fifo_queue[0][0]) <= 0:
+ # neutralize 0/negative stock by adding positive stock
+ fifo_queue[0][0] += flt(slot[0])
+ fifo_queue[0][1] = slot[1]
+ else:
+ fifo_queue.append(slot)
+
+ while transfer_qty_to_pop:
+ if transfer_data and 0 < transfer_data[0][0] <= transfer_qty_to_pop:
+ # bucket qty is not enough, consume whole
+ transfer_qty_to_pop -= transfer_data[0][0]
+ add_to_fifo_queue(transfer_data.pop(0))
+ elif not transfer_data:
+ # transfer bucket is empty, extra incoming qty
+ add_to_fifo_queue([transfer_qty_to_pop, row.posting_date])
+ transfer_qty_to_pop = 0
+ else:
+ # ample bucket qty to consume
+ transfer_data[0][0] -= transfer_qty_to_pop
+ add_to_fifo_queue([transfer_qty_to_pop, transfer_data[0][1]])
+ transfer_qty_to_pop = 0
+
def __update_balances(self, row: Dict, key: Union[Tuple, str]):
self.item_details[key]["qty_after_transaction"] = row.qty_after_transaction
@@ -338,6 +376,27 @@
self.item_details[key]["has_serial_no"] = row.has_serial_no
+ def __aggregate_details_by_item(self, wh_wise_data: Dict) -> Dict:
+ "Aggregate Item-Wh wise data into single Item entry."
+ item_aggregated_data = {}
+ for key,row in wh_wise_data.items():
+ item = key[0]
+ if not item_aggregated_data.get(item):
+ item_aggregated_data.setdefault(item, {
+ "details": frappe._dict(),
+ "fifo_queue": [],
+ "qty_after_transaction": 0.0,
+ "total_qty": 0.0
+ })
+ item_row = item_aggregated_data.get(item)
+ item_row["details"].update(row["details"])
+ item_row["fifo_queue"].extend(row["fifo_queue"])
+ item_row["qty_after_transaction"] += flt(row["qty_after_transaction"])
+ item_row["total_qty"] += flt(row["total_qty"])
+ item_row["has_serial_no"] = row["has_serial_no"]
+
+ return item_aggregated_data
+
def __get_stock_ledger_entries(self) -> List[Dict]:
sle = frappe.qb.DocType("Stock Ledger Entry")
item = self.__get_item_query() # used as derived table in sle query
diff --git a/erpnext/stock/report/stock_ageing/stock_ageing_fifo_logic.md b/erpnext/stock/report/stock_ageing/stock_ageing_fifo_logic.md
index 5ffe97f..3d759dd 100644
--- a/erpnext/stock/report/stock_ageing/stock_ageing_fifo_logic.md
+++ b/erpnext/stock/report/stock_ageing/stock_ageing_fifo_logic.md
@@ -15,6 +15,7 @@
50 qty is (today-the 1st) days old
20 qty is (today-the 2nd) days old
+> Note: We generate FIFO slots warehouse wise as stock reconciliations from different warehouses can cause incorrect values.
### Calculation of FIFO Slots
#### Case 1: Outward from sufficient balance qty
@@ -70,4 +71,39 @@
2nd | -60 | [[-10, 1-12-2021]]
3rd | +5 | [[-5, 3-12-2021]]
4th | +10 | [[5, 4-12-2021]]
-4th | +20 | [[5, 4-12-2021], [20, 4-12-2021]]
\ No newline at end of file
+4th | +20 | [[5, 4-12-2021], [20, 4-12-2021]]
+
+### Concept of Transfer Qty Bucket
+In the case of **Repack**, Quantity that comes in, isn't really incoming. It is just new stock repurposed from old stock, due to incoming-outgoing of the same warehouse.
+
+Here, stock is consumed from the FIFO Queue. It is then re-added back to the queue.
+While adding stock back to the queue we need to know how much to add.
+For this we need to keep track of how much was previously consumed.
+Hence we use **Transfer Qty Bucket**.
+
+While re-adding stock, we try to add buckets that were consumed earlier (date intact), to maintain correctness.
+
+#### Case 1: Same Item-Warehouse in Repack
+Eg:
+-------------------------------------------------------------------------------------
+Date | Qty | Voucher | FIFO Queue | Transfer Qty Buckets
+-------------------------------------------------------------------------------------
+1st | +500 | PR | [[500, 1-12-2021]] |
+2nd | -50 | Repack | [[450, 1-12-2021]] | [[50, 1-12-2021]]
+2nd | +50 | Repack | [[450, 1-12-2021], [50, 1-12-2021]] | []
+
+- The balance at the end is restored back to 500
+- However, the initial 500 qty bucket is now split into 450 and 50, with the same date
+- The net effect is the same as that before the Repack
+
+#### Case 2: Same Item-Warehouse in Repack with Split Consumption rows
+Eg:
+-------------------------------------------------------------------------------------
+Date | Qty | Voucher | FIFO Queue | Transfer Qty Buckets
+-------------------------------------------------------------------------------------
+1st | +500 | PR | [[500, 1-12-2021]] |
+2nd | -50 | Repack | [[450, 1-12-2021]] | [[50, 1-12-2021]]
+2nd | -50 | Repack | [[400, 1-12-2021]] | [[50, 1-12-2021],
+- | | | |[50, 1-12-2021]]
+2nd | +100 | Repack | [[400, 1-12-2021], [50, 1-12-2021], | []
+- | | | [50, 1-12-2021]] |
diff --git a/erpnext/stock/report/stock_ageing/test_stock_ageing.py b/erpnext/stock/report/stock_ageing/test_stock_ageing.py
index 949bb7c..ca963b7 100644
--- a/erpnext/stock/report/stock_ageing/test_stock_ageing.py
+++ b/erpnext/stock/report/stock_ageing/test_stock_ageing.py
@@ -1,25 +1,27 @@
-# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
+# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import frappe
+from frappe.tests.utils import FrappeTestCase
-from erpnext.stock.report.stock_ageing.stock_ageing import FIFOSlots
-from erpnext.tests.utils import ERPNextTestCase
+from erpnext.stock.report.stock_ageing.stock_ageing import FIFOSlots, format_report_data
-class TestStockAgeing(ERPNextTestCase):
+class TestStockAgeing(FrappeTestCase):
def setUp(self) -> None:
self.filters = frappe._dict(
company="_Test Company",
- to_date="2021-12-10"
+ to_date="2021-12-10",
+ range1=30, range2=60, range3=90
)
def test_normal_inward_outward_queue(self):
- "Reference: Case 1 in stock_ageing_fifo_logic.md"
+ "Reference: Case 1 in stock_ageing_fifo_logic.md (same wh)"
sle = [
frappe._dict(
name="Flask Item",
actual_qty=30, qty_after_transaction=30,
+ warehouse="WH 1",
posting_date="2021-12-01", voucher_type="Stock Entry",
voucher_no="001",
has_serial_no=False, serial_no=None
@@ -27,6 +29,7 @@
frappe._dict(
name="Flask Item",
actual_qty=20, qty_after_transaction=50,
+ warehouse="WH 1",
posting_date="2021-12-02", voucher_type="Stock Entry",
voucher_no="002",
has_serial_no=False, serial_no=None
@@ -34,6 +37,7 @@
frappe._dict(
name="Flask Item",
actual_qty=(-10), qty_after_transaction=40,
+ warehouse="WH 1",
posting_date="2021-12-03", voucher_type="Stock Entry",
voucher_no="003",
has_serial_no=False, serial_no=None
@@ -50,11 +54,12 @@
self.assertEqual(queue[0][0], 20.0)
def test_insufficient_balance(self):
- "Reference: Case 3 in stock_ageing_fifo_logic.md"
+ "Reference: Case 3 in stock_ageing_fifo_logic.md (same wh)"
sle = [
frappe._dict(
name="Flask Item",
actual_qty=(-30), qty_after_transaction=(-30),
+ warehouse="WH 1",
posting_date="2021-12-01", voucher_type="Stock Entry",
voucher_no="001",
has_serial_no=False, serial_no=None
@@ -62,6 +67,7 @@
frappe._dict(
name="Flask Item",
actual_qty=20, qty_after_transaction=(-10),
+ warehouse="WH 1",
posting_date="2021-12-02", voucher_type="Stock Entry",
voucher_no="002",
has_serial_no=False, serial_no=None
@@ -69,6 +75,7 @@
frappe._dict(
name="Flask Item",
actual_qty=20, qty_after_transaction=10,
+ warehouse="WH 1",
posting_date="2021-12-03", voucher_type="Stock Entry",
voucher_no="003",
has_serial_no=False, serial_no=None
@@ -76,6 +83,7 @@
frappe._dict(
name="Flask Item",
actual_qty=10, qty_after_transaction=20,
+ warehouse="WH 1",
posting_date="2021-12-03", voucher_type="Stock Entry",
voucher_no="004",
has_serial_no=False, serial_no=None
@@ -91,11 +99,16 @@
self.assertEqual(queue[0][0], 10.0)
self.assertEqual(queue[1][0], 10.0)
- def test_stock_reconciliation(self):
+ def test_basic_stock_reconciliation(self):
+ """
+ Ledger (same wh): [+30, reco reset >> 50, -10]
+ Bal: 40
+ """
sle = [
frappe._dict(
name="Flask Item",
actual_qty=30, qty_after_transaction=30,
+ warehouse="WH 1",
posting_date="2021-12-01", voucher_type="Stock Entry",
voucher_no="001",
has_serial_no=False, serial_no=None
@@ -103,6 +116,7 @@
frappe._dict(
name="Flask Item",
actual_qty=0, qty_after_transaction=50,
+ warehouse="WH 1",
posting_date="2021-12-02", voucher_type="Stock Reconciliation",
voucher_no="002",
has_serial_no=False, serial_no=None
@@ -110,6 +124,7 @@
frappe._dict(
name="Flask Item",
actual_qty=(-10), qty_after_transaction=40,
+ warehouse="WH 1",
posting_date="2021-12-03", voucher_type="Stock Entry",
voucher_no="003",
has_serial_no=False, serial_no=None
@@ -122,5 +137,477 @@
queue = result["fifo_queue"]
self.assertEqual(result["qty_after_transaction"], result["total_qty"])
+ self.assertEqual(result["total_qty"], 40.0)
self.assertEqual(queue[0][0], 20.0)
self.assertEqual(queue[1][0], 20.0)
+
+ def test_sequential_stock_reco_same_warehouse(self):
+ """
+ Test back to back stock recos (same warehouse).
+ Ledger: [reco opening >> +1000, reco reset >> 400, -10]
+ Bal: 390
+ """
+ sle = [
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=0, qty_after_transaction=1000,
+ warehouse="WH 1",
+ posting_date="2021-12-01", voucher_type="Stock Reconciliation",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=0, qty_after_transaction=400,
+ warehouse="WH 1",
+ posting_date="2021-12-02", voucher_type="Stock Reconciliation",
+ voucher_no="003",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=(-10), qty_after_transaction=390,
+ warehouse="WH 1",
+ posting_date="2021-12-03", voucher_type="Stock Entry",
+ voucher_no="003",
+ has_serial_no=False, serial_no=None
+ )
+ ]
+ slots = FIFOSlots(self.filters, sle).generate()
+
+ result = slots["Flask Item"]
+ queue = result["fifo_queue"]
+
+ self.assertEqual(result["qty_after_transaction"], result["total_qty"])
+ self.assertEqual(result["total_qty"], 390.0)
+ self.assertEqual(queue[0][0], 390.0)
+
+ def test_sequential_stock_reco_different_warehouse(self):
+ """
+ Ledger:
+ WH | Voucher | Qty
+ -------------------
+ WH1 | Reco | 1000
+ WH2 | Reco | 400
+ WH1 | SE | -10
+
+ Bal: WH1 bal + WH2 bal = 990 + 400 = 1390
+ """
+ sle = [
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=0, qty_after_transaction=1000,
+ warehouse="WH 1",
+ posting_date="2021-12-01", voucher_type="Stock Reconciliation",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=0, qty_after_transaction=400,
+ warehouse="WH 2",
+ posting_date="2021-12-02", voucher_type="Stock Reconciliation",
+ voucher_no="003",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=(-10), qty_after_transaction=990,
+ warehouse="WH 1",
+ posting_date="2021-12-03", voucher_type="Stock Entry",
+ voucher_no="004",
+ has_serial_no=False, serial_no=None
+ )
+ ]
+
+ item_wise_slots, item_wh_wise_slots = generate_item_and_item_wh_wise_slots(
+ filters=self.filters,sle=sle
+ )
+
+ # test without 'show_warehouse_wise_stock'
+ item_result = item_wise_slots["Flask Item"]
+ queue = item_result["fifo_queue"]
+
+ self.assertEqual(item_result["qty_after_transaction"], item_result["total_qty"])
+ self.assertEqual(item_result["total_qty"], 1390.0)
+ self.assertEqual(queue[0][0], 990.0)
+ self.assertEqual(queue[1][0], 400.0)
+
+ # test with 'show_warehouse_wise_stock' checked
+ item_wh_balances = [item_wh_wise_slots.get(i).get("qty_after_transaction") for i in item_wh_wise_slots]
+ self.assertEqual(sum(item_wh_balances), item_result["qty_after_transaction"])
+
+ def test_repack_entry_same_item_split_rows(self):
+ """
+ Split consumption rows and have single repacked item row (same warehouse).
+ Ledger:
+ Item | Qty | Voucher
+ ------------------------
+ Item 1 | 500 | 001
+ Item 1 | -50 | 002 (repack)
+ Item 1 | -50 | 002 (repack)
+ Item 1 | 100 | 002 (repack)
+
+ Case most likely for batch items. Test time bucket computation.
+ """
+ sle = [
+ frappe._dict( # stock up item
+ name="Flask Item",
+ actual_qty=500, qty_after_transaction=500,
+ warehouse="WH 1",
+ posting_date="2021-12-03", voucher_type="Stock Entry",
+ voucher_no="001",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=(-50), qty_after_transaction=450,
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=(-50), qty_after_transaction=400,
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=100, qty_after_transaction=500,
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ ]
+ slots = FIFOSlots(self.filters, sle).generate()
+ item_result = slots["Flask Item"]
+ queue = item_result["fifo_queue"]
+
+ self.assertEqual(item_result["total_qty"], 500.0)
+ self.assertEqual(queue[0][0], 400.0)
+ self.assertEqual(queue[1][0], 50.0)
+ self.assertEqual(queue[2][0], 50.0)
+ # check if time buckets add up to balance qty
+ self.assertEqual(sum([i[0] for i in queue]), 500.0)
+
+ def test_repack_entry_same_item_overconsume(self):
+ """
+ Over consume item and have less repacked item qty (same warehouse).
+ Ledger:
+ Item | Qty | Voucher
+ ------------------------
+ Item 1 | 500 | 001
+ Item 1 | -100 | 002 (repack)
+ Item 1 | 50 | 002 (repack)
+
+ Case most likely for batch items. Test time bucket computation.
+ """
+ sle = [
+ frappe._dict( # stock up item
+ name="Flask Item",
+ actual_qty=500, qty_after_transaction=500,
+ warehouse="WH 1",
+ posting_date="2021-12-03", voucher_type="Stock Entry",
+ voucher_no="001",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=(-100), qty_after_transaction=400,
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=50, qty_after_transaction=450,
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ ]
+ slots = FIFOSlots(self.filters, sle).generate()
+ item_result = slots["Flask Item"]
+ queue = item_result["fifo_queue"]
+
+ self.assertEqual(item_result["total_qty"], 450.0)
+ self.assertEqual(queue[0][0], 400.0)
+ self.assertEqual(queue[1][0], 50.0)
+ # check if time buckets add up to balance qty
+ self.assertEqual(sum([i[0] for i in queue]), 450.0)
+
+ def test_repack_entry_same_item_overconsume_with_split_rows(self):
+ """
+ Over consume item and have less repacked item qty (same warehouse).
+ Ledger:
+ Item | Qty | Voucher
+ ------------------------
+ Item 1 | 20 | 001
+ Item 1 | -50 | 002 (repack)
+ Item 1 | -50 | 002 (repack)
+ Item 1 | 50 | 002 (repack)
+ """
+ sle = [
+ frappe._dict( # stock up item
+ name="Flask Item",
+ actual_qty=20, qty_after_transaction=20,
+ warehouse="WH 1",
+ posting_date="2021-12-03", voucher_type="Stock Entry",
+ voucher_no="001",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=(-50), qty_after_transaction=(-30),
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=(-50), qty_after_transaction=(-80),
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=50, qty_after_transaction=(-30),
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ ]
+ fifo_slots = FIFOSlots(self.filters, sle)
+ slots = fifo_slots.generate()
+ item_result = slots["Flask Item"]
+ queue = item_result["fifo_queue"]
+
+ self.assertEqual(item_result["total_qty"], -30.0)
+ self.assertEqual(queue[0][0], -30.0)
+
+ # check transfer bucket
+ transfer_bucket = fifo_slots.transferred_item_details[('002', 'Flask Item', 'WH 1')]
+ self.assertEqual(transfer_bucket[0][0], 50)
+
+ def test_repack_entry_same_item_overproduce(self):
+ """
+ Under consume item and have more repacked item qty (same warehouse).
+ Ledger:
+ Item | Qty | Voucher
+ ------------------------
+ Item 1 | 500 | 001
+ Item 1 | -50 | 002 (repack)
+ Item 1 | 100 | 002 (repack)
+
+ Case most likely for batch items. Test time bucket computation.
+ """
+ sle = [
+ frappe._dict( # stock up item
+ name="Flask Item",
+ actual_qty=500, qty_after_transaction=500,
+ warehouse="WH 1",
+ posting_date="2021-12-03", voucher_type="Stock Entry",
+ voucher_no="001",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=(-50), qty_after_transaction=450,
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=100, qty_after_transaction=550,
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ ]
+ slots = FIFOSlots(self.filters, sle).generate()
+ item_result = slots["Flask Item"]
+ queue = item_result["fifo_queue"]
+
+ self.assertEqual(item_result["total_qty"], 550.0)
+ self.assertEqual(queue[0][0], 450.0)
+ self.assertEqual(queue[1][0], 50.0)
+ self.assertEqual(queue[2][0], 50.0)
+ # check if time buckets add up to balance qty
+ self.assertEqual(sum([i[0] for i in queue]), 550.0)
+
+ def test_repack_entry_same_item_overproduce_with_split_rows(self):
+ """
+ Over consume item and have less repacked item qty (same warehouse).
+ Ledger:
+ Item | Qty | Voucher
+ ------------------------
+ Item 1 | 20 | 001
+ Item 1 | -50 | 002 (repack)
+ Item 1 | 50 | 002 (repack)
+ Item 1 | 50 | 002 (repack)
+ """
+ sle = [
+ frappe._dict( # stock up item
+ name="Flask Item",
+ actual_qty=20, qty_after_transaction=20,
+ warehouse="WH 1",
+ posting_date="2021-12-03", voucher_type="Stock Entry",
+ voucher_no="001",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=(-50), qty_after_transaction=(-30),
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=50, qty_after_transaction=20,
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict(
+ name="Flask Item",
+ actual_qty=50, qty_after_transaction=70,
+ warehouse="WH 1",
+ posting_date="2021-12-04", voucher_type="Stock Entry",
+ voucher_no="002",
+ has_serial_no=False, serial_no=None
+ ),
+ ]
+ fifo_slots = FIFOSlots(self.filters, sle)
+ slots = fifo_slots.generate()
+ item_result = slots["Flask Item"]
+ queue = item_result["fifo_queue"]
+
+ self.assertEqual(item_result["total_qty"], 70.0)
+ self.assertEqual(queue[0][0], 20.0)
+ self.assertEqual(queue[1][0], 50.0)
+
+ # check transfer bucket
+ transfer_bucket = fifo_slots.transferred_item_details[('002', 'Flask Item', 'WH 1')]
+ self.assertFalse(transfer_bucket)
+
+ def test_negative_stock_same_voucher(self):
+ """
+ Test negative stock scenario in transfer bucket via repack entry (same wh).
+ Ledger:
+ Item | Qty | Voucher
+ ------------------------
+ Item 1 | -50 | 001
+ Item 1 | -50 | 001
+ Item 1 | 30 | 001
+ Item 1 | 80 | 001
+ """
+ sle = [
+ frappe._dict( # stock up item
+ name="Flask Item",
+ actual_qty=(-50), qty_after_transaction=(-50),
+ warehouse="WH 1",
+ posting_date="2021-12-01", voucher_type="Stock Entry",
+ voucher_no="001",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict( # stock up item
+ name="Flask Item",
+ actual_qty=(-50), qty_after_transaction=(-100),
+ warehouse="WH 1",
+ posting_date="2021-12-01", voucher_type="Stock Entry",
+ voucher_no="001",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict( # stock up item
+ name="Flask Item",
+ actual_qty=30, qty_after_transaction=(-70),
+ warehouse="WH 1",
+ posting_date="2021-12-01", voucher_type="Stock Entry",
+ voucher_no="001",
+ has_serial_no=False, serial_no=None
+ ),
+ ]
+ fifo_slots = FIFOSlots(self.filters, sle)
+ slots = fifo_slots.generate()
+ item_result = slots["Flask Item"]
+
+ # check transfer bucket
+ transfer_bucket = fifo_slots.transferred_item_details[('001', 'Flask Item', 'WH 1')]
+ self.assertEqual(transfer_bucket[0][0], 20)
+ self.assertEqual(transfer_bucket[1][0], 50)
+ self.assertEqual(item_result["fifo_queue"][0][0], -70.0)
+
+ sle.append(frappe._dict(
+ name="Flask Item",
+ actual_qty=80, qty_after_transaction=10,
+ warehouse="WH 1",
+ posting_date="2021-12-01", voucher_type="Stock Entry",
+ voucher_no="001",
+ has_serial_no=False, serial_no=None
+ ))
+
+ fifo_slots = FIFOSlots(self.filters, sle)
+ slots = fifo_slots.generate()
+ item_result = slots["Flask Item"]
+
+ transfer_bucket = fifo_slots.transferred_item_details[('001', 'Flask Item', 'WH 1')]
+ self.assertFalse(transfer_bucket)
+ self.assertEqual(item_result["fifo_queue"][0][0], 10.0)
+
+ def test_precision(self):
+ "Test if final balance qty is rounded off correctly."
+ sle = [
+ frappe._dict( # stock up item
+ name="Flask Item",
+ actual_qty=0.3, qty_after_transaction=0.3,
+ warehouse="WH 1",
+ posting_date="2021-12-01", voucher_type="Stock Entry",
+ voucher_no="001",
+ has_serial_no=False, serial_no=None
+ ),
+ frappe._dict( # stock up item
+ name="Flask Item",
+ actual_qty=0.6, qty_after_transaction=0.9,
+ warehouse="WH 1",
+ posting_date="2021-12-01", voucher_type="Stock Entry",
+ voucher_no="001",
+ has_serial_no=False, serial_no=None
+ ),
+ ]
+
+ slots = FIFOSlots(self.filters, sle).generate()
+ report_data = format_report_data(self.filters, slots, self.filters["to_date"])
+ row = report_data[0] # first row in report
+ bal_qty = row[5]
+ range_qty_sum = sum([i for i in row[7:11]]) # get sum of range balance
+
+ # check if value of Available Qty column matches with range bucket post format
+ self.assertEqual(bal_qty, 0.9)
+ self.assertEqual(bal_qty, range_qty_sum)
+
+def generate_item_and_item_wh_wise_slots(filters, sle):
+ "Return results with and without 'show_warehouse_wise_stock'"
+ item_wise_slots = FIFOSlots(filters, sle).generate()
+
+ filters.show_warehouse_wise_stock = True
+ item_wh_wise_slots = FIFOSlots(filters, sle).generate()
+ filters.show_warehouse_wise_stock = False
+
+ return item_wise_slots, item_wh_wise_slots
diff --git a/erpnext/stock/report/stock_analytics/test_stock_analytics.py b/erpnext/stock/report/stock_analytics/test_stock_analytics.py
index 32df585..f6c98f9 100644
--- a/erpnext/stock/report/stock_analytics/test_stock_analytics.py
+++ b/erpnext/stock/report/stock_analytics/test_stock_analytics.py
@@ -1,14 +1,13 @@
import datetime
-import unittest
from frappe import _dict
+from frappe.tests.utils import FrappeTestCase
from erpnext.accounts.utils import get_fiscal_year
from erpnext.stock.report.stock_analytics.stock_analytics import get_period_date_ranges
-from erpnext.tests.utils import ERPNextTestCase
-class TestStockAnalyticsReport(ERPNextTestCase):
+class TestStockAnalyticsReport(FrappeTestCase):
def test_get_period_date_ranges(self):
filters = _dict(range="Monthly", from_date="2020-12-28", to_date="2021-02-06")
diff --git a/erpnext/stock/report/stock_ledger_invariant_check/stock_ledger_invariant_check.py b/erpnext/stock/report/stock_ledger_invariant_check/stock_ledger_invariant_check.py
index 48753b0..1ba2482 100644
--- a/erpnext/stock/report/stock_ledger_invariant_check/stock_ledger_invariant_check.py
+++ b/erpnext/stock/report/stock_ledger_invariant_check/stock_ledger_invariant_check.py
@@ -21,6 +21,7 @@
"stock_value",
"stock_value_difference",
"valuation_rate",
+ "voucher_detail_no",
)
@@ -60,10 +61,15 @@
fifo_qty += qty
fifo_value += qty * rate
+ if sle.actual_qty < 0:
+ sle.consumption_rate = sle.stock_value_difference / sle.actual_qty
+
balance_qty += sle.actual_qty
balance_stock_value += sle.stock_value_difference
if sle.voucher_type == "Stock Reconciliation" and not sle.batch_no:
- balance_qty = sle.qty_after_transaction
+ balance_qty = frappe.db.get_value("Stock Reconciliation Item", sle.voucher_detail_no, "qty")
+ if balance_qty is None:
+ balance_qty = sle.qty_after_transaction
sle.fifo_queue_qty = fifo_qty
sle.fifo_stock_value = fifo_value
@@ -90,6 +96,9 @@
sle.fifo_stock_diff = sle.fifo_stock_value - sles[idx - 1].fifo_stock_value
sle.fifo_difference_diff = sle.fifo_stock_diff - sle.stock_value_difference
+ if sle.batch_no:
+ sle.use_batchwise_valuation = frappe.db.get_value("Batch", sle.batch_no, "use_batchwise_valuation", cache=True)
+
return sles
@@ -135,6 +144,11 @@
"options": "Batch",
},
{
+ "fieldname": "use_batchwise_valuation",
+ "fieldtype": "Check",
+ "label": "Batchwise Valuation",
+ },
+ {
"fieldname": "actual_qty",
"fieldtype": "Float",
"label": "Qty Change",
@@ -145,9 +159,9 @@
"label": "Incoming Rate",
},
{
- "fieldname": "outgoing_rate",
+ "fieldname": "consumption_rate",
"fieldtype": "Float",
- "label": "Outgoing Rate",
+ "label": "Consumption Rate",
},
{
"fieldname": "qty_after_transaction",
@@ -167,7 +181,7 @@
{
"fieldname": "stock_queue",
"fieldtype": "Data",
- "label": "FIFO Queue",
+ "label": "FIFO/LIFO Queue",
},
{
diff --git a/erpnext/stock/report/test_reports.py b/erpnext/stock/report/test_reports.py
index 525af40..76c2079 100644
--- a/erpnext/stock/report/test_reports.py
+++ b/erpnext/stock/report/test_reports.py
@@ -73,10 +73,11 @@
def test_execute_all_stock_reports(self):
"""Test that all script report in stock modules are executable with supported filters"""
for report, filter in REPORT_FILTER_TEST_CASES:
- execute_script_report(
- report_name=report,
- module="Stock",
- filters=filter,
- default_filters=DEFAULT_FILTERS,
- optional_filters=OPTIONAL_FILTERS if filter.get("_optional") else None,
- )
+ with self.subTest(report=report):
+ execute_script_report(
+ report_name=report,
+ module="Stock",
+ filters=filter,
+ default_filters=DEFAULT_FILTERS,
+ optional_filters=OPTIONAL_FILTERS if filter.get("_optional") else None,
+ )
diff --git a/erpnext/stock/spec/README.md b/erpnext/stock/spec/README.md
new file mode 100644
index 0000000..f5a3501
--- /dev/null
+++ b/erpnext/stock/spec/README.md
@@ -0,0 +1,103 @@
+# Implementation notes for Stock Ledger
+
+
+## Important files
+
+- `stock/stock_ledger.py`
+- `controllers/stock_controller.py`
+- `stock/valuation.py`
+
+## What is in an Stock Ledger Entry (SLE)?
+
+Stock Ledger Entry is a single row in the Stock Ledger. It signifies some
+modification of stock for a particular Item in the specified warehouse.
+
+- `item_code`: item for which ledger entry is made
+- `warehouse`: warehouse where inventory is affected
+- `actual_qty`: change in qty
+- `qty_after_transaction`: quantity available after the transaction is processed
+- `incoming_rate`: rate at which inventory was received.
+- `is_cancelled`: if 1 then stock ledger entry is cancelled and should not be used
+for any business logic except for the code that handles cancellation.
+- `posting_date` & `posting_time`: Specify the temporal ordering of stock ledger
+ entries. Ties are broken by `creation` timestamp.
+- `voucher_type`: Many transaction can create SLE, e.g. Stock Entry, Purchase
+ Invoice
+- `voucher_no`: `name` of the transaction that created SLE
+- `voucher_detail_no`: `name` of the child table row from parent transaction
+ that created the SLE.
+- `dependant_sle_voucher_detail_no`: cross-warehouse transfers need this
+ reference in order to update dependent warehouse rates in case of change in
+ rate.
+- `recalculate_rate`: if this is checked in/out rates are recomputed on
+ transactions.
+- `valuation_rate`: current average valuation rate.
+- `stock_value`: current total stock value
+- `stock_value_difference`: stock value difference made between last and current
+ entry. This value is booked in accounting ledger.
+- `stock_queue`: if FIFO/LIFO is used this represents queue/stack maintained for
+ computing incoming rate for inventory getting consumed.
+- `batch_no`: batch no for which stock entry is made; each stock entry can only
+ affect one batch number.
+- `serial_no`: newline separated list of serial numbers that were added (if
+ actual_qty > 0) or else removed. Currently multiple serial nos can have single
+ SLE but this will likely change in future.
+
+
+## Implementation of Stock Ledger
+
+Stock Ledger Entry affects stock of combinations of (item_code, warehouse) and
+optionally batch no if specified. For simplicity, lets avoid batch no. for now.
+
+
+Stock Ledger Entry table stores stock ledger for all combinations of item_code
+and warehouse. So whenever any operations are to be performed on said
+item-warehouse combination stock ledger is filtered and sorted by posting
+datetime. A typical query that will give you individual ledger looks like this:
+
+```sql
+select *
+from `tabStock Ledger Entry` as sle
+where
+ is_cancelled = 0 --- cancelled entries don't affect ledger
+ and item_code = 'item_code' and warehouse = 'warehouse_name'
+order by timestamp(posting_date, posting_time), creation
+```
+
+New entry is just an update to the last entry which is found by looking at last
+row in the filter ledger.
+
+
+### Serial nos
+
+Serial numbers do not follow any valuation method configuration and they are
+consumed at rate they were produced unless they are grouped in which case they
+are consumed at weighted average rate.
+
+
+### Batch Nos
+
+Batches are currently NOT consumed as per batch wise valuation rate, instead
+global FIFO queue for the item is used for valuation rate.
+
+
+## Creation process of SLEs
+
+- SLE creation is usually triggered by Stock Transactions using a method
+ conventionally named `update_stock_ledger()` This might not be defined for
+ stock transaction and could be specified somewhere in inheritance hierarchy of
+ controllers.
+- This method produces SLE objects which are processed by `make_sl_entries` in
+ `stock_ledger.py` which commits the SLE to database.
+- `update_entries_after` class is used to process ONLY the inserted SLE's queue
+ and valuation.
+- The change in qty is propagated to future entries immediately. Valuation and
+ queue for future entries is processed in background using repost item
+ valuation.
+
+
+## Accounting impact
+
+- Accounting impact for stock transaction is handled by `get_gl_entries()`
+ method on controllers. Each transaction has different business logic for
+ booking the accounting impact.
diff --git a/erpnext/stock/spec/reposting.md b/erpnext/stock/spec/reposting.md
new file mode 100644
index 0000000..b0d59fe
--- /dev/null
+++ b/erpnext/stock/spec/reposting.md
@@ -0,0 +1,38 @@
+# Stock Reposting
+
+Stock "reposting" is process of re-processing Stock Ledger Entry and GL Entries
+in event of backdated stock transaction.
+
+*Backdated stock transaction*: Any stock transaction for which some
+item-warehouse combination has a future transactions.
+
+## Why is this required?
+Stock Ledger is stateful, it maintains queue, qty at any
+point in time. So if you do a backdated transaction all future values change,
+queues need to be re-evaluated etc. Watch Nabin and Rohit's conference
+presentation for explanation: https://www.youtube.com/watch?v=mw3WAnekGIM
+
+## How is this implemented?
+Whenever backdated transaction is detected, instead of
+fully processing it while submitting, the processing is queued using "Repost
+Item Valuation" doctype. Every hour a scheduled job runs and processes this
+queue (for up to maximum of 25 minutes)
+
+
+## Queue implementation
+- "Repost item valuation" (RIV) is automatically submitted from backdated transactions. (check stock_controller.py)
+- Draft and cancelled RIV are ignored.
+- Keep filter of "submitted" documents when doing anything with RIVs.
+- The default status is "Queued".
+- When background job runs, it picks the oldest pending reposts and changes the status to "In Progress" and when it finishes it
+changes to "Completed"
+- There are two more status: "Failed" when reposting failed and "Skipped" when reposting is deemed not necessary so it's skipped.
+- technical detail: Entry point for whole process is "repost_entries" function in repost_item_valuation.py
+
+
+## How to identify broken stock data:
+There are 4 major reports for checking broken stock data:
+- Incorrect balance qty after the transaction - to check if the running total of qty isn't correct.
+- Incorrect stock value report - to check incorrect value books in accounts for stock transactions
+- Incorrect serial no valuation -specific to serial nos
+- Stock ledger invariant check - combined report for checking qty, running total, queue, balance value etc
diff --git a/erpnext/stock/stock_balance.py b/erpnext/stock/stock_balance.py
index 6663458..62017e4 100644
--- a/erpnext/stock/stock_balance.py
+++ b/erpnext/stock/stock_balance.py
@@ -3,10 +3,9 @@
import frappe
-from frappe.utils import cstr, flt, nowdate, nowtime
+from frappe.utils import cstr, flt, now, nowdate, nowtime
from erpnext.controllers.stock_controller import create_repost_item_valuation_entry
-from erpnext.stock.utils import update_bin
def repost(only_actual=False, allow_negative_stock=False, allow_zero_rate=False, only_bin=False):
@@ -175,6 +174,7 @@
bin.set(field, flt(value))
mismatch = True
+ bin.modified = now()
if mismatch:
bin.set_projected_qty()
bin.db_update()
@@ -227,8 +227,6 @@
"sle_id": sle_doc.name
})
- update_bin(args)
-
create_repost_item_valuation_entry({
"item_code": d[0],
"warehouse": d[1],
diff --git a/erpnext/stock/stock_ledger.py b/erpnext/stock/stock_ledger.py
index 0a7ab40..ba1081f 100644
--- a/erpnext/stock/stock_ledger.py
+++ b/erpnext/stock/stock_ledger.py
@@ -3,11 +3,14 @@
import copy
import json
+from typing import Optional
import frappe
from frappe import _
from frappe.model.meta import get_field_precision
+from frappe.query_builder.functions import Sum
from frappe.utils import cint, cstr, flt, get_link_to_form, getdate, now, nowdate
+from pypika import CustomFunction
import erpnext
from erpnext.stock.doctype.bin.bin import update_qty as update_bin_qty
@@ -16,16 +19,25 @@
get_or_make_bin,
get_valuation_method,
)
-from erpnext.stock.valuation import FIFOValuation
+from erpnext.stock.valuation import FIFOValuation, LIFOValuation, round_off_if_near_zero
class NegativeStockError(frappe.ValidationError): pass
class SerialNoExistsInFutureTransaction(frappe.ValidationError):
pass
-_exceptions = frappe.local('stockledger_exceptions')
def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
+ """ Create SL entries from SL entry dicts
+
+ args:
+ - allow_negative_stock: disable negative stock valiations if true
+ - via_landed_cost_voucher: landed cost voucher cancels and reposts
+ entries of purchase document. This flag is used to identify if
+ cancellation and repost is happening via landed cost voucher, in
+ such cases certain validations need to be ignored (like negative
+ stock)
+ """
from erpnext.controllers.stock_controller import future_sle_exists
if sl_entries:
cancel = sl_entries[0].get("is_cancelled")
@@ -37,7 +49,7 @@
future_sle_exists(args, sl_entries)
for sle in sl_entries:
- if sle.serial_no:
+ if sle.serial_no and not via_landed_cost_voucher:
validate_serial_no(sle)
if cancel:
@@ -268,11 +280,10 @@
self.verbose = verbose
self.allow_zero_rate = allow_zero_rate
self.via_landed_cost_voucher = via_landed_cost_voucher
- self.allow_negative_stock = allow_negative_stock \
- or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
+ self.item_code = args.get("item_code")
+ self.allow_negative_stock = allow_negative_stock or is_negative_stock_allowed(item_code=self.item_code)
self.args = frappe._dict(args)
- self.item_code = args.get("item_code")
if self.args.sle_id:
self.args['name'] = self.args.sle_id
@@ -447,6 +458,8 @@
self.wh_data.qty_after_transaction = sle.qty_after_transaction
self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate)
+ elif sle.batch_no and frappe.db.get_value("Batch", sle.batch_no, "use_batchwise_valuation", cache=True):
+ self.update_batched_values(sle)
else:
if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
# assert
@@ -461,11 +474,12 @@
self.wh_data.qty_after_transaction += flt(sle.actual_qty)
self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate)
else:
- self.update_fifo_values(sle)
- self.wh_data.qty_after_transaction += flt(sle.actual_qty)
+ self.update_queue_values(sle)
# rounding as per precision
self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
+ if not self.wh_data.qty_after_transaction:
+ self.wh_data.stock_value = 0.0
stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
self.wh_data.prev_stock_value = self.wh_data.stock_value
@@ -481,6 +495,7 @@
if not self.args.get("sle_id"):
self.update_outgoing_rate_on_transaction(sle)
+
def validate_negative_stock(self, sle):
"""
validate negative stock for entries current datetime onwards
@@ -629,9 +644,7 @@
if not self.wh_data.valuation_rate and sle.voucher_detail_no:
allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
if not allow_zero_rate:
- self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
- sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
- currency=erpnext.get_company_currency(sle.company), company=sle.company)
+ self.wh_data.valuation_rate = self.get_fallback_rate(sle)
def get_incoming_value_for_serial_nos(self, sle, serial_nos):
# get rate from serial nos within same company
@@ -697,42 +710,70 @@
if not self.wh_data.valuation_rate and sle.voucher_detail_no:
allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
if not allow_zero_valuation_rate:
- self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
- sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
- currency=erpnext.get_company_currency(sle.company), company=sle.company)
+ self.wh_data.valuation_rate = self.get_fallback_rate(sle)
- def update_fifo_values(self, sle):
+ def update_queue_values(self, sle):
incoming_rate = flt(sle.incoming_rate)
actual_qty = flt(sle.actual_qty)
outgoing_rate = flt(sle.outgoing_rate)
- fifo_queue = FIFOValuation(self.wh_data.stock_queue)
+ self.wh_data.qty_after_transaction = round_off_if_near_zero(self.wh_data.qty_after_transaction + actual_qty)
+
+ if self.valuation_method == "LIFO":
+ stock_queue = LIFOValuation(self.wh_data.stock_queue)
+ else:
+ stock_queue = FIFOValuation(self.wh_data.stock_queue)
+
+ _prev_qty, prev_stock_value = stock_queue.get_total_stock_and_value()
+
if actual_qty > 0:
- fifo_queue.add_stock(qty=actual_qty, rate=incoming_rate)
+ stock_queue.add_stock(qty=actual_qty, rate=incoming_rate)
else:
def rate_generator() -> float:
allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
if not allow_zero_valuation_rate:
- return get_valuation_rate(sle.item_code, sle.warehouse,
- sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
- currency=erpnext.get_company_currency(sle.company), company=sle.company)
+ return self.get_fallback_rate(sle)
else:
return 0.0
- fifo_queue.remove_stock(qty=abs(actual_qty), outgoing_rate=outgoing_rate, rate_generator=rate_generator)
+ stock_queue.remove_stock(qty=abs(actual_qty), outgoing_rate=outgoing_rate, rate_generator=rate_generator)
- stock_qty, stock_value = fifo_queue.get_total_stock_and_value()
+ _qty, stock_value = stock_queue.get_total_stock_and_value()
- self.wh_data.stock_queue = fifo_queue.get_state()
- self.wh_data.stock_value = stock_value
- if stock_qty:
- self.wh_data.valuation_rate = stock_value / stock_qty
+ stock_value_difference = stock_value - prev_stock_value
+ self.wh_data.stock_queue = stock_queue.state
+ self.wh_data.stock_value = round_off_if_near_zero(self.wh_data.stock_value + stock_value_difference)
if not self.wh_data.stock_queue:
self.wh_data.stock_queue.append([0, sle.incoming_rate or sle.outgoing_rate or self.wh_data.valuation_rate])
+ if self.wh_data.qty_after_transaction:
+ self.wh_data.valuation_rate = self.wh_data.stock_value / self.wh_data.qty_after_transaction
+ def update_batched_values(self, sle):
+ incoming_rate = flt(sle.incoming_rate)
+ actual_qty = flt(sle.actual_qty)
+
+ self.wh_data.qty_after_transaction = round_off_if_near_zero(self.wh_data.qty_after_transaction + actual_qty)
+
+ if actual_qty > 0:
+ stock_value_difference = incoming_rate * actual_qty
+ else:
+ outgoing_rate = get_batch_incoming_rate(item_code=sle.item_code,
+ warehouse=sle.warehouse, batch_no=sle.batch_no, posting_date=sle.posting_date,
+ posting_time=sle.posting_time, creation=sle.creation)
+ if outgoing_rate is None:
+ # This can *only* happen if qty available for the batch is zero.
+ # in such case fall back various other rates.
+ # future entries will correct the overall accounting as each
+ # batch individually uses moving average rates.
+ outgoing_rate = self.get_fallback_rate(sle)
+ stock_value_difference = outgoing_rate * actual_qty
+
+ self.wh_data.stock_value = round_off_if_near_zero(self.wh_data.stock_value + stock_value_difference)
+ if self.wh_data.qty_after_transaction:
+ self.wh_data.valuation_rate = self.wh_data.stock_value / self.wh_data.qty_after_transaction
def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
ref_item_dt = ""
@@ -747,6 +788,13 @@
else:
return 0
+ def get_fallback_rate(self, sle) -> float:
+ """When exact incoming rate isn't available use any of other "average" rates as fallback.
+ This should only get used for negative stock."""
+ return get_valuation_rate(sle.item_code, sle.warehouse,
+ sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
+ currency=erpnext.get_company_currency(sle.company), company=sle.company, batch_no=sle.batch_no)
+
def get_sle_before_datetime(self, args):
"""get previous stock ledger entry before current time-bucket"""
sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
@@ -781,7 +829,7 @@
if msg_list:
message = "\n\n".join(msg_list)
if self.verbose:
- frappe.throw(message, NegativeStockError, title='Insufficient Stock')
+ frappe.throw(message, NegativeStockError, title=_('Insufficient Stock'))
else:
raise NegativeStockError(message)
@@ -893,22 +941,72 @@
['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
as_dict=1)
+def get_batch_incoming_rate(item_code, warehouse, batch_no, posting_date, posting_time, creation=None):
+
+ Timestamp = CustomFunction('timestamp', ['date', 'time'])
+
+ sle = frappe.qb.DocType("Stock Ledger Entry")
+
+ timestamp_condition = (Timestamp(sle.posting_date, sle.posting_time) < Timestamp(posting_date, posting_time))
+ if creation:
+ timestamp_condition |= (
+ (Timestamp(sle.posting_date, sle.posting_time) == Timestamp(posting_date, posting_time))
+ & (sle.creation < creation)
+ )
+
+ batch_details = (
+ frappe.qb
+ .from_(sle)
+ .select(
+ Sum(sle.stock_value_difference).as_("batch_value"),
+ Sum(sle.actual_qty).as_("batch_qty")
+ )
+ .where(
+ (sle.item_code == item_code)
+ & (sle.warehouse == warehouse)
+ & (sle.batch_no == batch_no)
+ & (sle.is_cancelled == 0)
+ )
+ .where(timestamp_condition)
+ ).run(as_dict=True)
+
+ if batch_details and batch_details[0].batch_qty:
+ return batch_details[0].batch_value / batch_details[0].batch_qty
+
+
def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
- allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
+ allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True, batch_no=None):
if not company:
company = frappe.get_cached_value("Warehouse", warehouse, "company")
+ last_valuation_rate = None
+
+ # Get moving average rate of a specific batch number
+ if warehouse and batch_no and frappe.db.get_value("Batch", batch_no, "use_batchwise_valuation"):
+ last_valuation_rate = frappe.db.sql("""
+ select sum(stock_value_difference) / sum(actual_qty)
+ from `tabStock Ledger Entry`
+ where
+ item_code = %s
+ AND warehouse = %s
+ AND batch_no = %s
+ AND is_cancelled = 0
+ AND NOT (voucher_no = %s AND voucher_type = %s)
+ """,
+ (item_code, warehouse, batch_no, voucher_no, voucher_type))
+
# Get valuation rate from last sle for the same item and warehouse
- last_valuation_rate = frappe.db.sql("""select valuation_rate
- from `tabStock Ledger Entry` force index (item_warehouse)
- where
- item_code = %s
- AND warehouse = %s
- AND valuation_rate >= 0
- AND is_cancelled = 0
- AND NOT (voucher_no = %s AND voucher_type = %s)
- order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse, voucher_no, voucher_type))
+ if not last_valuation_rate or last_valuation_rate[0][0] is None:
+ last_valuation_rate = frappe.db.sql("""select valuation_rate
+ from `tabStock Ledger Entry` force index (item_warehouse)
+ where
+ item_code = %s
+ AND warehouse = %s
+ AND valuation_rate >= 0
+ AND is_cancelled = 0
+ AND NOT (voucher_no = %s AND voucher_type = %s)
+ order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse, voucher_no, voucher_type))
if not last_valuation_rate:
# Get valuation rate from last sle for the item against any warehouse
@@ -1045,10 +1143,7 @@
)"""
def validate_negative_qty_in_future_sle(args, allow_negative_stock=False):
- allow_negative_stock = cint(allow_negative_stock) \
- or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
-
- if allow_negative_stock:
+ if allow_negative_stock or is_negative_stock_allowed(item_code=args.item_code):
return
if not (args.actual_qty < 0 or args.voucher_type == "Stock Reconciliation"):
return
@@ -1062,7 +1157,7 @@
neg_sle[0]["posting_date"], neg_sle[0]["posting_time"],
frappe.get_desk_link(neg_sle[0]["voucher_type"], neg_sle[0]["voucher_no"]))
- frappe.throw(message, NegativeStockError, title='Insufficient Stock')
+ frappe.throw(message, NegativeStockError, title=_('Insufficient Stock'))
if not args.batch_no:
@@ -1076,7 +1171,7 @@
frappe.get_desk_link('Warehouse', args.warehouse),
neg_batch_sle[0]["posting_date"], neg_batch_sle[0]["posting_time"],
frappe.get_desk_link(neg_batch_sle[0]["voucher_type"], neg_batch_sle[0]["voucher_no"]))
- frappe.throw(message, NegativeStockError, title="Insufficient Stock for Batch")
+ frappe.throw(message, NegativeStockError, title=_("Insufficient Stock for Batch"))
def get_future_sle_with_negative_qty(args):
@@ -1117,3 +1212,11 @@
and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
limit 1
""", args, as_dict=1)
+
+
+def is_negative_stock_allowed(*, item_code: Optional[str] = None) -> bool:
+ if cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock", cache=True)):
+ return True
+ if item_code and cint(frappe.db.get_value("Item", item_code, "allow_negative_stock", cache=True)):
+ return True
+ return False
diff --git a/erpnext/stock/tests/test_valuation.py b/erpnext/stock/tests/test_valuation.py
index 85788ba..b64ff8e 100644
--- a/erpnext/stock/tests/test_valuation.py
+++ b/erpnext/stock/tests/test_valuation.py
@@ -1,16 +1,21 @@
+import json
import unittest
+import frappe
+from frappe.tests.utils import FrappeTestCase
from hypothesis import given
from hypothesis import strategies as st
-from erpnext.stock.valuation import FIFOValuation, _round_off_if_near_zero
+from erpnext.stock.doctype.item.test_item import make_item
+from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
+from erpnext.stock.valuation import FIFOValuation, LIFOValuation, round_off_if_near_zero
qty_gen = st.floats(min_value=-1e6, max_value=1e6)
value_gen = st.floats(min_value=1, max_value=1e6)
stock_queue_generator = st.lists(st.tuples(qty_gen, value_gen), min_size=10)
-class TestFifoValuation(unittest.TestCase):
+class TestFIFOValuation(unittest.TestCase):
def setUp(self):
self.queue = FIFOValuation([])
@@ -108,11 +113,11 @@
self.assertTotalQty(0)
def test_rounding_off_near_zero(self):
- self.assertEqual(_round_off_if_near_zero(0), 0)
- self.assertEqual(_round_off_if_near_zero(1), 1)
- self.assertEqual(_round_off_if_near_zero(-1), -1)
- self.assertEqual(_round_off_if_near_zero(-1e-8), 0)
- self.assertEqual(_round_off_if_near_zero(1e-8), 0)
+ self.assertEqual(round_off_if_near_zero(0), 0)
+ self.assertEqual(round_off_if_near_zero(1), 1)
+ self.assertEqual(round_off_if_near_zero(-1), -1)
+ self.assertEqual(round_off_if_near_zero(-1e-8), 0)
+ self.assertEqual(round_off_if_near_zero(1e-8), 0)
def test_totals(self):
self.queue.add_stock(1, 10)
@@ -164,3 +169,184 @@
total_value -= sum(q * r for q, r in consumed)
self.assertTotalQty(total_qty)
self.assertTotalValue(total_value)
+
+
+class TestLIFOValuation(unittest.TestCase):
+
+ def setUp(self):
+ self.stack = LIFOValuation([])
+
+ def tearDown(self):
+ qty, value = self.stack.get_total_stock_and_value()
+ self.assertTotalQty(qty)
+ self.assertTotalValue(value)
+
+ def assertTotalQty(self, qty):
+ self.assertAlmostEqual(sum(q for q, _ in self.stack), qty, msg=f"stack: {self.stack}", places=4)
+
+ def assertTotalValue(self, value):
+ self.assertAlmostEqual(sum(q * r for q, r in self.stack), value, msg=f"stack: {self.stack}", places=2)
+
+ def test_simple_addition(self):
+ self.stack.add_stock(1, 10)
+ self.assertTotalQty(1)
+
+ def test_merge_new_stock(self):
+ self.stack.add_stock(1, 10)
+ self.stack.add_stock(1, 10)
+ self.assertEqual(self.stack, [[2, 10]])
+
+ def test_simple_removal(self):
+ self.stack.add_stock(1, 10)
+ self.stack.remove_stock(1)
+ self.assertTotalQty(0)
+
+ def test_adding_negative_stock_keeps_rate(self):
+ self.stack = LIFOValuation([[-5.0, 100]])
+ self.stack.add_stock(1, 10)
+ self.assertEqual(self.stack, [[-4, 100]])
+
+ def test_adding_negative_stock_updates_rate(self):
+ self.stack = LIFOValuation([[-5.0, 100]])
+ self.stack.add_stock(6, 10)
+ self.assertEqual(self.stack, [[1, 10]])
+
+ def test_rounding_off(self):
+ self.stack.add_stock(1.0, 1.0)
+ self.stack.remove_stock(1.0 - 1e-9)
+ self.assertTotalQty(0)
+
+ def test_lifo_consumption(self):
+ self.stack.add_stock(10, 10)
+ self.stack.add_stock(10, 20)
+ consumed = self.stack.remove_stock(15)
+ self.assertEqual(consumed, [[10, 20], [5, 10]])
+ self.assertTotalQty(5)
+
+ def test_lifo_consumption_going_negative(self):
+ self.stack.add_stock(10, 10)
+ self.stack.add_stock(10, 20)
+ consumed = self.stack.remove_stock(25)
+ self.assertEqual(consumed, [[10, 20], [10, 10], [5, 10]])
+ self.assertTotalQty(-5)
+
+ def test_lifo_consumption_multiple(self):
+ self.stack.add_stock(1, 1)
+ self.stack.add_stock(2, 2)
+ consumed = self.stack.remove_stock(1)
+ self.assertEqual(consumed, [[1, 2]])
+
+ self.stack.add_stock(3, 3)
+ consumed = self.stack.remove_stock(4)
+ self.assertEqual(consumed, [[3, 3], [1, 2]])
+
+ self.stack.add_stock(4, 4)
+ consumed = self.stack.remove_stock(5)
+ self.assertEqual(consumed, [[4, 4], [1, 1]])
+
+ self.stack.add_stock(5, 5)
+ consumed = self.stack.remove_stock(5)
+ self.assertEqual(consumed, [[5, 5]])
+
+
+ @given(stock_queue_generator)
+ def test_lifo_qty_hypothesis(self, stock_stack):
+ self.stack = LIFOValuation([])
+ total_qty = 0
+
+ for qty, rate in stock_stack:
+ if qty == 0:
+ continue
+ if qty > 0:
+ self.stack.add_stock(qty, rate)
+ total_qty += qty
+ else:
+ qty = abs(qty)
+ consumed = self.stack.remove_stock(qty)
+ self.assertAlmostEqual(qty, sum(q for q, _ in consumed), msg=f"incorrect consumption {consumed}")
+ total_qty -= qty
+ self.assertTotalQty(total_qty)
+
+ @given(stock_queue_generator)
+ def test_lifo_qty_value_nonneg_hypothesis(self, stock_stack):
+ self.stack = LIFOValuation([])
+ total_qty = 0.0
+ total_value = 0.0
+
+ for qty, rate in stock_stack:
+ # don't allow negative stock
+ if qty == 0 or total_qty + qty < 0 or abs(qty) < 0.1:
+ continue
+ if qty > 0:
+ self.stack.add_stock(qty, rate)
+ total_qty += qty
+ total_value += qty * rate
+ else:
+ qty = abs(qty)
+ consumed = self.stack.remove_stock(qty)
+ self.assertAlmostEqual(qty, sum(q for q, _ in consumed), msg=f"incorrect consumption {consumed}")
+ total_qty -= qty
+ total_value -= sum(q * r for q, r in consumed)
+ self.assertTotalQty(total_qty)
+ self.assertTotalValue(total_value)
+
+class TestLIFOValuationSLE(FrappeTestCase):
+ ITEM_CODE = "_Test LIFO item"
+ WAREHOUSE = "_Test Warehouse - _TC"
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ super().setUpClass()
+ make_item(cls.ITEM_CODE, {"valuation_method": "LIFO"})
+
+ def _make_stock_entry(self, qty, rate=None):
+ kwargs = {
+ "item_code": self.ITEM_CODE,
+ "from_warehouse" if qty < 0 else "to_warehouse": self.WAREHOUSE,
+ "rate": rate,
+ "qty": abs(qty),
+ }
+ return make_stock_entry(**kwargs)
+
+ def assertStockQueue(self, se, expected_queue):
+ sle_name = frappe.db.get_value("Stock Ledger Entry", {"voucher_no": se.name, "is_cancelled": 0, "voucher_type": "Stock Entry"})
+ sle = frappe.get_doc("Stock Ledger Entry", sle_name)
+
+ stock_queue = json.loads(sle.stock_queue)
+
+ total_qty, total_value = LIFOValuation(stock_queue).get_total_stock_and_value()
+ self.assertEqual(sle.qty_after_transaction, total_qty)
+ self.assertEqual(sle.stock_value, total_value)
+
+ if total_qty > 0:
+ self.assertEqual(stock_queue, expected_queue)
+
+
+ def test_lifo_values(self):
+
+ in1 = self._make_stock_entry(1, 1)
+ self.assertStockQueue(in1, [[1, 1]])
+
+ in2 = self._make_stock_entry(2, 2)
+ self.assertStockQueue(in2, [[1, 1], [2, 2]])
+
+ out1 = self._make_stock_entry(-1)
+ self.assertStockQueue(out1, [[1, 1], [1, 2]])
+
+ in3 = self._make_stock_entry(3, 3)
+ self.assertStockQueue(in3, [[1, 1], [1, 2], [3, 3]])
+
+ out2 = self._make_stock_entry(-4)
+ self.assertStockQueue(out2, [[1, 1]])
+
+ in4 = self._make_stock_entry(4, 4)
+ self.assertStockQueue(in4, [[1, 1], [4,4]])
+
+ out3 = self._make_stock_entry(-5)
+ self.assertStockQueue(out3, [])
+
+ in5 = self._make_stock_entry(5, 5)
+ self.assertStockQueue(in5, [[5, 5]])
+
+ out5 = self._make_stock_entry(-5)
+ self.assertStockQueue(out5, [])
diff --git a/erpnext/stock/utils.py b/erpnext/stock/utils.py
index 7c63c17..f85a04f 100644
--- a/erpnext/stock/utils.py
+++ b/erpnext/stock/utils.py
@@ -9,6 +9,7 @@
from frappe.utils import cstr, flt, get_link_to_form, nowdate, nowtime
import erpnext
+from erpnext.stock.valuation import FIFOValuation, LIFOValuation
class InvalidWarehouseCompany(frappe.ValidationError): pass
@@ -205,42 +206,46 @@
return bin_obj
-def update_bin(args, allow_negative_stock=False, via_landed_cost_voucher=False):
- """WARNING: This function is deprecated. Inline this function instead of using it."""
- from erpnext.stock.doctype.bin.bin import update_stock
- is_stock_item = frappe.get_cached_value('Item', args.get("item_code"), 'is_stock_item')
- if is_stock_item:
- bin_name = get_or_make_bin(args.get("item_code"), args.get("warehouse"))
- update_stock(bin_name, args, allow_negative_stock, via_landed_cost_voucher)
- else:
- frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
-
@frappe.whitelist()
def get_incoming_rate(args, raise_error_if_no_rate=True):
"""Get Incoming Rate based on valuation method"""
- from erpnext.stock.stock_ledger import get_previous_sle, get_valuation_rate
+ from erpnext.stock.stock_ledger import (
+ get_batch_incoming_rate,
+ get_previous_sle,
+ get_valuation_rate,
+ )
if isinstance(args, str):
args = json.loads(args)
- in_rate = 0
+ voucher_no = args.get('voucher_no') or args.get('name')
+
+ in_rate = None
if (args.get("serial_no") or "").strip():
in_rate = get_avg_purchase_rate(args.get("serial_no"))
+ elif args.get("batch_no") and \
+ frappe.db.get_value("Batch", args.get("batch_no"), "use_batchwise_valuation", cache=True):
+ in_rate = get_batch_incoming_rate(
+ item_code=args.get('item_code'),
+ warehouse=args.get('warehouse'),
+ batch_no=args.get("batch_no"),
+ posting_date=args.get("posting_date"),
+ posting_time=args.get("posting_time"),
+ )
else:
valuation_method = get_valuation_method(args.get("item_code"))
previous_sle = get_previous_sle(args)
- if valuation_method == 'FIFO':
+ if valuation_method in ('FIFO', 'LIFO'):
if previous_sle:
previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
- in_rate = get_fifo_rate(previous_stock_queue, args.get("qty") or 0) if previous_stock_queue else 0
+ in_rate = _get_fifo_lifo_rate(previous_stock_queue, args.get("qty") or 0, valuation_method) if previous_stock_queue else 0
elif valuation_method == 'Moving Average':
in_rate = previous_sle.get('valuation_rate') or 0
- if not in_rate:
- voucher_no = args.get('voucher_no') or args.get('name')
+ if in_rate is None:
in_rate = get_valuation_rate(args.get('item_code'), args.get('warehouse'),
args.get('voucher_type'), voucher_no, args.get('allow_zero_valuation'),
currency=erpnext.get_company_currency(args.get('company')), company=args.get('company'),
- raise_error_if_no_rate=raise_error_if_no_rate)
+ raise_error_if_no_rate=raise_error_if_no_rate, batch_no=args.get("batch_no"))
return flt(in_rate)
@@ -256,34 +261,30 @@
"""get valuation method from item or default"""
val_method = frappe.db.get_value('Item', item_code, 'valuation_method', cache=True)
if not val_method:
- val_method = frappe.db.get_value("Stock Settings", None, "valuation_method") or "FIFO"
+ val_method = frappe.db.get_value("Stock Settings", None, "valuation_method", cache=True) or "FIFO"
return val_method
def get_fifo_rate(previous_stock_queue, qty):
"""get FIFO (average) Rate from Queue"""
- if flt(qty) >= 0:
- total = sum(f[0] for f in previous_stock_queue)
- return sum(flt(f[0]) * flt(f[1]) for f in previous_stock_queue) / flt(total) if total else 0.0
- else:
- available_qty_for_outgoing, outgoing_cost = 0, 0
- qty_to_pop = abs(flt(qty))
- while qty_to_pop and previous_stock_queue:
- batch = previous_stock_queue[0]
- if 0 < batch[0] <= qty_to_pop:
- # if batch qty > 0
- # not enough or exactly same qty in current batch, clear batch
- available_qty_for_outgoing += flt(batch[0])
- outgoing_cost += flt(batch[0]) * flt(batch[1])
- qty_to_pop -= batch[0]
- previous_stock_queue.pop(0)
- else:
- # all from current batch
- available_qty_for_outgoing += flt(qty_to_pop)
- outgoing_cost += flt(qty_to_pop) * flt(batch[1])
- batch[0] -= qty_to_pop
- qty_to_pop = 0
+ return _get_fifo_lifo_rate(previous_stock_queue, qty, "FIFO")
- return outgoing_cost / available_qty_for_outgoing
+def get_lifo_rate(previous_stock_queue, qty):
+ """get LIFO (average) Rate from Queue"""
+ return _get_fifo_lifo_rate(previous_stock_queue, qty, "LIFO")
+
+
+def _get_fifo_lifo_rate(previous_stock_queue, qty, method):
+ ValuationKlass = LIFOValuation if method == "LIFO" else FIFOValuation
+
+ stock_queue = ValuationKlass(previous_stock_queue)
+ if flt(qty) >= 0:
+ total_qty, total_value = stock_queue.get_total_stock_and_value()
+ return total_value / total_qty if total_qty else 0.0
+ else:
+ popped_bins = stock_queue.remove_stock(abs(flt(qty)))
+
+ total_qty, total_value = ValuationKlass(popped_bins).get_total_stock_and_value()
+ return total_value / total_qty if total_qty else 0.0
def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
"""split serial nos, validate and return list of valid serial nos"""
diff --git a/erpnext/stock/valuation.py b/erpnext/stock/valuation.py
index 45c5083..e2bd1ad 100644
--- a/erpnext/stock/valuation.py
+++ b/erpnext/stock/valuation.py
@@ -1,15 +1,54 @@
+from abc import ABC, abstractmethod, abstractproperty
from typing import Callable, List, NewType, Optional, Tuple
from frappe.utils import flt
-FifoBin = NewType("FifoBin", List[float])
+StockBin = NewType("StockBin", List[float]) # [[qty, rate], ...]
# Indexes of values inside FIFO bin 2-tuple
QTY = 0
RATE = 1
-class FIFOValuation:
+class BinWiseValuation(ABC):
+
+ @abstractmethod
+ def add_stock(self, qty: float, rate: float) -> None:
+ pass
+
+ @abstractmethod
+ def remove_stock(
+ self, qty: float, outgoing_rate: float = 0.0, rate_generator: Callable[[], float] = None
+ ) -> List[StockBin]:
+ pass
+
+ @abstractproperty
+ def state(self) -> List[StockBin]:
+ pass
+
+ def get_total_stock_and_value(self) -> Tuple[float, float]:
+ total_qty = 0.0
+ total_value = 0.0
+
+ for qty, rate in self.state:
+ total_qty += flt(qty)
+ total_value += flt(qty) * flt(rate)
+
+ return round_off_if_near_zero(total_qty), round_off_if_near_zero(total_value)
+
+ def __repr__(self):
+ return str(self.state)
+
+ def __iter__(self):
+ return iter(self.state)
+
+ def __eq__(self, other):
+ if isinstance(other, list):
+ return self.state == other
+ return type(self) == type(other) and self.state == other.state
+
+
+class FIFOValuation(BinWiseValuation):
"""Valuation method where a queue of all the incoming stock is maintained.
New stock is added at end of the queue.
@@ -24,34 +63,14 @@
# ref: https://docs.python.org/3/reference/datamodel.html#slots
__slots__ = ["queue",]
- def __init__(self, state: Optional[List[FifoBin]]):
- self.queue: List[FifoBin] = state if state is not None else []
+ def __init__(self, state: Optional[List[StockBin]]):
+ self.queue: List[StockBin] = state if state is not None else []
- def __repr__(self):
- return str(self.queue)
-
- def __iter__(self):
- return iter(self.queue)
-
- def __eq__(self, other):
- if isinstance(other, list):
- return self.queue == other
- return self.queue == other.queue
-
- def get_state(self) -> List[FifoBin]:
+ @property
+ def state(self) -> List[StockBin]:
"""Get current state of queue."""
return self.queue
- def get_total_stock_and_value(self) -> Tuple[float, float]:
- total_qty = 0.0
- total_value = 0.0
-
- for qty, rate in self.queue:
- total_qty += flt(qty)
- total_value += flt(qty) * flt(rate)
-
- return _round_off_if_near_zero(total_qty), _round_off_if_near_zero(total_value)
-
def add_stock(self, qty: float, rate: float) -> None:
"""Update fifo queue with new stock.
@@ -78,7 +97,7 @@
def remove_stock(
self, qty: float, outgoing_rate: float = 0.0, rate_generator: Callable[[], float] = None
- ) -> List[FifoBin]:
+ ) -> List[StockBin]:
"""Remove stock from the queue and return popped bins.
args:
@@ -117,7 +136,7 @@
fifo_bin = self.queue[index]
if qty >= fifo_bin[QTY]:
# consume current bin
- qty = _round_off_if_near_zero(qty - fifo_bin[QTY])
+ qty = round_off_if_near_zero(qty - fifo_bin[QTY])
to_consume = self.queue.pop(index)
consumed_bins.append(list(to_consume))
@@ -129,14 +148,109 @@
break
else:
# qty found in current bin consume it and exit
- fifo_bin[QTY] = _round_off_if_near_zero(fifo_bin[QTY] - qty)
+ fifo_bin[QTY] = round_off_if_near_zero(fifo_bin[QTY] - qty)
consumed_bins.append([qty, fifo_bin[RATE]])
qty = 0
return consumed_bins
-def _round_off_if_near_zero(number: float, precision: int = 7) -> float:
+class LIFOValuation(BinWiseValuation):
+ """Valuation method where a *stack* of all the incoming stock is maintained.
+
+ New stock is added at top of the stack.
+ Qty consumption happens on Last In First Out basis.
+
+ Stack is implemented using "bins" of [qty, rate].
+
+ ref: https://en.wikipedia.org/wiki/FIFO_and_LIFO_accounting
+ Implementation detail: appends and pops both at end of list.
+ """
+
+ # specifying the attributes to save resources
+ # ref: https://docs.python.org/3/reference/datamodel.html#slots
+ __slots__ = ["stack",]
+
+ def __init__(self, state: Optional[List[StockBin]]):
+ self.stack: List[StockBin] = state if state is not None else []
+
+ @property
+ def state(self) -> List[StockBin]:
+ """Get current state of stack."""
+ return self.stack
+
+ def add_stock(self, qty: float, rate: float) -> None:
+ """Update lifo stack with new stock.
+
+ args:
+ qty: new quantity to add
+ rate: incoming rate of new quantity.
+
+ Behaviour of this is same as FIFO valuation.
+ """
+ if not len(self.stack):
+ self.stack.append([0, 0])
+
+ # last row has the same rate, merge new bin.
+ if self.stack[-1][RATE] == rate:
+ self.stack[-1][QTY] += qty
+ else:
+ # Item has a positive balance qty, add new entry
+ if self.stack[-1][QTY] > 0:
+ self.stack.append([qty, rate])
+ else: # negative balance qty
+ qty = self.stack[-1][QTY] + qty
+ if qty > 0: # new balance qty is positive
+ self.stack[-1] = [qty, rate]
+ else: # new balance qty is still negative, maintain same rate
+ self.stack[-1][QTY] = qty
+
+
+ def remove_stock(
+ self, qty: float, outgoing_rate: float = 0.0, rate_generator: Callable[[], float] = None
+ ) -> List[StockBin]:
+ """Remove stock from the stack and return popped bins.
+
+ args:
+ qty: quantity to remove
+ rate: outgoing rate - ignored. Kept for backwards compatibility.
+ rate_generator: function to be called if stack is not found and rate is required.
+ """
+ if not rate_generator:
+ rate_generator = lambda : 0.0 # noqa
+
+ consumed_bins = []
+ while qty:
+ if not len(self.stack):
+ # rely on rate generator.
+ self.stack.append([0, rate_generator()])
+
+ # start at the end.
+ index = -1
+
+ stock_bin = self.stack[index]
+ if qty >= stock_bin[QTY]:
+ # consume current bin
+ qty = round_off_if_near_zero(qty - stock_bin[QTY])
+ to_consume = self.stack.pop(index)
+ consumed_bins.append(list(to_consume))
+
+ if not self.stack and qty:
+ # stock finished, qty still remains to be withdrawn
+ # negative stock, keep in as a negative bin
+ self.stack.append([-qty, outgoing_rate or stock_bin[RATE]])
+ consumed_bins.append([qty, outgoing_rate or stock_bin[RATE]])
+ break
+ else:
+ # qty found in current bin consume it and exit
+ stock_bin[QTY] = round_off_if_near_zero(stock_bin[QTY] - qty)
+ consumed_bins.append([qty, stock_bin[RATE]])
+ qty = 0
+
+ return consumed_bins
+
+
+def round_off_if_near_zero(number: float, precision: int = 7) -> float:
"""Rounds off the number to zero only if number is close to zero for decimal
specified in precision. Precision defaults to 7.
"""
diff --git a/erpnext/templates/includes/footer/footer_powered.html b/erpnext/templates/includes/footer/footer_powered.html
index 82b2716..faf5e92 100644
--- a/erpnext/templates/includes/footer/footer_powered.html
+++ b/erpnext/templates/includes/footer/footer_powered.html
@@ -1,27 +1 @@
-{% set domains = frappe.get_doc("Domain Settings").active_domains %}
-{% set links = {
- 'Manufacturing': '/manufacturing',
- 'Services': '/services',
- 'Retail': '/retail',
- 'Distribution': '/distribution',
- 'Non Profit': '/non-profit',
- 'Education': '/education',
- 'Healthcare': '/healthcare',
- 'Agriculture': '/agriculture',
- 'Hospitality': ''
-} %}
-
-{% set link = '' %}
-{% set label = '' %}
-{% if domains %}
- {% set label = domains[0].domain %}
- {% set link = links[label] %}
-{% endif %}
-
-{% if label == "Services" %}
- {% set label = "Service" %}
-{% endif %}
-
-
-
-<a href="https://erpnext.com{{ link }}?source=website_footer" target="_blank" class="text-muted">Powered by ERPNext - {{ '' if domains else 'Open Source' }} ERP Software {{ ('for ' + label + ' Companies') if domains else '' }}</a>
+<a href="https://erpnext.com?source=website_footer" target="_blank" class="text-muted">Powered by ERPNext</a>
diff --git a/erpnext/templates/includes/navbar/navbar_items.html b/erpnext/templates/includes/navbar/navbar_items.html
index 3275521..d7adae5 100644
--- a/erpnext/templates/includes/navbar/navbar_items.html
+++ b/erpnext/templates/includes/navbar/navbar_items.html
@@ -13,7 +13,7 @@
<li class="wishlist wishlist-icon hidden">
<a class="nav-link" href="/wishlist">
<svg class="icon icon-lg">
- <use href="#icon-heart-active"></use>
+ <use href="#icon-heart"></use>
</svg>
<span class="badge badge-primary shopping-badge" id="wish-count"></span>
</a>
diff --git a/erpnext/templates/pages/non_profit/join-chapter.html b/erpnext/templates/pages/non_profit/join-chapter.html
deleted file mode 100644
index 4923efc..0000000
--- a/erpnext/templates/pages/non_profit/join-chapter.html
+++ /dev/null
@@ -1,59 +0,0 @@
-{% extends "templates/web.html" %}
-
-{% block page_content %}
-
-{% macro chapter_button() %}
- <p><a href="/{{ chapter.route }}" class='btn btn-primary'>
- Go to Chapter Page</a></p>
-{% endmacro %}
-{% if frappe.session.user=='Guest' %}
- <p>Please signup and login to join this chapter</p>
- <p><a href="/login?redirect-to=/{{ chapter.route }}" class='btn btn-primary'>Login</a></p>
-{% else %}
- {% if already_member %}
- <p>You are already a member of {{ chapter.name }}!</p>
- {{ chapter_button() }}
- <p><a href="">Leave Chapter</a></p>
- {% else %}
- {% if request.method=='POST' %}
- <p>Welcome to chapter {{ chapter.name }}!</p>
- {{ chapter_button() }}
- {% else %}
- <div style="padding: 20px 0;">
- <div class="row">
- <div class="col-lg-8 col-md-8">
- <form name="user-intro" action="/non_profit/join-chapter" method='POST'>
- <div class="form-group">
- <input name="name" class="hidden form-control" type="text"
- value="{{chapter.name}}">
- <input name="csrf_token" class="hidden form-control" type="text"
- value="{{frappe.session.csrf_token}}">
- </div>
- <div class="form-group">
- <label for="user" class="">User Name</label>
- <input name="user" class="form-control" type="text" value="{{ frappe.session.user }}">
- </div>
- <div class="form-group">
- <label for="website_url" class="">Website URL</label>
- <input name="website_url" required class="form-control" type="text"
- placeholder="https://example.com" />
- </div>
- <div class="form-group">
- <label for="introduction" class="">Introduction</label>
- <textarea name="introduction" required class="form-control"
- placeholder="Your profession and how you are associated with ERPNext"></textarea>
- </div>
- <div class="form-group">
- <button type="Submit" id="update_member" class="btn btn-primary">
- Submit</button>
- </div>
- </form>
- </div>
- </div>
- </div>
- {% endif %}
- {% endif %}
-
-{% endif %}
-
-{% endblock %}
diff --git a/erpnext/templates/pages/non_profit/join_chapter.js b/erpnext/templates/pages/non_profit/join_chapter.js
deleted file mode 100644
index e2bc8bc..0000000
--- a/erpnext/templates/pages/non_profit/join_chapter.js
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright (c) 2017, EOSSF and contributors
-// For license information, please see license.txt
-
-frappe.ui.form.on('Chapter Member', {
- onsubmit: function (frm) {
- console.log("here" + frappe.session.user)
- // body...
- }
- refresh: function(frm) {
-
- }
-});
diff --git a/erpnext/templates/pages/non_profit/join_chapter.py b/erpnext/templates/pages/non_profit/join_chapter.py
deleted file mode 100644
index 7caf87d..0000000
--- a/erpnext/templates/pages/non_profit/join_chapter.py
+++ /dev/null
@@ -1,23 +0,0 @@
-import frappe
-
-
-def get_context(context):
- context.no_cache = True
- chapter = frappe.get_doc('Chapter', frappe.form_dict.name)
- if frappe.session.user!='Guest':
- if frappe.session.user in [d.user for d in chapter.members if d.enabled == 1]:
- context.already_member = True
- else:
- if frappe.request.method=='GET':
- pass
- elif frappe.request.method=='POST':
- chapter.append('members', dict(
- user=frappe.session.user,
- introduction=frappe.form_dict.introduction,
- website_url=frappe.form_dict.website_url,
- enabled=1
- ))
- chapter.save(ignore_permissions=1)
- frappe.db.commit()
-
- context.chapter = chapter
diff --git a/erpnext/templates/pages/non_profit/leave-chapter.html b/erpnext/templates/pages/non_profit/leave-chapter.html
deleted file mode 100644
index fd7658b..0000000
--- a/erpnext/templates/pages/non_profit/leave-chapter.html
+++ /dev/null
@@ -1,42 +0,0 @@
-{% extends "templates/web.html" %}
-{% block page_content %}
-
- {% if member_deleted %}
- <p>You are not a member of {{ chapter.name }}!</p>
- <div>
- <form>
- <div class="form-group">
- <label for="leave">Why do you want to leave this chapter</label>
- <input type="text" name="leave" class="form-control" id="leave">
- </div>
- <button type="button" class="btn btn-light btn-leave" data-title= "{{ chapter.name }}" id="btn-leave">Submit
- </button>
- </form>
- </div>
- <p>Please signup and login to join this chapter</p>
-
- <p><a href="/join-chapter?name={{ chapter.name }}" class='btn btn-primary'>Become Member agian</a></p>
- {% endif %}
- <script>
- frappe.ready(function() {
- $(".btn-leave").on("click", function() {
- var leave = $("#leave").val();
- var user_id = frappe.session.user;
- var title = $(this).attr("data-title");
- frappe.call({
- method: "erpnext.non_profit.doctype.chapter.chapter.leave",
- args: {
- leave_reason: leave,
- user_id: user_id,
- title: title
- },
- callback: function(r) {
- if(r.message) {
- frappe.msgprint(r.message)
- }
- }
- })
- });
- })
- </script>
-{% endblock %}
diff --git a/erpnext/templates/pages/non_profit/leave_chapter.py b/erpnext/templates/pages/non_profit/leave_chapter.py
deleted file mode 100644
index 65908e1..0000000
--- a/erpnext/templates/pages/non_profit/leave_chapter.py
+++ /dev/null
@@ -1,8 +0,0 @@
-import frappe
-
-
-def get_context(context):
- context.no_cache = True
- chapter = frappe.get_doc('Chapter', frappe.form_dict.name)
- context.member_deleted = True
- context.chapter = chapter
diff --git a/erpnext/tests/test_point_of_sale.py b/erpnext/tests/test_point_of_sale.py
index df2dc8b..38f2c16 100644
--- a/erpnext/tests/test_point_of_sale.py
+++ b/erpnext/tests/test_point_of_sale.py
@@ -1,21 +1,31 @@
# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
+import unittest
+
+import frappe
from erpnext.accounts.doctype.pos_profile.test_pos_profile import make_pos_profile
from erpnext.selling.page.point_of_sale.point_of_sale import get_items
from erpnext.stock.doctype.item.test_item import make_item
from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
-from erpnext.tests.utils import ERPNextTestCase
-class TestPointOfSale(ERPNextTestCase):
+class TestPointOfSale(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ frappe.db.savepoint('before_test_point_of_sale')
+
+ @classmethod
+ def tearDownClass(cls) -> None:
+ frappe.db.rollback(save_point='before_test_point_of_sale')
+
def test_item_search(self):
"""
Test Stock and Service Item Search.
"""
- pos_profile = make_pos_profile()
+ pos_profile = make_pos_profile(name="Test POS Profile for Search")
item1 = make_item("Test Search Stock Item", {"is_stock_item": 1})
make_stock_entry(
item_code="Test Search Stock Item",
diff --git a/erpnext/tests/test_zform_loads.py b/erpnext/tests/test_zform_loads.py
new file mode 100644
index 0000000..b6fb636
--- /dev/null
+++ b/erpnext/tests/test_zform_loads.py
@@ -0,0 +1,30 @@
+""" dumb test to check all function calls on known form loads """
+
+import unittest
+
+import frappe
+from frappe.desk.form.load import getdoc
+
+
+class TestFormLoads(unittest.TestCase):
+
+ def test_load(self):
+ erpnext_modules = frappe.get_all("Module Def", filters={"app_name": "erpnext"}, pluck="name")
+ doctypes = frappe.get_all("DocType", {"istable": 0, "issingle": 0, "is_virtual": 0, "module": ("in", erpnext_modules)}, pluck="name")
+
+ for doctype in doctypes:
+ last_doc = frappe.db.get_value(doctype, {}, "name", order_by="modified desc")
+ if not last_doc:
+ continue
+ with self.subTest(msg=f"Loading {doctype} - {last_doc}", doctype=doctype, last_doc=last_doc):
+ try:
+ # reset previous response
+ frappe.response = frappe._dict({"docs":[]})
+ frappe.response.docinfo = None
+
+ getdoc(doctype, last_doc)
+ except Exception as e:
+ self.fail(f"Failed to load {doctype} - {last_doc}: {e}")
+
+ self.assertTrue(frappe.response.docs, msg=f"expected document in reponse, found: {frappe.response.docs}")
+ self.assertTrue(frappe.response.docinfo, msg=f"expected docinfo in reponse, found: {frappe.response.docinfo}")
diff --git a/erpnext/tests/ui_test_bulk_transaction_processing.py b/erpnext/tests/ui_test_bulk_transaction_processing.py
new file mode 100644
index 0000000..d78689e
--- /dev/null
+++ b/erpnext/tests/ui_test_bulk_transaction_processing.py
@@ -0,0 +1,21 @@
+import frappe
+
+from erpnext.bulk_transaction.doctype.bulk_transaction_logger.test_bulk_transaction_logger import (
+ create_company,
+ create_customer,
+ create_item,
+ create_so,
+)
+
+
+@frappe.whitelist()
+def create_records():
+ create_company()
+ create_customer()
+ create_item()
+
+ gd = frappe.get_doc("Global Defaults")
+ gd.set("default_company", "Test Bulk")
+ gd.save()
+ frappe.clear_cache()
+ create_so()
\ No newline at end of file
diff --git a/erpnext/tests/utils.py b/erpnext/tests/utils.py
index 2bd7e9e..d795253 100644
--- a/erpnext/tests/utils.py
+++ b/erpnext/tests/utils.py
@@ -1,10 +1,6 @@
# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
-import copy
-import signal
-import unittest
-from contextlib import contextmanager
from typing import Any, Dict, NewType, Optional
import frappe
@@ -13,22 +9,6 @@
ReportFilters = Dict[str, Any]
ReportName = NewType("ReportName", str)
-
-class ERPNextTestCase(unittest.TestCase):
- """A sane default test class for ERPNext tests."""
-
-
- @classmethod
- def setUpClass(cls) -> None:
- frappe.db.commit()
- return super().setUpClass()
-
- @classmethod
- def tearDownClass(cls) -> None:
- frappe.db.rollback()
- return super().tearDownClass()
-
-
def create_test_contact_and_address():
frappe.db.sql('delete from tabContact')
frappe.db.sql('delete from `tabContact Email`')
@@ -66,42 +46,19 @@
contact.add_phone("+91 0000000000", is_primary_phone=True)
contact.insert()
-
-@contextmanager
-def change_settings(doctype, settings_dict):
- """ A context manager to ensure that settings are changed before running
- function and restored after running it regardless of exceptions occured.
- This is useful in tests where you want to make changes in a function but
- don't retain those changes.
- import and use as decorator to cover full function or using `with` statement.
-
- example:
- @change_settings("Stock Settings", {"item_naming_by": "Naming Series"})
- def test_case(self):
- ...
- """
-
- try:
- settings = frappe.get_doc(doctype)
- # remember setting
- previous_settings = copy.deepcopy(settings_dict)
- for key in previous_settings:
- previous_settings[key] = getattr(settings, key)
-
- # change setting
- for key, value in settings_dict.items():
- setattr(settings, key, value)
- settings.save()
- # singles are cached by default, clear to avoid flake
- frappe.db.value_cache[settings] = {}
- yield # yield control to calling function
-
- finally:
- # restore settings
- settings = frappe.get_doc(doctype)
- for key, value in previous_settings.items():
- setattr(settings, key, value)
- settings.save()
+ contact_two = frappe.get_doc({
+ "doctype": 'Contact',
+ "first_name": "_Test Contact 2 for _Test Customer",
+ "links": [
+ {
+ "link_doctype": "Customer",
+ "link_name": "_Test Customer"
+ }
+ ]
+ })
+ contact_two.add_email("test_contact_two_customer@example.com", is_primary=True)
+ contact_two.add_phone("+92 0000000000", is_primary_phone=True)
+ contact_two.insert()
def execute_script_report(
@@ -143,24 +100,3 @@
except Exception:
print(f"Report failed to execute with filters: {test_filter}")
raise
-
-
-
-def timeout(seconds=30, error_message="Test timed out."):
- """ Timeout decorator to ensure a test doesn't run for too long.
-
- adapted from https://stackoverflow.com/a/2282656"""
- def decorator(func):
- def _handle_timeout(signum, frame):
- raise Exception(error_message)
-
- def wrapper(*args, **kwargs):
- signal.signal(signal.SIGALRM, _handle_timeout)
- signal.alarm(seconds)
- try:
- result = func(*args, **kwargs)
- finally:
- signal.alarm(0)
- return result
- return wrapper
- return decorator
diff --git a/erpnext/translations/de.csv b/erpnext/translations/de.csv
index 4a6c834..b882b9d 100644
--- a/erpnext/translations/de.csv
+++ b/erpnext/translations/de.csv
@@ -913,6 +913,7 @@
Email Address,E-Mail-Adresse,
"Email Address must be unique, already exists for {0}","E-Mail-Adresse muss eindeutig sein, diese wird bereits für {0} verwendet",
Email Digest: ,E-Mail-Bericht:,
+Email Digest Recipient,E-Mail-Berichtsempfänger,
Email Reminders will be sent to all parties with email contacts,E-Mail-Erinnerungen werden an alle Parteien mit E-Mail-Kontakten gesendet,
Email Sent,E-Mail wurde versandt,
Email Template,E-Mail-Vorlage,
@@ -1596,6 +1597,7 @@
Middle Income,Mittleres Einkommen,
Middle Name,Zweiter Vorname,
Middle Name (Optional),Weiterer Vorname (optional),
+Milestonde,Meilenstein,
Min Amt can not be greater than Max Amt,Min. Amt kann nicht größer als Max. Amt sein,
Min Qty can not be greater than Max Qty,Mindestmenge kann nicht größer als Maximalmenge sein,
Minimum Lead Age (Days),Mindest Lead-Alter (in Tagen),
@@ -2944,7 +2946,7 @@
Temporary Opening,Temporäre Eröffnungskonten,
Terms and Conditions,Allgemeine Geschäftsbedingungen,
Terms and Conditions Template,Vorlage für Allgemeine Geschäftsbedingungen,
-Territory,Region,
+Territory,Gebiet,
Test,Test,
Thank you,Danke,
Thank you for your business!,Vielen Dank für Ihr Unternehmen!,
@@ -3729,7 +3731,7 @@
Edit Details,Details bearbeiten,
Edit Profile,Profil bearbeiten,
Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road,Bei Straßentransport ist entweder die GST-Transporter-ID oder die Fahrzeug-Nr. Erforderlich,
-Email,Email,
+Email,E-Mail,
Email Campaigns,E-Mail-Kampagnen,
Employee ID is linked with another instructor,Die Mitarbeiter-ID ist mit einem anderen Ausbilder verknüpft,
Employee Tax and Benefits,Mitarbeitersteuern und -leistungen,
@@ -6485,7 +6487,7 @@
Send Emails At,Die E-Mails senden um,
Reminder,Erinnerung,
Daily Work Summary Group User,Tägliche Arbeit Zusammenfassung Gruppenbenutzer,
-email,Email,
+email,E-Mail,
Parent Department,Elternabteilung,
Leave Block List,Urlaubssperrenliste,
Days for which Holidays are blocked for this department.,"Tage, an denen eine Urlaubssperre für diese Abteilung gilt.",
diff --git a/erpnext/utilities/bulk_transaction.py b/erpnext/utilities/bulk_transaction.py
new file mode 100644
index 0000000..64e2ff4
--- /dev/null
+++ b/erpnext/utilities/bulk_transaction.py
@@ -0,0 +1,201 @@
+import json
+from datetime import date, datetime
+
+import frappe
+from frappe import _
+
+
+@frappe.whitelist()
+def transaction_processing(data, from_doctype, to_doctype):
+ if isinstance(data, str):
+ deserialized_data = json.loads(data)
+
+ else:
+ deserialized_data = data
+
+ length_of_data = len(deserialized_data)
+
+ if length_of_data > 10:
+ frappe.msgprint(
+ _("Started a background job to create {1} {0}").format(to_doctype, length_of_data)
+ )
+ frappe.enqueue(
+ job,
+ deserialized_data=deserialized_data,
+ from_doctype=from_doctype,
+ to_doctype=to_doctype,
+ )
+ else:
+ job(deserialized_data, from_doctype, to_doctype)
+
+
+def job(deserialized_data, from_doctype, to_doctype):
+ failed_history = []
+ i = 0
+ for d in deserialized_data:
+ failed = []
+
+ try:
+ i += 1
+ doc_name = d.get("name")
+ frappe.db.savepoint("before_creation_state")
+ task(doc_name, from_doctype, to_doctype)
+
+ except Exception as e:
+ frappe.db.rollback(save_point="before_creation_state")
+ failed_history.append(e)
+ failed.append(e)
+ update_logger(doc_name, e, from_doctype, to_doctype, status="Failed", log_date=str(date.today()))
+ if not failed:
+ update_logger(doc_name, None, from_doctype, to_doctype, status="Success", log_date=str(date.today()))
+
+ show_job_status(failed_history, deserialized_data, to_doctype)
+
+
+def task(doc_name, from_doctype, to_doctype):
+ from erpnext.accounts.doctype.payment_entry import payment_entry
+ from erpnext.accounts.doctype.purchase_invoice import purchase_invoice
+ from erpnext.accounts.doctype.sales_invoice import sales_invoice
+ from erpnext.buying.doctype.purchase_order import purchase_order
+ from erpnext.buying.doctype.supplier_quotation import supplier_quotation
+ from erpnext.selling.doctype.quotation import quotation
+ from erpnext.selling.doctype.sales_order import sales_order
+ from erpnext.stock.doctype.delivery_note import delivery_note
+ from erpnext.stock.doctype.purchase_receipt import purchase_receipt
+
+ mapper = {
+ "Sales Order": {
+ "Sales Invoice": sales_order.make_sales_invoice,
+ "Delivery Note": sales_order.make_delivery_note,
+ "Advance Payment": payment_entry.get_payment_entry,
+ },
+ "Sales Invoice": {
+ "Delivery Note": sales_invoice.make_delivery_note,
+ "Payment": payment_entry.get_payment_entry,
+ },
+ "Delivery Note": {
+ "Sales Invoice": delivery_note.make_sales_invoice,
+ "Packing Slip": delivery_note.make_packing_slip,
+ },
+ "Quotation": {
+ "Sales Order": quotation.make_sales_order,
+ "Sales Invoice": quotation.make_sales_invoice,
+ },
+ "Supplier Quotation": {
+ "Purchase Order": supplier_quotation.make_purchase_order,
+ "Purchase Invoice": supplier_quotation.make_purchase_invoice,
+ "Advance Payment": payment_entry.get_payment_entry,
+ },
+ "Purchase Order": {
+ "Purchase Invoice": purchase_order.make_purchase_invoice,
+ "Purchase Receipt": purchase_order.make_purchase_receipt,
+ },
+ "Purhcase Invoice": {
+ "Purchase Receipt": purchase_invoice.make_purchase_receipt,
+ "Payment": payment_entry.get_payment_entry,
+ },
+ "Purchase Receipt": {"Purchase Invoice": purchase_receipt.make_purchase_invoice},
+ }
+ if to_doctype in ['Advance Payment', 'Payment']:
+ obj = mapper[from_doctype][to_doctype](from_doctype, doc_name)
+ else:
+ obj = mapper[from_doctype][to_doctype](doc_name)
+
+ obj.flags.ignore_validate = True
+ obj.insert(ignore_mandatory=True)
+
+
+def check_logger_doc_exists(log_date):
+ return frappe.db.exists("Bulk Transaction Log", log_date)
+
+
+def get_logger_doc(log_date):
+ return frappe.get_doc("Bulk Transaction Log", log_date)
+
+
+def create_logger_doc():
+ log_doc = frappe.new_doc("Bulk Transaction Log")
+ log_doc.set_new_name(set_name=str(date.today()))
+ log_doc.log_date = date.today()
+
+ return log_doc
+
+
+def append_data_to_logger(log_doc, doc_name, error, from_doctype, to_doctype, status, restarted):
+ row = log_doc.append("logger_data", {})
+ row.transaction_name = doc_name
+ row.date = date.today()
+ now = datetime.now()
+ row.time = now.strftime("%H:%M:%S")
+ row.transaction_status = status
+ row.error_description = str(error)
+ row.from_doctype = from_doctype
+ row.to_doctype = to_doctype
+ row.retried = restarted
+
+
+def update_logger(doc_name, e, from_doctype, to_doctype, status, log_date=None, restarted=0):
+ if not check_logger_doc_exists(log_date):
+ log_doc = create_logger_doc()
+ append_data_to_logger(log_doc, doc_name, e, from_doctype, to_doctype, status, restarted)
+ log_doc.insert()
+ else:
+ log_doc = get_logger_doc(log_date)
+ if record_exists(log_doc, doc_name, status):
+ append_data_to_logger(
+ log_doc, doc_name, e, from_doctype, to_doctype, status, restarted
+ )
+ log_doc.save()
+
+
+def show_job_status(failed_history, deserialized_data, to_doctype):
+ if not failed_history:
+ frappe.msgprint(
+ _("Creation of {0} successful").format(to_doctype),
+ title="Successful",
+ indicator="green",
+ )
+
+ if len(failed_history) != 0 and len(failed_history) < len(deserialized_data):
+ frappe.msgprint(
+ _("""Creation of {0} partially successful.
+ Check <b><a href="/app/bulk-transaction-log">Bulk Transaction Log</a></b>""").format(
+ to_doctype
+ ),
+ title="Partially successful",
+ indicator="orange",
+ )
+
+ if len(failed_history) == len(deserialized_data):
+ frappe.msgprint(
+ _("""Creation of {0} failed.
+ Check <b><a href="/app/bulk-transaction-log">Bulk Transaction Log</a></b>""").format(
+ to_doctype
+ ),
+ title="Failed",
+ indicator="red",
+ )
+
+
+def record_exists(log_doc, doc_name, status):
+
+ record = mark_retrired_transaction(log_doc, doc_name)
+
+ if record and status == "Failed":
+ return False
+ elif record and status == "Success":
+ return True
+ else:
+ return True
+
+
+def mark_retrired_transaction(log_doc, doc_name):
+ record = 0
+ for d in log_doc.get("logger_data"):
+ if d.transaction_name == doc_name and d.transaction_status == "Failed":
+ d.retried = 1
+ record = record + 1
+
+ log_doc.save()
+
+ return record
\ No newline at end of file
diff --git a/erpnext/utilities/doctype/rename_tool/rename_tool.js b/erpnext/utilities/doctype/rename_tool/rename_tool.js
index 7823055..5553e44 100644
--- a/erpnext/utilities/doctype/rename_tool/rename_tool.js
+++ b/erpnext/utilities/doctype/rename_tool/rename_tool.js
@@ -13,6 +13,12 @@
},
refresh: function(frm) {
frm.disable_save();
+
+ frm.get_field("file_to_rename").df.options = {
+ restrictions: {
+ allowed_file_types: [".csv"],
+ },
+ };
if (!frm.doc.file_to_rename) {
frm.get_field("rename_log").$wrapper.html("");
}
diff --git a/erpnext/www/lms/macros/hero.html b/erpnext/www/lms/macros/hero.html
index e72bfc8..95ba8f7 100644
--- a/erpnext/www/lms/macros/hero.html
+++ b/erpnext/www/lms/macros/hero.html
@@ -11,7 +11,7 @@
{% if frappe.session.user == 'Guest' %}
<a id="signup" class="btn btn-primary btn-lg" href="/login#signup">{{_('Sign Up')}}</a>
{% elif not has_access %}
- <button id="enroll" class="btn btn-primary btn-lg" onclick="enroll()" disabled>{{_('Enroll')}}</button>
+ <button id="enroll" class="btn btn-primary btn-lg" onclick="enroll()">{{_('Enroll')}}</button>
{% endif %}
</p>
</div>
@@ -20,34 +20,35 @@
<script type="text/javascript">
frappe.ready(() => {
btn = document.getElementById('enroll');
- if (btn) btn.disabled = false;
})
function enroll() {
let params = frappe.utils.get_query_params()
let btn = document.getElementById('enroll');
- btn.disbaled = true;
- btn.innerText = __('Enrolling...')
let opts = {
method: 'erpnext.education.utils.enroll_in_program',
args: {
program_name: params.program
- }
+ },
+ freeze: true,
+ freeze_message: __('Enrolling...')
}
frappe.call(opts).then(res => {
let success_dialog = new frappe.ui.Dialog({
title: __('Success'),
+ primary_action_label: __('View Program Content'),
+ primary_action: function() {
+ window.location.reload();
+ },
secondary_action: function() {
- window.location.reload()
+ window.location.reload();
}
})
- success_dialog.set_message(__('You have successfully enrolled for the program '));
- success_dialog.$message.show()
success_dialog.show();
- btn.disbaled = false;
+ success_dialog.set_message(__('You have successfully enrolled for the program '));
})
}
</script>
diff --git a/erpnext/www/shop-by-category/index.py b/erpnext/www/shop-by-category/index.py
index 3946212..09f97ba 100644
--- a/erpnext/www/shop-by-category/index.py
+++ b/erpnext/www/shop-by-category/index.py
@@ -62,8 +62,7 @@
"parent_item_group": "All Item Groups",
"show_in_website": 1
},
- fields=["name", "parent_item_group", "is_group", "image", "route"],
- as_dict=True
+ fields=["name", "parent_item_group", "is_group", "image", "route"]
)
else:
doctype = frappe.unscrub(category)
@@ -71,7 +70,7 @@
if frappe.get_meta(doctype, cached=True).get_field("image"):
fields += ["image"]
- categorical_data[category] = frappe.db.get_all(doctype, fields=fields, as_dict=True)
+ categorical_data[category] = frappe.db.get_all(doctype, fields=fields)
return categorical_data