blob: caad793ca180e797f3a3fc5595bfdaf791d0596f [file] [log] [blame]
Rushabh Mehtaad45e312013-11-20 12:59:58 +05301# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# 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 Hait2b06aaa2013-08-22 18:25:43 +05307from webnotes.utils import nowdate, nowtime, cstr, flt, now, getdate, add_months
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
Nabin Hait2b06aaa2013-08-22 18:25:43 +053015class BudgetError(webnotes.ValidationError): pass
16
Nabin Hait23941aa2013-01-29 11:32:38 +053017
Nabin Haitcfecd2b2013-07-11 17:49:18 +053018def get_fiscal_year(date=None, fiscal_year=None, label="Date", verbose=1):
19 return get_fiscal_years(date, fiscal_year, label, verbose=1)[0]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +053020
Nabin Haitcfecd2b2013-07-11 17:49:18 +053021def get_fiscal_years(date=None, fiscal_year=None, label="Date", verbose=1):
Nabin Hait23941aa2013-01-29 11:32:38 +053022 # 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 +053023 cond = ""
24 if fiscal_year:
25 cond = "name = '%s'" % fiscal_year
26 else:
Akhilesh Darjeeec0da0b2013-11-25 19:51:18 +053027 cond = "'%s' >= year_start_date and '%s' <= year_end_date" % \
Nabin Hait0930b942013-06-20 16:35:09 +053028 (date, date)
Akhilesh Darjeeec0da0b2013-11-25 19:51:18 +053029 fy = webnotes.conn.sql("""select name, year_start_date, year_end_date
30 from `tabFiscal Year` where %s order by year_start_date desc""" % cond)
Nabin Hait23941aa2013-01-29 11:32:38 +053031
32 if not fy:
Nabin Haitcfecd2b2013-07-11 17:49:18 +053033 error_msg = """%s %s not in any Fiscal Year""" % (label, formatdate(date))
Nabin Hait23941aa2013-01-29 11:32:38 +053034 if verbose: webnotes.msgprint(error_msg)
35 raise FiscalYearError, error_msg
36
Rushabh Mehtac2563ef2013-02-05 23:25:37 +053037 return fy
Rushabh Mehta2e8d0782013-02-05 11:31:27 +053038
39def validate_fiscal_year(date, fiscal_year, label="Date"):
Nabin Haitcfecd2b2013-07-11 17:49:18 +053040 years = [f[0] for f in get_fiscal_years(date, label=label)]
Rushabh Mehtac2563ef2013-02-05 23:25:37 +053041 if fiscal_year not in years:
Rushabh Mehta96075822013-02-05 11:39:49 +053042 webnotes.msgprint(("%(label)s '%(posting_date)s': " + _("not within Fiscal Year") + \
Rushabh Mehta2e8d0782013-02-05 11:31:27 +053043 ": '%(fiscal_year)s'") % {
44 "label": label,
45 "posting_date": formatdate(date),
46 "fiscal_year": fiscal_year
47 }, raise_exception=1)
Nabin Hait23941aa2013-01-29 11:32:38 +053048
49@webnotes.whitelist()
50def get_balance_on(account=None, date=None):
51 if not account and webnotes.form_dict.get("account"):
52 account = webnotes.form_dict.get("account")
53 date = webnotes.form_dict.get("date")
54
55 cond = []
56 if date:
57 cond.append("posting_date <= '%s'" % date)
58 else:
59 # get balance of all entries that exist
60 date = nowdate()
61
62 try:
63 year_start_date = get_fiscal_year(date, verbose=0)[1]
64 except FiscalYearError, e:
65 from webnotes.utils import getdate
66 if getdate(date) > getdate(nowdate()):
67 # if fiscal year not found and the date is greater than today
68 # get fiscal year for today's date and its corresponding year start date
69 year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
70 else:
71 # this indicates that it is a date older than any existing fiscal year.
72 # hence, assuming balance as 0.0
73 return 0.0
74
75 acc = webnotes.conn.get_value('Account', account, \
76 ['lft', 'rgt', 'debit_or_credit', 'is_pl_account', 'group_or_ledger'], as_dict=1)
77
78 # for pl accounts, get balance within a fiscal year
79 if acc.is_pl_account == 'Yes':
80 cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" \
81 % year_start_date)
82
83 # different filter for group and ledger - improved performance
84 if acc.group_or_ledger=="Group":
85 cond.append("""exists (
86 select * from `tabAccount` ac where ac.name = gle.account
87 and ac.lft >= %s and ac.rgt <= %s
88 )""" % (acc.lft, acc.rgt))
89 else:
90 cond.append("""gle.account = "%s" """ % (account, ))
91
Nabin Hait23941aa2013-01-29 11:32:38 +053092 bal = webnotes.conn.sql("""
93 SELECT sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
94 FROM `tabGL Entry` gle
Nabin Hait9b09c952013-08-21 17:47:11 +053095 WHERE %s""" % " and ".join(cond))[0][0]
Nabin Hait23941aa2013-01-29 11:32:38 +053096
97 # if credit account, it should calculate credit - debit
98 if bal and acc.debit_or_credit == 'Credit':
99 bal = -bal
100
101 # if bal is None, return 0
Anand Doshi6fa5e422013-07-19 15:33:11 +0530102 return flt(bal)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530103
104@webnotes.whitelist()
105def add_ac(args=None):
106 if not args:
Rushabh Mehta8c2e4e12013-10-02 14:34:25 +0530107 args = webnotes.local.form_dict
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530108 args.pop("cmd")
Rushabh Mehtaaae45532013-02-15 14:39:34 +0530109
Rushabh Mehtac53231a2013-02-18 18:24:28 +0530110 ac = webnotes.bean(args)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530111 ac.doc.doctype = "Account"
112 ac.doc.old_parent = ""
113 ac.doc.freeze_account = "No"
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530114 ac.insert()
115 return ac.doc.name
116
117@webnotes.whitelist()
118def add_cc(args=None):
119 if not args:
Rushabh Mehta8c2e4e12013-10-02 14:34:25 +0530120 args = webnotes.local.form_dict
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530121 args.pop("cmd")
122
Rushabh Mehtac53231a2013-02-18 18:24:28 +0530123 cc = webnotes.bean(args)
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530124 cc.doc.doctype = "Cost Center"
125 cc.doc.old_parent = ""
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530126 cc.insert()
127 return cc.doc.name
128
129def reconcile_against_document(args):
130 """
131 Cancel JV, Update aginst document, split if required and resubmit jv
132 """
133 for d in args:
134 check_if_jv_modified(d)
135
136 against_fld = {
137 'Journal Voucher' : 'against_jv',
138 'Sales Invoice' : 'against_invoice',
139 'Purchase Invoice' : 'against_voucher'
140 }
141
142 d['against_fld'] = against_fld[d['against_voucher_type']]
143
144 # cancel JV
145 jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children=1)
146 jv_obj.make_gl_entries(cancel=1, adv_adj=1)
147
148 # update ref in JV Detail
149 update_against_doc(d, jv_obj)
150
151 # re-submit JV
152 jv_obj = webnotes.get_obj('Journal Voucher', d['voucher_no'], with_children =1)
153 jv_obj.make_gl_entries(cancel = 0, adv_adj =1)
154
155
156def check_if_jv_modified(args):
157 """
158 check if there is already a voucher reference
159 check if amount is same
160 check if jv is submitted
161 """
162 ret = webnotes.conn.sql("""
163 select t2.%(dr_or_cr)s from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2
164 where t1.name = t2.parent and t2.account = '%(account)s'
165 and ifnull(t2.against_voucher, '')=''
166 and ifnull(t2.against_invoice, '')='' and ifnull(t2.against_jv, '')=''
167 and t1.name = '%(voucher_no)s' and t2.name = '%(voucher_detail_no)s'
168 and t1.docstatus=1 and t2.%(dr_or_cr)s = %(unadjusted_amt)s""" % args)
169
170 if not ret:
171 msgprint(_("""Payment Entry has been modified after you pulled it.
172 Please pull it again."""), raise_exception=1)
173
174def update_against_doc(d, jv_obj):
175 """
176 Updates against document, if partial amount splits into rows
177 """
178
179 webnotes.conn.sql("""
180 update `tabJournal Voucher Detail` t1, `tabJournal Voucher` t2
181 set t1.%(dr_or_cr)s = '%(allocated_amt)s',
182 t1.%(against_fld)s = '%(against_voucher)s', t2.modified = now()
183 where t1.name = '%(voucher_detail_no)s' and t1.parent = t2.name""" % d)
184
185 if d['allocated_amt'] < d['unadjusted_amt']:
186 jvd = webnotes.conn.sql("""select cost_center, balance, against_account, is_advance
187 from `tabJournal Voucher Detail` where name = %s""", d['voucher_detail_no'])
188 # new entry with balance amount
189 ch = addchild(jv_obj.doc, 'entries', 'Journal Voucher Detail')
190 ch.account = d['account']
191 ch.cost_center = cstr(jvd[0][0])
192 ch.balance = cstr(jvd[0][1])
193 ch.fields[d['dr_or_cr']] = flt(d['unadjusted_amt']) - flt(d['allocated_amt'])
194 ch.fields[d['dr_or_cr']== 'debit' and 'credit' or 'debit'] = 0
195 ch.against_account = cstr(jvd[0][2])
196 ch.is_advance = cstr(jvd[0][3])
197 ch.docstatus = 1
Nabin Haita76a0682013-02-08 14:04:13 +0530198 ch.save(1)
199
200def get_account_list(doctype, txt, searchfield, start, page_len, filters):
201 if not filters.get("group_or_ledger"):
202 filters["group_or_ledger"] = "Ledger"
203
204 conditions, filter_values = build_filter_conditions(filters)
205
206 return webnotes.conn.sql("""select name, parent_account from `tabAccount`
207 where docstatus < 2 %s and %s like %s order by name limit %s, %s""" %
208 (conditions, searchfield, "%s", "%s", "%s"),
209 tuple(filter_values + ["%%%s%%" % txt, start, page_len]))
210
211def get_cost_center_list(doctype, txt, searchfield, start, page_len, filters):
212 if not filters.get("group_or_ledger"):
213 filters["group_or_ledger"] = "Ledger"
214
215 conditions, filter_values = build_filter_conditions(filters)
216
217 return webnotes.conn.sql("""select name, parent_cost_center from `tabCost Center`
218 where docstatus < 2 %s and %s like %s order by name limit %s, %s""" %
219 (conditions, searchfield, "%s", "%s", "%s"),
Anand Doshi7da72dd2013-03-20 17:00:41 +0530220 tuple(filter_values + ["%%%s%%" % txt, start, page_len]))
221
222def remove_against_link_from_jv(ref_type, ref_no, against_field):
223 webnotes.conn.sql("""update `tabJournal Voucher Detail` set `%s`=null,
224 modified=%s, modified_by=%s
225 where `%s`=%s and docstatus < 2""" % (against_field, "%s", "%s", against_field, "%s"),
226 (now(), webnotes.session.user, ref_no))
227
228 webnotes.conn.sql("""update `tabGL Entry`
229 set against_voucher_type=null, against_voucher=null,
230 modified=%s, modified_by=%s
231 where against_voucher_type=%s and against_voucher=%s
Nabin Hait9b09c952013-08-21 17:47:11 +0530232 and voucher_no != ifnull(against_voucher, '')""",
Anand Doshi7da72dd2013-03-20 17:00:41 +0530233 (now(), webnotes.session.user, ref_type, ref_no))
Nabin Hait0fc24542013-03-25 11:06:00 +0530234
235@webnotes.whitelist()
236def get_company_default(company, fieldname):
237 value = webnotes.conn.get_value("Company", company, fieldname)
238
239 if not value:
240 msgprint(_("Please mention default value for '") +
241 _(webnotes.get_doctype("company").get_label(fieldname) +
242 _("' in Company: ") + company), raise_exception=True)
243
244 return value
Nabin Hait8b509f52013-05-28 16:52:30 +0530245
246def fix_total_debit_credit():
247 vouchers = webnotes.conn.sql("""select voucher_type, voucher_no,
248 sum(debit) - sum(credit) as diff
249 from `tabGL Entry`
250 group by voucher_type, voucher_no
251 having sum(ifnull(debit, 0)) != sum(ifnull(credit, 0))""", as_dict=1)
252
253 for d in vouchers:
254 if abs(d.diff) > 0:
255 dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
256
257 webnotes.conn.sql("""update `tabGL Entry` set %s = %s + %s
258 where voucher_type = %s and voucher_no = %s and %s > 0 limit 1""" %
259 (dr_or_cr, dr_or_cr, '%s', '%s', '%s', dr_or_cr),
Nabin Haitcac622e2013-08-02 11:44:29 +0530260 (d.diff, d.voucher_type, d.voucher_no))
Nabin Haitcac622e2013-08-02 11:44:29 +0530261
Nabin Hait27994c22013-08-26 16:53:30 +0530262def get_stock_and_account_difference(account_list=None, posting_date=None):
263 from stock.utils import get_stock_balance_on
264
265 if not posting_date: posting_date = nowdate()
266
Nabin Haitcac622e2013-08-02 11:44:29 +0530267 difference = {}
Nabin Hait625da792013-09-25 10:32:51 +0530268
269 account_warehouse = dict(webnotes.conn.sql("""select name, master_name from tabAccount
270 where account_type = 'Warehouse' and ifnull(master_name, '') != ''
271 and name in (%s)""" % ', '.join(['%s']*len(account_list)), account_list))
Nabin Haitcac622e2013-08-02 11:44:29 +0530272
Nabin Hait625da792013-09-25 10:32:51 +0530273 for account, warehouse in account_warehouse.items():
Nabin Hait27994c22013-08-26 16:53:30 +0530274 account_balance = get_balance_on(account, posting_date)
Nabin Hait625da792013-09-25 10:32:51 +0530275 stock_value = get_stock_balance_on(warehouse, posting_date)
Nabin Haitaa342012013-08-07 14:21:04 +0530276 if abs(flt(stock_value) - flt(account_balance)) > 0.005:
Nabin Hait469ee712013-08-07 12:33:37 +0530277 difference.setdefault(account, flt(stock_value) - flt(account_balance))
Nabin Haitaa342012013-08-07 14:21:04 +0530278
Nabin Haitcc0e2d12013-08-06 16:19:18 +0530279 return difference
Nabin Haitb4418a42013-08-22 14:38:46 +0530280
Nabin Haitb4418a42013-08-22 14:38:46 +0530281def validate_expense_against_budget(args):
282 args = webnotes._dict(args)
283 if webnotes.conn.get_value("Account", {"name": args.account, "is_pl_account": "Yes",
284 "debit_or_credit": "Debit"}):
285 budget = webnotes.conn.sql("""
286 select bd.budget_allocated, cc.distribution_id
287 from `tabCost Center` cc, `tabBudget Detail` bd
288 where cc.name=bd.parent and cc.name=%s and account=%s and bd.fiscal_year=%s
289 """, (args.cost_center, args.account, args.fiscal_year), as_dict=True)
290
291 if budget and budget[0].budget_allocated:
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530292 yearly_action, monthly_action = webnotes.conn.get_value("Company", args.company,
Nabin Haitb4418a42013-08-22 14:38:46 +0530293 ["yearly_bgt_flag", "monthly_bgt_flag"])
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530294 action_for = action = ""
295
296 if monthly_action in ["Stop", "Warn"]:
297 budget_amount = get_allocated_budget(budget[0].distribution_id,
298 args.posting_date, args.fiscal_year, budget[0].budget_allocated)
Nabin Haitb4418a42013-08-22 14:38:46 +0530299
Nabin Haita3916062013-08-23 10:46:41 +0530300 args["month_end_date"] = webnotes.conn.sql("select LAST_DAY(%s)",
301 args.posting_date)[0][0]
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530302 action_for, action = "Monthly", monthly_action
303
304 elif yearly_action in ["Stop", "Warn"]:
305 budget_amount = budget[0].budget_allocated
306 action_for, action = "Monthly", yearly_action
Nabin Haita3916062013-08-23 10:46:41 +0530307
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530308 if action_for:
309 actual_expense = get_actual_expense(args)
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530310 if actual_expense > budget_amount:
311 webnotes.msgprint(action_for + _(" budget ") + cstr(budget_amount) +
312 _(" for account ") + args.account + _(" against cost center ") +
313 args.cost_center + _(" will exceed by ") +
314 cstr(actual_expense - budget_amount) + _(" after this transaction.")
315 , raise_exception=BudgetError if action=="Stop" else False)
316
317def get_allocated_budget(distribution_id, posting_date, fiscal_year, yearly_budget):
318 if distribution_id:
319 distribution = {}
320 for d in webnotes.conn.sql("""select bdd.month, bdd.percentage_allocation
321 from `tabBudget Distribution Detail` bdd, `tabBudget Distribution` bd
322 where bdd.parent=bd.name and bd.fiscal_year=%s""", fiscal_year, as_dict=1):
323 distribution.setdefault(d.month, d.percentage_allocation)
Nabin Haita3916062013-08-23 10:46:41 +0530324
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530325 dt = webnotes.conn.get_value("Fiscal Year", fiscal_year, "year_start_date")
326 budget_percentage = 0.0
327
328 while(dt <= getdate(posting_date)):
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530329 if distribution_id:
Nabin Haita3916062013-08-23 10:46:41 +0530330 budget_percentage += distribution.get(getdate(dt).strftime("%B"), 0)
Nabin Hait2b06aaa2013-08-22 18:25:43 +0530331 else:
332 budget_percentage += 100.0/12
333
334 dt = add_months(dt, 1)
335
336 return yearly_budget * budget_percentage / 100
Nabin Haitb4418a42013-08-22 14:38:46 +0530337
338def get_actual_expense(args):
Nabin Haita3916062013-08-23 10:46:41 +0530339 args["condition"] = " and posting_date<='%s'" % args.month_end_date \
340 if args.get("month_end_date") else ""
341
Nabin Haitb4418a42013-08-22 14:38:46 +0530342 return webnotes.conn.sql("""
343 select sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
344 from `tabGL Entry`
Nabin Haita3916062013-08-23 10:46:41 +0530345 where account='%(account)s' and cost_center='%(cost_center)s'
346 and fiscal_year='%(fiscal_year)s' and company='%(company)s' %(condition)s
Nabin Hait131939a2013-11-26 15:03:51 +0530347 """ % (args))[0][0]
348
349def rename_account_for(dt, olddn, newdn, merge):
350 old_account = get_account_for(dt, olddn)
351 if old_account:
352 new_account = None
353 if not merge:
354 if old_account == olddn:
355 new_account = webnotes.rename_doc("Account", olddn, newdn)
356 else:
357 existing_new_account = get_account_for(dt, newdn)
358 new_account = webnotes.rename_doc("Account", old_account,
359 existing_new_account or newdn, merge=True if existing_new_account else False)
360
361 if new_account:
362 webnotes.conn.set_value("Account", new_account, "master_name", newdn)
363
364def get_account_for(account_for_doctype, account_for):
365 if account_for_doctype in ["Customer", "Supplier"]:
366 account_for_field = "master_type"
367 elif account_for_doctype == "Warehouse":
368 account_for_field = "account_type"
369
370 return webnotes.conn.get_value("Account", {account_for_field: account_for_doctype,
Nabin Haitac9bcf72013-11-26 01:57:17 -0800371 "master_name": account_for})