make_gl_entry function in account_controller: deprecated gl mapper

This commit is contained in:
Nabin Hait 2013-01-29 11:34:39 +05:30
parent 23941aa8f2
commit 2df4d546ae
3 changed files with 264 additions and 133 deletions

View File

@ -8,80 +8,83 @@
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import webnotes
from webnotes.utils import cstr, flt, getdate
from webnotes.model import db_exists
from webnotes.model.wrapper import copy_doclist
from webnotes.model.code import get_obj
from webnotes import msgprint
sql = webnotes.conn.sql
class DocType:
def __init__(self,d,dl):
self.doc, self.doclist = d, dl
# Get monthly budget
#-------------------
def get_monthly_budget(self, distribution_id, cfy, st_date, post_dt, budget_allocated):
# get month_list
st_date, post_dt = getdate(st_date), getdate(post_dt)
if distribution_id:
if st_date.month <= post_dt.month:
tot_per_allocated = sql("select ifnull(sum(percentage_allocation),0) from `tabBudget Distribution Detail` where parent='%s' and idx between '%s' and '%s'" % (distribution_id, st_date.month, post_dt.month))[0][0]
def __init__(self,d,dl):
self.doc, self.doclist = d, dl
# Get monthly budget
#-------------------
def get_monthly_budget(self, distribution_id, cfy, st_date, post_dt, budget_allocated):
# get month_list
st_date, post_dt = getdate(st_date), getdate(post_dt)
if distribution_id:
if st_date.month <= post_dt.month:
tot_per_allocated = webnotes.conn.sql("select ifnull(sum(percentage_allocation),0) from `tabBudget Distribution Detail` where parent='%s' and idx between '%s' and '%s'" % (distribution_id, st_date.month, post_dt.month))[0][0]
if st_date.month > post_dt.month:
tot_per_allocated = flt(sql("select ifnull(sum(percentage_allocation),0) from `tabBudget Distribution Detail` where parent='%s' and idx between '%s' and '%s'" % (distribution_id, st_date.month, 12 ))[0][0])
tot_per_allocated = flt(tot_per_allocated) + flt(sql("select ifnull(sum(percentage_allocation),0) from `tabBudget Distribution Detail` where parent='%s' and idx between '%s' and '%s'" % (distribution_id, 1, post_dt.month))[0][0])
return (flt(budget_allocated) * flt(tot_per_allocated)) / 100
period_diff = sql("select PERIOD_DIFF('%s','%s')" % (post_dt.strftime('%Y%m'), st_date.strftime('%Y%m')))
return (flt(budget_allocated) * (flt(period_diff[0][0]) + 1)) / 12
def validate_budget(self, acct, cost_center, actual, budget, action):
# action if actual exceeds budget
if flt(actual) > flt(budget):
msgprint("Your monthly expense "+ cstr((action == 'stop') and "will exceed" or "has exceeded") +" budget for <b>Account - "+cstr(acct)+" </b> under <b>Cost Center - "+ cstr(cost_center) + "</b>"+cstr((action == 'Stop') and ", you can not have this transaction." or "."))
if action == 'Stop': raise Exception
if st_date.month > post_dt.month:
tot_per_allocated = flt(webnotes.conn.sql("select ifnull(sum(percentage_allocation),0) from `tabBudget Distribution Detail` where parent='%s' and idx between '%s' and '%s'" % (distribution_id, st_date.month, 12 ))[0][0])
tot_per_allocated = flt(tot_per_allocated) + flt(webnotes.conn.sql("select ifnull(sum(percentage_allocation),0) from `tabBudget Distribution Detail` where parent='%s' and idx between '%s' and '%s'" % (distribution_id, 1, post_dt.month))[0][0])
return (flt(budget_allocated) * flt(tot_per_allocated)) / 100
period_diff = webnotes.conn.sql("select PERIOD_DIFF('%s','%s')" % (post_dt.strftime('%Y%m'), st_date.strftime('%Y%m')))
return (flt(budget_allocated) * (flt(period_diff[0][0]) + 1)) / 12
def validate_budget(self, acct, cost_center, actual, budget, action):
# action if actual exceeds budget
if flt(actual) > flt(budget):
msgprint("Your monthly expense "+ cstr((action == 'stop') and "will exceed" or "has exceeded") +" budget for <b>Account - "+cstr(acct)+" </b> under <b>Cost Center - "+ cstr(cost_center) + "</b>"+cstr((action == 'Stop') and ", you can not have this transaction." or "."))
if action == 'Stop': raise Exception
def check_budget(self,le_list,cancel):
# get value from record
acct, cost_center, debit, credit, post_dt, cfy, company = le_list
def check_budget(self,gle,cancel):
# get allocated budget
bgt = webnotes.conn.sql("""select t1.budget_allocated, t1.actual, t2.distribution_id
from `tabBudget Detail` t1, `tabCost Center` t2
where t1.account='%s' and t1.parent=t2.name and t2.name = '%s'
and t1.fiscal_year='%s'""" %
(gle['account'], gle['cost_center'], gle['fiscal_year']), as_dict =1)
# get allocated budget
bgt = sql("select t1.budget_allocated, t1.actual, t2.distribution_id from `tabBudget Detail` t1, `tabCost Center` t2 where t1.account='%s' and t1.parent=t2.name and t2.name = '%s' and t1.fiscal_year='%s'" % (acct,cost_center,cfy), as_dict =1)
curr_amt = ((cancel and -1 or 1) * flt(debit)) + ((cancel and 1 or -1) * flt(credit))
if bgt and bgt[0]['budget_allocated']:
# check budget flag in Company
bgt_flag = sql("select yearly_bgt_flag, monthly_bgt_flag from `tabCompany` where name = '%s'" % company, as_dict =1)
if bgt_flag and bgt_flag[0]['monthly_bgt_flag'] in ['Stop', 'Warn']:
# get start date and last date
st_date = webnotes.conn.get_value('Fiscal Year', cfy, 'year_start_date').strftime('%Y-%m-%d')
lt_date = sql("select LAST_DAY('%s')" % post_dt)
# get Actual
actual = get_obj('GL Control').get_period_difference(acct + '~~~' + cstr(st_date) + '~~~' + cstr(lt_date[0][0]), cost_center)
# Get Monthly budget
budget = self.get_monthly_budget(bgt and bgt[0]['distribution_id'] or '' , cfy, st_date, post_dt, bgt[0]['budget_allocated'])
# validate monthly budget
self.validate_budget(acct, cost_center, flt(actual) + flt(curr_amt), budget, 'monthly_bgt_flag')
curr_amt = flt(gle['debit']) - flt(gle['credit'])
if cancel: curr_amt = -1 * curr_amt
if bgt and bgt[0]['budget_allocated']:
# check budget flag in Company
bgt_flag = webnotes.conn.sql("""select yearly_bgt_flag, monthly_bgt_flag
from `tabCompany` where name = '%s'""" % gle['company'], as_dict =1)
if bgt_flag and bgt_flag[0]['monthly_bgt_flag'] in ['Stop', 'Warn']:
# get start date and last date
start_date = webnotes.conn.get_value('Fiscal Year', gle['fiscal_year'], \
'year_start_date').strftime('%Y-%m-%d')
end_date = webnotes.conn.sql("select LAST_DAY('%s')" % gle['posting_date'])
# get Actual
actual = webnotes.get_obj('GL Control').get_period_difference(gle['account'] +
'~~~' + cstr(start_date) + '~~~' + cstr(end_date[0][0]), gle['cost_center'])
# Get Monthly budget
budget = self.get_monthly_budget(bgt and bgt[0]['distribution_id'] or '' , \
gle['fiscal_year'], start_date, gle['posting_date'], bgt[0]['budget_allocated'])
# validate monthly budget
self.validate_budget(gle['account'], gle['cost_center'], \
flt(actual) + flt(curr_amt), budget, 'monthly_bgt_flag')
# update actual against budget allocated in cost center
sql("update `tabBudget Detail` set actual = ifnull(actual,0) + %s where account = '%s' and fiscal_year = '%s' and parent = '%s'" % (curr_amt,cstr(acct),cstr(cfy),cstr(cost_center)))
# update actual against budget allocated in cost center
webnotes.conn.sql("""update `tabBudget Detail` set actual = ifnull(actual,0) + %s
where account = '%s' and fiscal_year = '%s' and parent = '%s'""" %
(curr_amt, gle['account'],gle['fiscal_year'], gle['cost_center']))

