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