blob: effc906c161339a6cc28f772261af6cf73e3c9c4 [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, _
Rushabh Mehta2e8d0782013-02-05 11:31:27 +053023from webnotes.utils import formatdate
Nabin Hait23941aa2013-01-29 11:32:38 +053024
25class FiscalYearError(webnotes.ValidationError): pass
26
27def get_fiscal_year(date, verbose=1):
Nabin Hait23941aa2013-01-29 11:32:38 +053028 # 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]
Rushabh Mehta2e8d0782013-02-05 11:31:27 +053042
43def validate_fiscal_year(date, fiscal_year, label="Date"):
44 if get_fiscal_year(date)[0] != fiscal_year:
45 msgprint(("%(label)s '%(posting_date)s': " + _("not within Fiscal Year") + \
46 ": '%(fiscal_year)s'") % {
47 "label": label,
48 "posting_date": formatdate(date),
49 "fiscal_year": fiscal_year
50 }, raise_exception=1)
Nabin Hait23941aa2013-01-29 11:32:38 +053051
52@webnotes.whitelist()
53def get_balance_on(account=None, date=None):
54 if not account and webnotes.form_dict.get("account"):
55 account = webnotes.form_dict.get("account")
56 date = webnotes.form_dict.get("date")
57
58 cond = []
59 if date:
60 cond.append("posting_date <= '%s'" % date)
61 else:
62 # get balance of all entries that exist
63 date = nowdate()
64
65 try:
66 year_start_date = get_fiscal_year(date, verbose=0)[1]
67 except FiscalYearError, e:
68 from webnotes.utils import getdate
69 if getdate(date) > getdate(nowdate()):
70 # if fiscal year not found and the date is greater than today
71 # get fiscal year for today's date and its corresponding year start date
72 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
73 else:
74 # this indicates that it is a date older than any existing fiscal year.
75 # hence, assuming balance as 0.0
76 return 0.0
77
78 acc = webnotes.conn.get_value('Account', account, \
79 ['lft', 'rgt', 'debit_or_credit', 'is_pl_account', 'group_or_ledger'], as_dict=1)
80
81 # for pl accounts, get balance within a fiscal year
82 if acc.is_pl_account == 'Yes':
83 cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" \
84 % year_start_date)
85
86 # different filter for group and ledger - improved performance
87 if acc.group_or_ledger=="Group":
88 cond.append("""exists (
89 select * from `tabAccount` ac where ac.name = gle.account
90 and ac.lft >= %s and ac.rgt <= %s
91 )""" % (acc.lft, acc.rgt))
92 else:
93 cond.append("""gle.account = "%s" """ % (account, ))
94
95 # join conditional conditions
96 cond = " and ".join(cond)
97 if cond:
98 cond += " and "
99
100 bal = webnotes.conn.sql("""
101 SELECT sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
102 FROM `tabGL Entry` gle
103 WHERE %s ifnull(is_cancelled, 'No') = 'No' """ % (cond, ))[0][0]
104
105 # if credit account, it should calculate credit - debit
106 if bal and acc.debit_or_credit == 'Credit':
107 bal = -bal
108
109 # if bal is None, return 0
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530110 return bal or 0
111
112@webnotes.whitelist()
113def add_ac(args=None):
114 if not args:
115 args = webnotes.form_dict
116 args.pop("cmd")
117
118 ac = webnotes.model_wrapper(args)
119 ac.doc.doctype = "Account"
120 ac.doc.old_parent = ""
121 ac.doc.freeze_account = "No"
122 ac.ignore_permissions = 1
123 ac.insert()
124 return ac.doc.name
125
126@webnotes.whitelist()
127def add_cc(args=None):
128 if not args:
129 args = webnotes.form_dict
130 args.pop("cmd")
131
132 cc = webnotes.model_wrapper(args)
133 cc.doc.doctype = "Cost Center"
134 cc.doc.old_parent = ""
135 cc.ignore_permissions = 1
136 cc.insert()
137 return cc.doc.name
138
139def reconcile_against_document(args):
140 """
141 Cancel JV, Update aginst document, split if required and resubmit jv
142 """
143 for d in args:
144 check_if_jv_modified(d)
145
146 against_fld = {
147 'Journal Voucher' : 'against_jv',
148 'Sales Invoice' : 'against_invoice',
149 'Purchase Invoice' : 'against_voucher'
150 }
151
152 d['against_fld'] = against_fld[d['against_voucher_type']]
153
154 # cancel JV
155 jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children=1)
156 jv_obj.make_gl_entries(cancel=1, adv_adj=1)
157
158 # update ref in JV Detail
159 update_against_doc(d, jv_obj)
160
161 # re-submit JV
162 jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children =1)
163 jv_obj.make_gl_entries(cancel = 0, adv_adj =1)
164
165
166def check_if_jv_modified(args):
167 """
168 check if there is already a voucher reference
169 check if amount is same
170 check if jv is submitted
171 """
172 ret = webnotes.conn.sql("""
173 select t2.%(dr_or_cr)s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2
174 where t1.name = t2.parent and t2.account = '%(account)s'
175 and ifnull(t2.against_voucher, '')=''
176 and ifnull(t2.against_invoice, '')='' and ifnull(t2.against_jv, '')=''
177 and t1.name = '%(voucher_no)s' and t2.name = '%(voucher_detail_no)s'
178 and t1.docstatus=1 and t2.%(dr_or_cr)s = %(unadjusted_amt)s""" % args)
179
180 if not ret:
181 msgprint(_("""Payment Entry has been modified after you pulled it.
182 Please pull it again."""), raise_exception=1)
183
184def update_against_doc(d, jv_obj):
185 """
186 Updates against document, if partial amount splits into rows
187 """
188
189 webnotes.conn.sql("""
190 update `tabJournal Voucher Detail` t1, `tabJournal Voucher` t2
191 set t1.%(dr_or_cr)s = '%(allocated_amt)s',
192 t1.%(against_fld)s = '%(against_voucher)s', t2.modified = now()
193 where t1.name = '%(voucher_detail_no)s' and t1.parent = t2.name""" % d)
194
195 if d['allocated_amt'] < d['unadjusted_amt']:
196 jvd = webnotes.conn.sql("""select cost_center, balance, against_account, is_advance
197 from `tabJournal Voucher Detail` where name = %s""", d['voucher_detail_no'])
198 # new entry with balance amount
199 ch = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail')
200 ch.account = d['account']
201 ch.cost_center = cstr(jvd[0][0])
202 ch.balance = cstr(jvd[0][1])
203 ch.fields[d['dr_or_cr']] = flt(d['unadjusted_amt']) - flt(d['allocated_amt'])
204 ch.fields[d['dr_or_cr']== 'debit' and 'credit' or 'debit'] = 0
205 ch.against_account = cstr(jvd[0][2])
206 ch.is_advance = cstr(jvd[0][3])
207 ch.docstatus = 1
208 ch.save(1)