View File

@ -220,78 +220,10 @@ class DocType:
def clear_advances(self, obj,table_name,table_field_name):
for d in getlist(obj.doclist,table_field_name):
if not flt(d.allocated_amount):
webnotes.conn.sql("update `tab%s` set parent = '' where name = '%s' and parent = '%s'" % (table_name, d.name, d.parent))
webnotes.conn.sql("update `tab%s` set parent = '' where name = '%s' \
and parent = '%s'" % (table_name, d.name, d.parent))
d.parent = ''
# Update aginst document in journal voucher
#------------------------------------------
def update_against_document_in_jv(self, obj, table_field_name, against_document_no, against_document_doctype, account_head, dr_or_cr,doctype):
for d in getlist(obj.doclist, table_field_name):
self.validate_jv_entry(d, account_head, dr_or_cr)
if flt(d.advance_amount) == flt(d.allocated_amount):
# cancel JV
jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children=1)
get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel =1, adv_adj =1)
# update ref in JV Detail
webnotes.conn.sql("update `tabJournal Voucher Detail` set %s = '%s' where name = '%s'" % (doctype=='Purchase Invoice' and 'against_voucher' or 'against_invoice', cstr(against_document_no), d.jv_detail_no))
# re-submit JV
jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children =1)
get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel = 0, adv_adj =1)
elif flt(d.advance_amount) > flt(d.allocated_amount):
# cancel JV
jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children=1)
get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel =1, adv_adj = 1)
# add extra entries
self.add_extra_entry(jv_obj, d.journal_voucher, d.jv_detail_no, flt(d.allocated_amount), account_head, doctype, dr_or_cr, against_document_no)
# re-submit JV
jv_obj = get_obj('Journal Voucher', d.journal_voucher, with_children =1)
get_obj(dt='GL Control').make_gl_entries(jv_obj.doc, jv_obj.doclist, cancel = 0, adv_adj = 1)
else:
msgprint("Allocation amount cannot be greater than advance amount")
raise Exception
# Add extra row in jv detail for unadjusted amount
#--------------------------------------------------
def add_extra_entry(self,jv_obj,jv,jv_detail_no, allocate, account_head, doctype, dr_or_cr, against_document_no):
# get old entry details
jvd = webnotes.conn.sql("select %s, cost_center, balance, against_account from `tabJournal Voucher Detail` where name = '%s'" % (dr_or_cr,jv_detail_no))
advance = jvd and flt(jvd[0][0]) or 0
balance = flt(advance) - flt(allocate)
# update old entry
webnotes.conn.sql("update `tabJournal Voucher Detail` set %s = '%s', %s = '%s' where name = '%s'" % (dr_or_cr, flt(allocate), doctype == "Purchase Invoice" and 'against_voucher' or 'against_invoice',cstr(against_document_no), jv_detail_no))
# new entry with balance amount
add = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail', jv_obj.doclist)
add.account = account_head
add.cost_center = cstr(jvd[0][1])
add.balance = cstr(jvd[0][2])
add.fields[dr_or_cr] = balance
add.against_account = cstr(jvd[0][3])
add.is_advance = 'Yes'
add.save(1)
# check if advance entries are still valid
# ----------------------------------------
def validate_jv_entry(self, d, account_head, dr_or_cr):
# 1. check if there is already a voucher reference
# 2. check if amount is same
# 3. check if is_advance is 'Yes'
# 4. check if jv is submitted
ret = webnotes.conn.sql("select t2.%s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2 where t1.name = t2.parent and ifnull(t2.against_voucher, '') = '' and ifnull(t2.against_invoice, '') = '' and t2.account = '%s' and t1.name = '%s' and t2.name = '%s' and t2.is_advance = 'Yes' and t1.docstatus=1 and t2.%s = %s" % (dr_or_cr, account_head, d.journal_voucher, d.jv_detail_no, dr_or_cr, d.advance_amount))
if (not ret):
msgprint("Please click on 'Get Advances Paid' button as the advance entries have been changed.")
raise Exception
return
def reconcile_against_document(self, args):
"""
Cancel JV, Update aginst document, split if required and resubmit jv

View File

@ -0,0 +1,196 @@
# ERPNext - web based ERP (http://erpnext.com)
# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import webnotes
from webnotes.utils import flt, cstr
from webnotes.model.doc import Document
from webnotes.model.controller import DocListController
class AccountsController(DocListController):
def make_gl_entries(self, cancel=False, adv_adj=False, mapper=None, merge_entries=True,
update_outstanding='Yes', gl_map=None):
self.entries = []
self.merged_entries = []
self.total_debit = self.total_credit = 0.0
if gl_map:
self.entries = gl_map
else:
self.make_gl_map(mapper)
self.merge_similar_entries(merge_entries)
self.check_budget(cancel)
self.save_entries(cancel, adv_adj, update_outstanding)
if cancel:
self.set_as_cancel()
else:
self.validate_total_debit_credit()
def make_gl_map(self, mapper):
def _gl_map(parent, d, entry_map):
if self.get_val(entry_map['account'], d, parent) \
and (self.get_val(entry_map['debit'], d, parent)
or self.get_val(entry_map['credit'], d, parent)):
gl_dict = {}
for k in entry_map:
gl_dict[k] = self.get_val(entry_map[k], d, parent)
self.entries.append(gl_dict)
# get entries
gl_fields = ", ".join([d.fieldname for d in \
webnotes.model.doctype.get("GL Mapper Detail").get({
"doctype": "DocField", "parent": "GL Mapper Detail"})])
entry_map_list = webnotes.conn.sql("""select %s from `tabGL Mapper Detail`
where parent = %s""" % (gl_fields, '%s'), mapper or self.doc.doctype, as_dict=1)
for entry_map in entry_map_list:
table_field = entry_map.get("table_field")
# table_field does not exist in gl entry table
entry_map.pop("table_field")
if table_field:
for d in self.doclist.get({"parentfield": table_field}):
# taxes_and_charges is the table of other charges in purchase cycle
if table_field == "taxes_and_charges" and \
d.fields.get("category") == "Valuation":
# don't create gl entry for only valuation type charges
continue
_gl_map(self.doc, d, entry_map)
else:
_gl_map(None, self.doc, entry_map)
def get_val(self, src, d, parent=None):
"""Get field values from the voucher"""
if not src:
return None
if src.startswith('parent:'):
return parent.fields[src.split(':')[1]]
elif src.startswith('value:'):
return eval(src.split(':')[1])
elif src:
return d.fields.get(src)
def merge_similar_entries(self, merge_entries):
if merge_entries:
for entry in self.entries:
# if there is already an entry in this account then just add it
# to that entry
same_head = self.check_if_in_list(entry)
if same_head:
same_head['debit'] = flt(same_head['debit']) + flt(entry['debit'])
same_head['credit'] = flt(same_head['credit']) + flt(entry['credit'])
else:
self.merged_entries.append(entry)
else:
self.merged_entries = self.entries
def save_entries(self, cancel, adv_adj, update_outstanding):
def _swap(gle):
gle.debit, gle.credit = abs(flt(gle.credit)), abs(flt(gle.debit))
for entry in self.merged_entries:
gle = Document('GL Entry', fielddata=entry)
# toggle debit, credit if negative entry
if flt(gle.debit) < 0 or flt(gle.credit) < 0:
_swap(gle)
# toggled debit/credit in two separate condition because
# both should be executed at the
# time of cancellation when there is negative amount (tax discount)
if cancel:
_swap(gle)
gle_obj = webnotes.get_obj(doc=gle)
# validate except on_cancel
if not cancel:
gle_obj.validate()
# save
gle.save(1)
gle_obj.on_update(adv_adj, cancel, update_outstanding)
# update total debit / credit
self.total_debit += flt(gle.debit)
self.total_credit += flt(gle.credit)
def check_if_in_list(self, gle):
for e in self.merged_entries:
if e['account'] == gle['account'] and \
cstr(e.get('against_voucher'))==cstr(gle.get('against_voucher')) \
and cstr(e.get('against_voucher_type')) == \
cstr(gle.get('against_voucher_type')) \
and cstr(e.get('cost_center')) == cstr(gle.get('cost_center')):
return e
def validate_total_debit_credit(self):
if abs(self.total_debit - self.total_credit) > 0.005:
webnotes.msgprint("""Debit and Credit not equal for
this voucher: Diff (Debit) is %s""" %
(self.total_debit - self.total_credit), raise_exception=1)
def set_as_cancel(self):
webnotes.conn.sql("""update `tabGL Entry` set is_cancelled='Yes'
where voucher_type=%s and voucher_no=%s""", (self.doc.doctype, self.doc.name))
def check_budget(self, cancel):
for gle in self.merged_entries:
if gle.get('cost_center'):
#check budget only if account is expense account
acc_details = webnotes.conn.get_value("Account", gle['account'],
['is_pl_account', 'debit_or_credit'])
if acc_details[0]=="Yes" and acc_details[1]=="Debit":
webnotes.get_obj('Budget Control').check_budget(gle, cancel)
def get_gl_dict(self, args, cancel):
"""this method populates the common properties of a gl entry record"""
gl_dict = {
'company': self.doc.company,
'posting_date': self.doc.posting_date,
'voucher_type': self.doc.doctype,
'voucher_no': self.doc.name,
'aging_date': self.doc.fields.get("aging_date") or self.doc.posting_date,
'remarks': self.doc.remarks,
'is_cancelled': cancel and "Yes" or "No",
'fiscal_year': self.doc.fiscal_year,
'debit': 0,
'credit': 0,
'is_opening': self.doc.fields.get("is_opening") or "No",
}
gl_dict.update(args)
return gl_dict
def get_company_abbr(self):
return webnotes.conn.get_value("Company", self.doc.company, "abbr")
def get_stock_in_hand_account(self):
stock_in_hand = webnotes.conn.get_value("Company", self.doc.company, "stock_in_hand")
if not stock_in_hand:
webnotes.msgprint("""Please specify "Stock In Hand" account
for company: %s""" % (self.doc.company,), raise_exception=1)
return stock_in_hand