Merge pull request #7094 from manassolanki/budget

[Enhancement] Budget Against Project #7036
This commit is contained in:
Nabin Hait 2016-12-08 13:52:33 +05:30 committed by GitHub
commit 72c5aec68b
7 changed files with 312 additions and 119 deletions

View File

@ -10,6 +10,14 @@ frappe.ui.form.on('Budget', {
}
}
})
frm.set_query("project", function() {
return {
filters: {
company: frm.doc.company
}
}
})
frm.set_query("account", "accounts", function() {
return {

View File

@ -15,47 +15,19 @@
"bold": 0,
"collapsible": 0,
"columns": 0,
"fieldname": "cost_center",
"fieldtype": "Link",
"default": "Cost Center",
"fieldname": "budget_against",
"fieldtype": "Select",
"hidden": 0,
"ignore_user_permissions": 0,
"ignore_xss_filter": 0,
"in_filter": 0,
"in_list_view": 0,
"in_standard_filter": 1,
"label": "Cost Center",
"label": "Budget Against",
"length": 0,
"no_copy": 0,
"options": "Cost Center",
"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_on_submit": 0,
"bold": 0,
"collapsible": 0,
"columns": 0,
"fieldname": "fiscal_year",
"fieldtype": "Link",
"hidden": 0,
"ignore_user_permissions": 0,
"ignore_xss_filter": 0,
"in_filter": 0,
"in_list_view": 0,
"in_standard_filter": 0,
"label": "Fiscal Year",
"length": 0,
"no_copy": 0,
"options": "Fiscal Year",
"options": "\nCost Center\nProject",
"permlevel": 0,
"precision": "",
"print_hide": 0,
@ -90,7 +62,96 @@
"print_hide": 0,
"print_hide_if_no_value": 0,
"read_only": 0,
"remember_last_selected_value": 1,
"remember_last_selected_value": 0,
"report_hide": 0,
"reqd": 1,
"search_index": 0,
"set_only_once": 0,
"unique": 0
},
{
"allow_on_submit": 0,
"bold": 0,
"collapsible": 0,
"columns": 0,
"depends_on": "eval:doc.budget_against == 'Cost Center'",
"fieldname": "cost_center",
"fieldtype": "Link",
"hidden": 0,
"ignore_user_permissions": 0,
"ignore_xss_filter": 0,
"in_filter": 0,
"in_list_view": 0,
"in_standard_filter": 1,
"label": "Cost Center",
"length": 0,
"no_copy": 0,
"options": "Cost Center",
"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_on_submit": 0,
"bold": 0,
"collapsible": 0,
"columns": 0,
"depends_on": "eval:doc.budget_against == 'Project'",
"fieldname": "project",
"fieldtype": "Link",
"hidden": 0,
"ignore_user_permissions": 0,
"ignore_xss_filter": 0,
"in_filter": 0,
"in_list_view": 0,
"in_standard_filter": 1,
"label": "Project",
"length": 0,
"no_copy": 0,
"options": "Project",
"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_on_submit": 0,
"bold": 0,
"collapsible": 0,
"columns": 0,
"fieldname": "fiscal_year",
"fieldtype": "Link",
"hidden": 0,
"ignore_user_permissions": 0,
"ignore_xss_filter": 0,
"in_filter": 0,
"in_list_view": 0,
"in_standard_filter": 0,
"label": "Fiscal Year",
"length": 0,
"no_copy": 0,
"options": "Fiscal Year",
"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,
@ -310,7 +371,7 @@
"issingle": 0,
"istable": 0,
"max_attachments": 0,
"modified": "2016-11-07 05:50:57.064961",
"modified": "2016-11-30 08:51:10.453935",
"modified_by": "Administrator",
"module": "Accounts",
"name": "Budget",

View File

@ -1,4 +1,4 @@
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
@ -14,20 +14,25 @@ class DuplicateBudgetError(frappe.ValidationError): pass
class Budget(Document):
def autoname(self):
self.name = make_autoname(self.cost_center + "/" + self.fiscal_year + "/.###")
self.name = make_autoname(self.get(frappe.scrub(self.budget_against))
+ "/" + self.fiscal_year + "/.###")
def validate(self):
if not self.get(frappe.scrub(self.budget_against)):
frappe.throw(_("{0} is mandatory").format(self.budget_against))
self.validate_duplicate()
self.validate_accounts()
def validate_duplicate(self):
existing_budget = frappe.db.get_value("Budget", {"cost_center": self.cost_center,
budget_against_field = frappe.scrub(self.budget_against)
budget_against = self.get(budget_against_field)
existing_budget = frappe.db.get_value("Budget", {budget_against_field: budget_against,
"fiscal_year": self.fiscal_year, "company": self.company,
"name": ["!=", self.name], "docstatus": ["!=", 2]})
if existing_budget:
frappe.throw(_("Another Budget record {0} already exists against {1} for fiscal year {2}")
.format(existing_budget, self.cost_center, self.fiscal_year), DuplicateBudgetError)
if existing_budget:
frappe.throw(_("Another Budget record '{0}' already exists against {1} '{2}' for fiscal year {3}")
.format(existing_budget, self.budget_against, budget_against, self.fiscal_year), DuplicateBudgetError)
def validate_accounts(self):
account_list = []
for d in self.get('accounts'):
@ -51,56 +56,104 @@ class Budget(Document):
def validate_expense_against_budget(args):
args = frappe._dict(args)
if not args.cost_center:
if not args.cost_center and not args.project:
return
if frappe.db.get_value("Account", {"name": args.account, "root_type": "Expense"}):
cc_lft, cc_rgt = frappe.db.get_value("Cost Center", args.cost_center, ["lft", "rgt"])
for budget_against in [args.project, args.cost_center]:
if budget_against \
and frappe.db.get_value("Account", {"name": args.account, "root_type": "Expense"}):
budget_records = frappe.db.sql("""
select ba.budget_amount, b.monthly_distribution, b.cost_center,
b.action_if_annual_budget_exceeded, b.action_if_accumulated_monthly_budget_exceeded
from `tabBudget` b, `tabBudget Account` ba
where
b.name=ba.parent and b.fiscal_year=%s and ba.account=%s and b.docstatus=1
and exists(select name from `tabCost Center` where lft<=%s and rgt>=%s and name=b.cost_center)
""", (args.fiscal_year, args.account, cc_lft, cc_rgt), as_dict=True)
if args.project:
condition = "and exists(select name from `tabProject` where name=b.project)"
args.budget_against_field = "Project"
elif args.cost_center:
cc_lft, cc_rgt = frappe.db.get_value("Cost Center", args.cost_center, ["lft", "rgt"])
condition = """and exists(select name from `tabCost Center`
where lft<=%s and rgt>=%s and name=b.cost_center)""" % (cc_lft, cc_rgt)
args.budget_against_field = "Cost Center"
args.budget_against = budget_against
for budget in budget_records:
if budget.budget_amount:
yearly_action = budget.action_if_annual_budget_exceeded
monthly_action = budget.action_if_accumulated_monthly_budget_exceeded
budget_records = frappe.db.sql("""
select
b.{budget_against_field}, ba.budget_amount, b.monthly_distribution,
b.action_if_annual_budget_exceeded,
b.action_if_accumulated_monthly_budget_exceeded
from
`tabBudget` b, `tabBudget Account` ba
where
b.name=ba.parent and b.fiscal_year=%s
and ba.account=%s and b.docstatus=1
{condition}
""".format(condition=condition,
budget_against_field=frappe.scrub(args.get("budget_against_field"))),
(args.fiscal_year, args.account), as_dict=True)
if monthly_action in ["Stop", "Warn"]:
budget_amount = get_accumulated_monthly_budget(budget.monthly_distribution,
args.posting_date, args.fiscal_year, budget.budget_amount)
validate_budget_records(args, budget_records)
args["month_end_date"] = get_last_day(args.posting_date)
compare_expense_with_budget(args, budget.cost_center,
budget_amount, _("Accumulated Monthly"), monthly_action)
def validate_budget_records(args, budget_records):
for budget in budget_records:
if budget.budget_amount:
yearly_action = budget.action_if_annual_budget_exceeded
monthly_action = budget.action_if_accumulated_monthly_budget_exceeded
if yearly_action in ("Stop", "Warn") and monthly_action != "Stop" \
and yearly_action != monthly_action:
compare_expense_with_budget(args, budget.cost_center,
flt(budget.budget_amount), _("Annual"), yearly_action)
if monthly_action in ["Stop", "Warn"]:
budget_amount = get_accumulated_monthly_budget(budget.monthly_distribution,
args.posting_date, args.fiscal_year, budget.budget_amount)
args["month_end_date"] = get_last_day(args.posting_date)
def compare_expense_with_budget(args, cost_center, budget_amount, action_for, action):
actual_expense = get_actual_expense(args, cost_center)
compare_expense_with_budget(args, budget_amount,
_("Accumulated Monthly"), monthly_action)
if yearly_action in ("Stop", "Warn") and monthly_action != "Stop" \
and yearly_action != monthly_action:
compare_expense_with_budget(args, flt(budget.budget_amount),
_("Annual"), yearly_action)
def compare_expense_with_budget(args, budget_amount, action_for, action):
actual_expense = get_actual_expense(args)
if actual_expense > budget_amount:
diff = actual_expense - budget_amount
currency = frappe.db.get_value('Company', frappe.db.get_value('Cost Center',
cost_center, 'company'), 'default_currency')
currency = frappe.db.get_value('Company', args.company, 'default_currency')
msg = _("{0} Budget for Account {1} against Cost Center {2} is {3}. It will exceed by {4}").format(_(action_for),
frappe.bold(args.account), frappe.bold(cost_center),
frappe.bold(fmt_money(budget_amount, currency=currency)), frappe.bold(fmt_money(diff, currency=currency)))
msg = _("{0} Budget for Account {1} against {2} {3} is {4}. It will exceed by {5}").format(
_(action_for), frappe.bold(args.account), args.budget_against_field,
frappe.bold(args.budget_against),
frappe.bold(fmt_money(budget_amount, currency=currency)),
frappe.bold(fmt_money(diff, currency=currency)))
if action=="Stop":
frappe.throw(msg, BudgetError)
else:
frappe.msgprint(msg, indicator='orange')
def get_actual_expense(args):
condition1 = " and gle.posting_date <= %(month_end_date)s" \
if args.get("month_end_date") else ""
if args.budget_against_field == "Cost Center":
lft_rgt = frappe.db.get_value(args.budget_against_field,
args.budget_against, ["lft", "rgt"], as_dict=1)
args.update(lft_rgt)
condition2 = """and exists(select name from `tabCost Center`
where lft>=%(lft)s and rgt<=%(rgt)s and name=gle.cost_center)"""
elif args.budget_against_field == "Project":
condition2 = "and exists(select name from `tabProject` where name=gle.project)"
return flt(frappe.db.sql("""
select sum(gle.debit) - sum(gle.credit)
from `tabGL Entry` gle
where gle.account=%(account)s
{condition1}
and gle.fiscal_year=%(fiscal_year)s
and gle.company=%(company)s
and gle.docstatus=1
{condition2}
""".format(condition1=condition1, condition2=condition2), (args))[0][0])
def get_accumulated_monthly_budget(monthly_distribution, posting_date, fiscal_year, annual_budget):
distribution = {}
if monthly_distribution:
@ -121,21 +174,3 @@ def get_accumulated_monthly_budget(monthly_distribution, posting_date, fiscal_ye
dt = add_months(dt, 1)
return annual_budget * accumulated_percentage / 100
def get_actual_expense(args, cost_center):
lft_rgt = frappe.db.get_value("Cost Center", cost_center, ["lft", "rgt"], as_dict=1)
args.update(lft_rgt)
condition = " and gle.posting_date <= %(month_end_date)s" if args.get("month_end_date") else ""
return flt(frappe.db.sql("""
select sum(gle.debit) - sum(gle.credit)
from `tabGL Entry` gle
where gle.account=%(account)s
and exists(select name from `tabCost Center`
where lft>=%(lft)s and rgt<=%(rgt)s and name=gle.cost_center)
and gle.fiscal_year=%(fiscal_year)s
and gle.company=%(company)s
and gle.docstatus=1
{condition}
""".format(condition=condition), (args))[0][0])

View File

@ -10,9 +10,9 @@ from erpnext.accounts.doctype.journal_entry.test_journal_entry import make_journ
class TestBudget(unittest.TestCase):
def test_monthly_budget_crossed_ignore(self):
set_total_expense_zero("2013-02-28")
set_total_expense_zero("2013-02-28", "Cost Center")
budget = make_budget()
budget = make_budget("Cost Center")
jv = make_journal_entry("_Test Account Cost for Goods Sold - _TC",
"_Test Bank - _TC", 40000, "_Test Cost Center - _TC", submit=True)
@ -22,10 +22,10 @@ class TestBudget(unittest.TestCase):
budget.cancel()
def test_monthly_budget_crossed_stop(self):
set_total_expense_zero("2013-02-28")
def test_monthly_budget_crossed_stop1(self):
set_total_expense_zero("2013-02-28", "Cost Center")
budget = make_budget()
budget = make_budget("Cost Center")
frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
@ -37,10 +37,25 @@ class TestBudget(unittest.TestCase):
budget.load_from_db()
budget.cancel()
def test_yearly_budget_crossed_stop(self):
set_total_expense_zero("2013-02-28")
def test_monthly_budget_crossed_stop2(self):
set_total_expense_zero("2013-02-28", "Project")
budget = make_budget()
budget = make_budget("Project")
frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
jv = make_journal_entry("_Test Account Cost for Goods Sold - _TC",
"_Test Bank - _TC", 40000, "_Test Cost Center - _TC", project="_Test Project")
self.assertRaises(BudgetError, jv.submit)
budget.load_from_db()
budget.cancel()
def test_yearly_budget_crossed_stop1(self):
set_total_expense_zero("2013-02-28", "Cost Center")
budget = make_budget("Cost Center")
jv = make_journal_entry("_Test Account Cost for Goods Sold - _TC",
"_Test Bank - _TC", 150000, "_Test Cost Center - _TC")
@ -49,10 +64,22 @@ class TestBudget(unittest.TestCase):
budget.cancel()
def test_monthly_budget_on_cancellation(self):
set_total_expense_zero("2013-02-28")
def test_yearly_budget_crossed_stop2(self):
set_total_expense_zero("2013-02-28", "Project")
budget = make_budget()
budget = make_budget("Project")
jv = make_journal_entry("_Test Account Cost for Goods Sold - _TC",
"_Test Bank - _TC", 150000, "_Test Cost Center - _TC", project="_Test Project")
self.assertRaises(BudgetError, jv.submit)
budget.cancel()
def test_monthly_budget_on_cancellation1(self):
set_total_expense_zero("2013-02-28", "Cost Center")
budget = make_budget("Cost Center")
jv1 = make_journal_entry("_Test Account Cost for Goods Sold - _TC",
"_Test Bank - _TC", 20000, "_Test Cost Center - _TC", submit=True)
@ -72,12 +99,37 @@ class TestBudget(unittest.TestCase):
budget.load_from_db()
budget.cancel()
def test_monthly_budget_on_cancellation2(self):
set_total_expense_zero("2013-02-28", "Project")
budget = make_budget("Project")
jv1 = make_journal_entry("_Test Account Cost for Goods Sold - _TC",
"_Test Bank - _TC", 20000, "_Test Cost Center - _TC", submit=True, project="_Test Project")
self.assertTrue(frappe.db.get_value("GL Entry",
{"voucher_type": "Journal Entry", "voucher_no": jv1.name}))
jv2 = make_journal_entry("_Test Account Cost for Goods Sold - _TC",
"_Test Bank - _TC", 20000, "_Test Cost Center - _TC", submit=True, project="_Test Project")
self.assertTrue(frappe.db.get_value("GL Entry",
{"voucher_type": "Journal Entry", "voucher_no": jv2.name}))
frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
self.assertRaises(BudgetError, jv1.cancel)
budget.load_from_db()
budget.cancel()
def test_monthly_budget_against_group_cost_center(self):
set_total_expense_zero("2013-02-28")
set_total_expense_zero("2013-02-28", "_Test Cost Center 2 - _TC")
set_total_expense_zero("2013-02-28", "Cost Center")
set_total_expense_zero("2013-02-28", "Cost Center", "_Test Cost Center 2 - _TC")
budget = make_budget("_Test Company - _TC")
budget = make_budget("Cost Center", "_Test Company - _TC")
frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
jv = make_journal_entry("_Test Account Cost for Goods Sold - _TC",
@ -88,28 +140,52 @@ class TestBudget(unittest.TestCase):
budget.load_from_db()
budget.cancel()
def set_total_expense_zero(posting_date, cost_center=None):
existing_expense = get_actual_expense({
def set_total_expense_zero(posting_date, budget_against_field=None, budget_against_CC=None):
if budget_against_field == "Project":
budget_against = "_Test Project"
else:
budget_against = budget_against_CC or "_Test Cost Center - _TC"
existing_expense = get_actual_expense(frappe._dict({
"account": "_Test Account Cost for Goods Sold - _TC",
"cost_center": cost_center or "_Test Cost Center - _TC",
"cost_center": "_Test Cost Center - _TC",
"monthly_end_date": posting_date,
"company": "_Test Company",
"fiscal_year": "_Test Fiscal Year 2013"
}, cost_center or "_Test Cost Center - _TC")
"fiscal_year": "_Test Fiscal Year 2013",
"budget_against_field": budget_against_field,
"budget_against": budget_against
}))
if existing_expense:
make_journal_entry("_Test Account Cost for Goods Sold - _TC",
if budget_against_field == "Cost Center":
make_journal_entry("_Test Account Cost for Goods Sold - _TC",
"_Test Bank - _TC", -existing_expense, "_Test Cost Center - _TC", submit=True)
elif budget_against_field == "Project":
make_journal_entry("_Test Account Cost for Goods Sold - _TC",
"_Test Bank - _TC", -existing_expense, "_Test Cost Center - _TC", submit=True, project="_Test Project")
def make_budget(cost_center=None):
def make_budget(budget_against=None, cost_center=None):
if budget_against == "Project":
budget_list = frappe.get_all("Budget", fields=["name"], filters = {"name": ("like", "_Test Project/_Test Fiscal Year 2013%")})
else:
budget_list = frappe.get_all("Budget", fields=["name"], filters = {"name": ("like", "_Test Cost Center - _TC/_Test Fiscal Year 2013%")})
for d in budget_list:
frappe.db.sql("delete from `tabBudget` where name = %(name)s", d)
frappe.db.sql("delete from `tabBudget Account` where parent = %(name)s", d)
budget = frappe.new_doc("Budget")
budget.cost_center = cost_center or "_Test Cost Center - _TC"
if budget_against == "Project":
budget.project = "_Test Project"
else:
budget.cost_center =cost_center or "_Test Cost Center - _TC"
budget.fiscal_year = "_Test Fiscal Year 2013"
budget.monthly_distribution = "_Test Distribution"
budget.company = "_Test Company"
budget.action_if_annual_budget_exceeded = "Stop"
budget.action_if_accumulated_monthly_budget_exceeded = "Ignore"
budget.budget_against = budget_against
budget.append("accounts", {
"account": "_Test Account Cost for Goods Sold - _TC",
"budget_amount": 100000

View File

@ -186,10 +186,10 @@ class TestJournalEntry(unittest.TestCase):
self.assertEqual(len(je.get("accounts")), 2)
def make_journal_entry(account1, account2, amount, cost_center=None, posting_date=None, exchange_rate=1, save=True, submit=False):
def make_journal_entry(account1, account2, amount, cost_center=None, posting_date=None, exchange_rate=1, save=True, submit=False, project=None):
if not cost_center:
cost_center = "_Test Cost Center - _TC"
jv = frappe.new_doc("Journal Entry")
jv.posting_date = posting_date or "2013-02-14"
jv.company = "_Test Company"
@ -199,12 +199,14 @@ def make_journal_entry(account1, account2, amount, cost_center=None, posting_dat
{
"account": account1,
"cost_center": cost_center,
"project": project,
"debit_in_account_currency": amount if amount > 0 else 0,
"credit_in_account_currency": abs(amount) if amount < 0 else 0,
"exchange_rate": exchange_rate
}, {
"account": account2,
"cost_center": cost_center,
"project": project,
"credit_in_account_currency": amount if amount > 0 else 0,
"debit_in_account_currency": abs(amount) if amount < 0 else 0,
"exchange_rate": exchange_rate

View File

@ -354,3 +354,4 @@ erpnext.patches.v7_1.rename_quality_inspection_field
erpnext.patches.v7_0.update_autoname_field
erpnext.patches.v7_1.update_bom_base_currency
erpnext.patches.v7_0.update_status_of_po_so
erpnext.patches.v7_1.set_budget_against_as_cost_center

View File

@ -0,0 +1,10 @@
import frappe
def execute():
frappe.reload_doc("account", "doctype", "budget")
frappe.db.sql("""
update
`tabBudget`
set
budget_against = 'Cost Center'
""")