blob: bb1e5d9b6b543e134f43b1847fda2fcf989f0dd4 [file] [log] [blame]
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05301# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
2# License: GNU General Public License v3. See license.txt
Nabin Hait23941aa2013-01-29 11:32:38 +05303
4from __future__ import unicode_literals
5
6import webnotes
Nabin Haitcac622e2013-08-02 11:44:29 +05307from webnotes.utils import nowdate, nowtime, cstr, flt, now
Nabin Haitfb3fd6e2013-01-30 19:16:13 +05308from webnotes.model.doc import addchild
9from webnotes import msgprint, _
Rushabh Mehta2e8d0782013-02-05 11:31:27 +053010from webnotes.utils import formatdate
Nabin Haita76a0682013-02-08 14:04:13 +053011from utilities import build_filter_conditions
12
Nabin Hait23941aa2013-01-29 11:32:38 +053013
14class FiscalYearError(webnotes.ValidationError): pass
15
Nabin Haitcfecd2b2013-07-11 17:49:18 +053016def get_fiscal_year(date=None, fiscal_year=None, label="Date", verbose=1):
17 return get_fiscal_years(date, fiscal_year, label, verbose=1)[0]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +053018
Nabin Haitcfecd2b2013-07-11 17:49:18 +053019def get_fiscal_years(date=None, fiscal_year=None, label="Date", verbose=1):
Nabin Hait23941aa2013-01-29 11:32:38 +053020 # if year start date is 2012-04-01, year end date should be 2013-03-31 (hence subdate)
Nabin Hait0930b942013-06-20 16:35:09 +053021 cond = ""
22 if fiscal_year:
23 cond = "name = '%s'" % fiscal_year
24 else:
25 cond = "'%s' >= year_start_date and '%s' < adddate(year_start_date, interval 1 year)" % \
26 (date, date)
Nabin Hait23941aa2013-01-29 11:32:38 +053027 fy = webnotes.conn.sql("""select name, year_start_date,
28 subdate(adddate(year_start_date, interval 1 year), interval 1 day)
29 as year_end_date
30 from `tabFiscal Year`
Nabin Hait0930b942013-06-20 16:35:09 +053031 where %s
32 order by year_start_date desc""" % cond)
Nabin Hait23941aa2013-01-29 11:32:38 +053033
34 if not fy:
Nabin Haitcfecd2b2013-07-11 17:49:18 +053035 error_msg = """%s %s not in any Fiscal Year""" % (label, formatdate(date))
Nabin Hait23941aa2013-01-29 11:32:38 +053036 if verbose: webnotes.msgprint(error_msg)
37 raise FiscalYearError, error_msg
38
Rushabh Mehtac2563ef2013-02-05 23:25:37 +053039 return fy
Rushabh Mehta2e8d0782013-02-05 11:31:27 +053040
41def validate_fiscal_year(date, fiscal_year, label="Date"):
Nabin Haitcfecd2b2013-07-11 17:49:18 +053042 years = [f[0] for f in get_fiscal_years(date, label=label)]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +053043 if fiscal_year not in years:
Rushabh Mehta96075822013-02-05 11:39:49 +053044 webnotes.msgprint(("%(label)s '%(posting_date)s': " + _("not within Fiscal Year") + \
Rushabh Mehta2e8d0782013-02-05 11:31:27 +053045 ": '%(fiscal_year)s'") % {
46 "label": label,
47 "posting_date": formatdate(date),
48 "fiscal_year": fiscal_year
49 }, raise_exception=1)
Nabin Hait23941aa2013-01-29 11:32:38 +053050
51@webnotes.whitelist()
52def get_balance_on(account=None, date=None):
53 if not account and webnotes.form_dict.get("account"):
54 account = webnotes.form_dict.get("account")
55 date = webnotes.form_dict.get("date")
56
57 cond = []
58 if date:
59 cond.append("posting_date <= '%s'" % date)
60 else:
61 # get balance of all entries that exist
62 date = nowdate()
63
64 try:
65 year_start_date = get_fiscal_year(date, verbose=0)[1]
66 except FiscalYearError, e:
67 from webnotes.utils import getdate
68 if getdate(date) > getdate(nowdate()):
69 # if fiscal year not found and the date is greater than today
70 # get fiscal year for today's date and its corresponding year start date
71 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
72 else:
73 # this indicates that it is a date older than any existing fiscal year.
74 # hence, assuming balance as 0.0
75 return 0.0
76
77 acc = webnotes.conn.get_value('Account', account, \
78 ['lft', 'rgt', 'debit_or_credit', 'is_pl_account', 'group_or_ledger'], as_dict=1)
79
80 # for pl accounts, get balance within a fiscal year
81 if acc.is_pl_account == 'Yes':
82 cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" \
83 % year_start_date)
84
85 # different filter for group and ledger - improved performance
86 if acc.group_or_ledger=="Group":
87 cond.append("""exists (
88 select * from `tabAccount` ac where ac.name = gle.account
89 and ac.lft >= %s and ac.rgt <= %s
90 )""" % (acc.lft, acc.rgt))
91 else:
92 cond.append("""gle.account = "%s" """ % (account, ))
93
Nabin Hait23941aa2013-01-29 11:32:38 +053094 bal = webnotes.conn.sql("""
95 SELECT sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
96 FROM `tabGL Entry` gle
Nabin Hait9b09c952013-08-21 17:47:11 +053097 WHERE %s""" % " and ".join(cond))[0][0]
Nabin Hait23941aa2013-01-29 11:32:38 +053098
99 # if credit account, it should calculate credit - debit
100 if bal and acc.debit_or_credit == 'Credit':
101 bal = -bal
102
103 # if bal is None, return 0
Anand Doshi6fa5e422013-07-19 15:33:11 +0530104 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530105
106@webnotes.whitelist()
107def add_ac(args=None):
108 if not args:
109 args = webnotes.form_dict
110 args.pop("cmd")
Rushabh Mehtaaae45532013-02-15 14:39:34 +0530111
Rushabh Mehtac53231a2013-02-18 18:24:28 +0530112 ac = webnotes.bean(args)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530113 ac.doc.doctype = "Account"
114 ac.doc.old_parent = ""
115 ac.doc.freeze_account = "No"
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530116 ac.insert()
117 return ac.doc.name
118
119@webnotes.whitelist()
120def add_cc(args=None):
121 if not args:
122 args = webnotes.form_dict
123 args.pop("cmd")
124
Rushabh Mehtac53231a2013-02-18 18:24:28 +0530125 cc = webnotes.bean(args)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530126 cc.doc.doctype = "Cost Center"
127 cc.doc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530128 cc.insert()
129 return cc.doc.name
130
131def reconcile_against_document(args):
132 """
133 Cancel JV, Update aginst document, split if required and resubmit jv
134 """
135 for d in args:
136 check_if_jv_modified(d)
137
138 against_fld = {
139 'Journal Voucher' : 'against_jv',
140 'Sales Invoice' : 'against_invoice',
141 'Purchase Invoice' : 'against_voucher'
142 }
143
144 d['against_fld'] = against_fld[d['against_voucher_type']]
145
146 # cancel JV
147 jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children=1)
148 jv_obj.make_gl_entries(cancel=1, adv_adj=1)
149
150 # update ref in JV Detail
151 update_against_doc(d, jv_obj)
152
153 # re-submit JV
154 jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children =1)
155 jv_obj.make_gl_entries(cancel = 0, adv_adj =1)
156
157
158def check_if_jv_modified(args):
159 """
160 check if there is already a voucher reference
161 check if amount is same
162 check if jv is submitted
163 """
164 ret = webnotes.conn.sql("""
165 select t2.%(dr_or_cr)s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2
166 where t1.name = t2.parent and t2.account = '%(account)s'
167 and ifnull(t2.against_voucher, '')=''
168 and ifnull(t2.against_invoice, '')='' and ifnull(t2.against_jv, '')=''
169 and t1.name = '%(voucher_no)s' and t2.name = '%(voucher_detail_no)s'
170 and t1.docstatus=1 and t2.%(dr_or_cr)s = %(unadjusted_amt)s""" % args)
171
172 if not ret:
173 msgprint(_("""Payment Entry has been modified after you pulled it.
174 Please pull it again."""), raise_exception=1)
175
176def update_against_doc(d, jv_obj):
177 """
178 Updates against document, if partial amount splits into rows
179 """
180
181 webnotes.conn.sql("""
182 update `tabJournal Voucher Detail` t1, `tabJournal Voucher` t2
183 set t1.%(dr_or_cr)s = '%(allocated_amt)s',
184 t1.%(against_fld)s = '%(against_voucher)s', t2.modified = now()
185 where t1.name = '%(voucher_detail_no)s' and t1.parent = t2.name""" % d)
186
187 if d['allocated_amt'] < d['unadjusted_amt']:
188 jvd = webnotes.conn.sql("""select cost_center, balance, against_account, is_advance
189 from `tabJournal Voucher Detail` where name = %s""", d['voucher_detail_no'])
190 # new entry with balance amount
191 ch = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail')
192 ch.account = d['account']
193 ch.cost_center = cstr(jvd[0][0])
194 ch.balance = cstr(jvd[0][1])
195 ch.fields[d['dr_or_cr']] = flt(d['unadjusted_amt']) - flt(d['allocated_amt'])
196 ch.fields[d['dr_or_cr']== 'debit' and 'credit' or 'debit'] = 0
197 ch.against_account = cstr(jvd[0][2])
198 ch.is_advance = cstr(jvd[0][3])
199 ch.docstatus = 1
Nabin Haita76a0682013-02-08 14:04:13 +0530200 ch.save(1)
201
202def get_account_list(doctype, txt, searchfield, start, page_len, filters):
203 if not filters.get("group_or_ledger"):
204 filters["group_or_ledger"] = "Ledger"
205
206 conditions, filter_values = build_filter_conditions(filters)
207
208 return webnotes.conn.sql("""select name, parent_account from `tabAccount`
209 where docstatus < 2 %s and %s like %s order by name limit %s, %s""" %
210 (conditions, searchfield, "%s", "%s", "%s"),
211 tuple(filter_values + ["%%%s%%" % txt, start, page_len]))
212
213def get_cost_center_list(doctype, txt, searchfield, start, page_len, filters):
214 if not filters.get("group_or_ledger"):
215 filters["group_or_ledger"] = "Ledger"
216
217 conditions, filter_values = build_filter_conditions(filters)
218
219 return webnotes.conn.sql("""select name, parent_cost_center from `tabCost Center`
220 where docstatus < 2 %s and %s like %s order by name limit %s, %s""" %
221 (conditions, searchfield, "%s", "%s", "%s"),
Anand Doshi7da72dd2013-03-20 17:00:41 +0530222 tuple(filter_values + ["%%%s%%" % txt, start, page_len]))
223
224def remove_against_link_from_jv(ref_type, ref_no, against_field):
225 webnotes.conn.sql("""update `tabJournal Voucher Detail` set `%s`=null,
226 modified=%s, modified_by=%s
227 where `%s`=%s and docstatus < 2""" % (against_field, "%s", "%s", against_field, "%s"),
228 (now(), webnotes.session.user, ref_no))
229
230 webnotes.conn.sql("""update `tabGL Entry`
231 set against_voucher_type=null, against_voucher=null,
232 modified=%s, modified_by=%s
233 where against_voucher_type=%s and against_voucher=%s
Nabin Hait9b09c952013-08-21 17:47:11 +0530234 and voucher_no != ifnull(against_voucher, '')""",
Anand Doshi7da72dd2013-03-20 17:00:41 +0530235 (now(), webnotes.session.user, ref_type, ref_no))
Nabin Hait0fc24542013-03-25 11:06:00 +0530236
237@webnotes.whitelist()
238def get_company_default(company, fieldname):
239 value = webnotes.conn.get_value("Company", company, fieldname)
240
241 if not value:
242 msgprint(_("Please mention default value for '") +
243 _(webnotes.get_doctype("company").get_label(fieldname) +
244 _("' in Company: ") + company), raise_exception=True)
245
246 return value
247
248def create_stock_in_hand_jv(reverse=False):
249 from webnotes.utils import nowdate
250 today = nowdate()
251 fiscal_year = get_fiscal_year(today)[0]
Nabin Hait787c02e2013-03-29 16:42:33 +0530252 jv_list = []
Nabin Hait0fc24542013-03-25 11:06:00 +0530253
254 for company in webnotes.conn.sql_list("select name from `tabCompany`"):
255 stock_rbnb_value = get_stock_rbnb_value(company)
Nabin Hait787c02e2013-03-29 16:42:33 +0530256 stock_rbnb_value = reverse and -1*stock_rbnb_value or stock_rbnb_value
257 if stock_rbnb_value:
258 jv = webnotes.bean([
259 {
260 "doctype": "Journal Voucher",
Anand Doshi72edc3d2013-05-29 12:13:16 +0530261 "naming_series": "JV-AUTO-",
Nabin Hait787c02e2013-03-29 16:42:33 +0530262 "company": company,
263 "posting_date": today,
264 "fiscal_year": fiscal_year,
265 "voucher_type": "Journal Entry",
Nabin Hait4af2dbf2013-08-12 12:24:08 +0530266 "user_remark": (_("Perpetual Accounting") + ": " +
Anand Doshi72edc3d2013-05-29 12:13:16 +0530267 (_("Disabled") if reverse else _("Enabled")) + ". " +
268 _("Journal Entry for inventory that is received but not yet invoiced"))
Nabin Hait787c02e2013-03-29 16:42:33 +0530269 },
270 {
271 "doctype": "Journal Voucher Detail",
272 "parentfield": "entries",
273 "account": get_company_default(company, "stock_received_but_not_billed"),
Anand Doshi72edc3d2013-05-29 12:13:16 +0530274 (stock_rbnb_value > 0 and "credit" or "debit"): abs(stock_rbnb_value)
Nabin Hait787c02e2013-03-29 16:42:33 +0530275 },
276 {
277 "doctype": "Journal Voucher Detail",
278 "parentfield": "entries",
279 "account": get_company_default(company, "stock_adjustment_account"),
Anand Doshi72edc3d2013-05-29 12:13:16 +0530280 (stock_rbnb_value > 0 and "debit" or "credit"): abs(stock_rbnb_value),
Nabin Hait787c02e2013-03-29 16:42:33 +0530281 "cost_center": get_company_default(company, "stock_adjustment_cost_center")
282 },
283 ])
284 jv.insert()
Nabin Hait787c02e2013-03-29 16:42:33 +0530285
286 jv_list.append(jv.doc.name)
287
288 if jv_list:
Anand Doshi72edc3d2013-05-29 12:13:16 +0530289 msgprint(_("Following Journal Vouchers have been created automatically") + \
290 ":\n%s" % ("\n".join([("<a href=\"#Form/Journal Voucher/%s\">%s</a>" % (jv, jv)) for jv in jv_list]),))
291
292 msgprint(_("""These adjustment vouchers book the difference between \
293 the total value of received items and the total value of invoiced items, \
Nabin Hait4af2dbf2013-08-12 12:24:08 +0530294 as a required step to use Perpetual Accounting.
Anand Doshi72edc3d2013-05-29 12:13:16 +0530295 This is an approximation to get you started.
296 You will need to submit these vouchers after checking if the values are correct.
297 For more details, read: \
298 <a href="http://erpnext.com/auto-inventory-accounting" target="_blank">\
Nabin Hait4af2dbf2013-08-12 12:24:08 +0530299 Perpetual Accounting</a>"""))
Nabin Hait787c02e2013-03-29 16:42:33 +0530300
Nabin Hait4af2dbf2013-08-12 12:24:08 +0530301 webnotes.msgprint("""Please refresh the system to get effect of Perpetual Accounting""")
Nabin Hait787c02e2013-03-29 16:42:33 +0530302
Nabin Hait0fc24542013-03-25 11:06:00 +0530303
Nabin Hait787c02e2013-03-29 16:42:33 +0530304def get_stock_rbnb_value(company):
305 total_received_amount = webnotes.conn.sql("""select sum(valuation_rate*qty*conversion_factor)
Nabin Hait0fc24542013-03-25 11:06:00 +0530306 from `tabPurchase Receipt Item` pr_item where docstatus=1
307 and exists(select name from `tabItem` where name = pr_item.item_code
308 and is_stock_item='Yes')
Nabin Hait41fe3562013-03-28 15:54:11 +0530309 and exists(select name from `tabPurchase Receipt`
Nabin Hait0fc24542013-03-25 11:06:00 +0530310 where name = pr_item.parent and company = %s)""", company)
311
Nabin Hait787c02e2013-03-29 16:42:33 +0530312 total_billed_amount = webnotes.conn.sql("""select sum(valuation_rate*qty*conversion_factor)
Nabin Hait0fc24542013-03-25 11:06:00 +0530313 from `tabPurchase Invoice Item` pi_item where docstatus=1
314 and exists(select name from `tabItem` where name = pi_item.item_code
315 and is_stock_item='Yes')
Nabin Hait41fe3562013-03-28 15:54:11 +0530316 and exists(select name from `tabPurchase Invoice`
Nabin Hait0fc24542013-03-25 11:06:00 +0530317 where name = pi_item.parent and company = %s)""", company)
Nabin Hait0fc24542013-03-25 11:06:00 +0530318 return flt(total_received_amount[0][0]) - flt(total_billed_amount[0][0])
Nabin Hait8b509f52013-05-28 16:52:30 +0530319
320
321def fix_total_debit_credit():
322 vouchers = webnotes.conn.sql("""select voucher_type, voucher_no,
323 sum(debit) - sum(credit) as diff
324 from `tabGL Entry`
325 group by voucher_type, voucher_no
326 having sum(ifnull(debit, 0)) != sum(ifnull(credit, 0))""", as_dict=1)
327
328 for d in vouchers:
329 if abs(d.diff) > 0:
330 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
331
332 webnotes.conn.sql("""update `tabGL Entry` set %s = %s + %s
333 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1""" %
334 (dr_or_cr, dr_or_cr, '%s', '%s', '%s', dr_or_cr),
Nabin Haitcac622e2013-08-02 11:44:29 +0530335 (d.diff, d.voucher_type, d.voucher_no))
336
337def validate_stock_and_account_balance():
338 difference = get_stock_and_account_difference()
339 if difference:
340 msgprint(_("Account balance must be synced with stock balance, \
341 to enable perpetual accounting." +
342 _(" Following accounts are not synced with stock balance") + ": \n" +
343 "\n".join(difference.keys())), raise_exception=1)
344
345def get_stock_and_account_difference(warehouse_list=None):
346 from stock.utils import get_latest_stock_balance
347
348 if not warehouse_list:
349 warehouse_list = webnotes.conn.sql_list("""select name from tabWarehouse
350 where docstatus<2""")
Nabin Hait94d39632013-08-06 15:58:44 +0530351
Nabin Haitcac622e2013-08-02 11:44:29 +0530352 account_warehouse_map = {}
353 warehouse_with_no_account = []
354 difference = {}
Nabin Haitcac622e2013-08-02 11:44:29 +0530355 warehouse_account = webnotes.conn.sql("""select name, account from tabWarehouse
356 where name in (%s)""" % ', '.join(['%s']*len(warehouse_list)), warehouse_list, as_dict=1)
357
358 for wh in warehouse_account:
359 if not wh.account: warehouse_with_no_account.append(wh.name)
360 account_warehouse_map.setdefault(wh.account, []).append(wh.name)
361
362 if warehouse_with_no_account:
363 msgprint(_("Please mention Perpetual Account in warehouse master for following warehouses")
364 + ": " + '\n'.join(warehouse_with_no_account), raise_exception=1)
365
Nabin Hait94d39632013-08-06 15:58:44 +0530366 bin_map = get_latest_stock_balance()
367 for account, warehouse_list in account_warehouse_map.items():
Nabin Haitcac622e2013-08-02 11:44:29 +0530368 account_balance = get_balance_on(account)
Nabin Hait94d39632013-08-06 15:58:44 +0530369 stock_value = sum([sum(bin_map.get(warehouse, {}).values())
370 for warehouse in warehouse_list])
Nabin Haitaa342012013-08-07 14:21:04 +0530371 if abs(flt(stock_value) - flt(account_balance)) > 0.005:
Nabin Hait469ee712013-08-07 12:33:37 +0530372 difference.setdefault(account, flt(stock_value) - flt(account_balance))
Nabin Haitaa342012013-08-07 14:21:04 +0530373
Nabin Haitcc0e2d12013-08-06 16:19:18 +0530374 return difference