blob: b2a2b2cc30d8990d3204b57129d8a6bf1b3b2101 [file] [log] [blame]
Nabin Hait23941aa2013-01-29 11:32:38 +05301# ERPNext - web based ERP (http://erpnext.com)
2# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17from __future__ import unicode_literals
18
19import webnotes
Nabin Haitfb3fd6e2013-01-30 19:16:13 +053020from webnotes.utils import nowdate, cstr, flt
21from webnotes.model.doc import addchild
22from webnotes import msgprint, _
Nabin Hait23941aa2013-01-29 11:32:38 +053023
24class FiscalYearError(webnotes.ValidationError): pass
25
26def get_fiscal_year(date, verbose=1):
27 from webnotes.utils import formatdate
28 # if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate)
29 fy = webnotes.conn.sql("""select name, year_start_date,
30 subdate(adddate(year_start_date, interval 1 year), interval 1 day)
31 as year_end_date
32 from `tabFiscal Year`
33 where %s >= year_start_date and %s < adddate(year_start_date, interval 1 year)
34 order by year_start_date desc""", (date, date))
35
36 if not fy:
37 error_msg = """%s not in any Fiscal Year""" % formatdate(date)
38 if verbose: webnotes.msgprint(error_msg)
39 raise FiscalYearError, error_msg
40
41 return fy[0]
42
43@webnotes.whitelist()
44def get_balance_on(account=None, date=None):
45 if not account and webnotes.form_dict.get("account"):
46 account = webnotes.form_dict.get("account")
47 date = webnotes.form_dict.get("date")
48
49 cond = []
50 if date:
51 cond.append("posting_date <= '%s'" % date)
52 else:
53 # get balance of all entries that exist
54 date = nowdate()
55
56 try:
57 year_start_date = get_fiscal_year(date, verbose=0)[1]
58 except FiscalYearError, e:
59 from webnotes.utils import getdate
60 if getdate(date) > getdate(nowdate()):
61 # if fiscal year not found and the date is greater than today
62 # get fiscal year for today's date and its corresponding year start date
63 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
64 else:
65 # this indicates that it is a date older than any existing fiscal year.
66 # hence, assuming balance as 0.0
67 return 0.0
68
69 acc = webnotes.conn.get_value('Account', account, \
70 ['lft', 'rgt', 'debit_or_credit', 'is_pl_account', 'group_or_ledger'], as_dict=1)
71
72 # for pl accounts, get balance within a fiscal year
73 if acc.is_pl_account == 'Yes':
74 cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" \
75 % year_start_date)
76
77 # different filter for group and ledger - improved performance
78 if acc.group_or_ledger=="Group":
79 cond.append("""exists (
80 select * from `tabAccount` ac where ac.name = gle.account
81 and ac.lft >= %s and ac.rgt <= %s
82 )""" % (acc.lft, acc.rgt))
83 else:
84 cond.append("""gle.account = "%s" """ % (account, ))
85
86 # join conditional conditions
87 cond = " and ".join(cond)
88 if cond:
89 cond += " and "
90
91 bal = webnotes.conn.sql("""
92 SELECT sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
93 FROM `tabGL Entry` gle
94 WHERE %s ifnull(is_cancelled, 'No') = 'No' """ % (cond, ))[0][0]
95
96 # if credit account, it should calculate credit - debit
97 if bal and acc.debit_or_credit == 'Credit':
98 bal = -bal
99
100 # if bal is None, return 0
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530101 return bal or 0
102
103@webnotes.whitelist()
104def add_ac(args=None):
105 if not args:
106 args = webnotes.form_dict
107 args.pop("cmd")
108
109 ac = webnotes.model_wrapper(args)
110 ac.doc.doctype = "Account"
111 ac.doc.old_parent = ""
112 ac.doc.freeze_account = "No"
113 ac.ignore_permissions = 1
114 ac.insert()
115 return ac.doc.name
116
117@webnotes.whitelist()
118def add_cc(args=None):
119 if not args:
120 args = webnotes.form_dict
121 args.pop("cmd")
122
123 cc = webnotes.model_wrapper(args)
124 cc.doc.doctype = "Cost Center"
125 cc.doc.old_parent = ""
126 cc.ignore_permissions = 1
127 cc.insert()
128 return cc.doc.name
129
130def reconcile_against_document(args):
131 """
132 Cancel JV, Update aginst document, split if required and resubmit jv
133 """
134 for d in args:
135 check_if_jv_modified(d)
136
137 against_fld = {
138 'Journal Voucher' : 'against_jv',
139 'Sales Invoice' : 'against_invoice',
140 'Purchase Invoice' : 'against_voucher'
141 }
142
143 d['against_fld'] = against_fld[d['against_voucher_type']]
144
145 # cancel JV
146 jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children=1)
147 jv_obj.make_gl_entries(cancel=1, adv_adj=1)
148
149 # update ref in JV Detail
150 update_against_doc(d, jv_obj)
151
152 # re-submit JV
153 jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children =1)
154 jv_obj.make_gl_entries(cancel = 0, adv_adj =1)
155
156
157def check_if_jv_modified(args):
158 """
159 check if there is already a voucher reference
160 check if amount is same
161 check if jv is submitted
162 """
163 ret = webnotes.conn.sql("""
164 select t2.%(dr_or_cr)s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2
165 where t1.name = t2.parent and t2.account = '%(account)s'
166 and ifnull(t2.against_voucher, '')=''
167 and ifnull(t2.against_invoice, '')='' and ifnull(t2.against_jv, '')=''
168 and t1.name = '%(voucher_no)s' and t2.name = '%(voucher_detail_no)s'
169 and t1.docstatus=1 and t2.%(dr_or_cr)s = %(unadjusted_amt)s""" % args)
170
171 if not ret:
172 msgprint(_("""Payment Entry has been modified after you pulled it.
173 Please pull it again."""), raise_exception=1)
174
175def update_against_doc(d, jv_obj):
176 """
177 Updates against document, if partial amount splits into rows
178 """
179
180 webnotes.conn.sql("""
181 update `tabJournal Voucher Detail` t1, `tabJournal Voucher` t2
182 set t1.%(dr_or_cr)s = '%(allocated_amt)s',
183 t1.%(against_fld)s = '%(against_voucher)s', t2.modified = now()
184 where t1.name = '%(voucher_detail_no)s' and t1.parent = t2.name""" % d)
185
186 if d['allocated_amt'] < d['unadjusted_amt']:
187 jvd = webnotes.conn.sql("""select cost_center, balance, against_account, is_advance
188 from `tabJournal Voucher Detail` where name = %s""", d['voucher_detail_no'])
189 # new entry with balance amount
190 ch = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail')
191 ch.account = d['account']
192 ch.cost_center = cstr(jvd[0][0])
193 ch.balance = cstr(jvd[0][1])
194 ch.fields[d['dr_or_cr']] = flt(d['unadjusted_amt']) - flt(d['allocated_amt'])
195 ch.fields[d['dr_or_cr']== 'debit' and 'credit' or 'debit'] = 0
196 ch.against_account = cstr(jvd[0][2])
197 ch.is_advance = cstr(jvd[0][3])
198 ch.docstatus = 1
199 ch.save(1)