blob: 4e850ff8e0b2dd358edc9057f251b1f4c784710d [file] [log] [blame]
Nabin Hait2df4d542013-01-29 11:34:39 +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
18import webnotes
Anand Doshi3543f302013-05-24 19:25:01 +053019from webnotes import _, msgprint
Nabin Hait4166c352013-07-25 15:14:59 +053020from webnotes.utils import flt, cint, today, cstr
Anand Doshi3543f302013-05-24 19:25:01 +053021from setup.utils import get_company_currency, get_price_list_currency
Nabin Haitcfecd2b2013-07-11 17:49:18 +053022from accounts.utils import get_fiscal_year, validate_fiscal_year
Rushabh Mehta4dca4012013-07-25 17:45:59 +053023from utilities.transaction_base import TransactionBase, validate_conversion_rate, validate_uom_is_integer
Anand Doshi3543f302013-05-24 19:25:01 +053024import json
Nabin Hait2df4d542013-01-29 11:34:39 +053025
Nabin Haitbf495c92013-01-30 12:49:08 +053026class AccountsController(TransactionBase):
Saurabh6f753182013-03-20 12:55:28 +053027 def validate(self):
Anand Doshi3543f302013-05-24 19:25:01 +053028 self.set_missing_values(for_validate=True)
29
Nabin Haitcfecd2b2013-07-11 17:49:18 +053030 self.validate_date_with_fiscal_year()
Anand Doshi3543f302013-05-24 19:25:01 +053031 if self.meta.get_field("currency"):
Anand Doshi923d41d2013-05-28 17:23:36 +053032 self.calculate_taxes_and_totals()
Saurabh6f753182013-03-20 12:55:28 +053033 self.validate_value("grand_total", ">=", 0)
Anand Doshi3543f302013-05-24 19:25:01 +053034 self.set_total_in_words()
35
Anand Doshiabc10032013-06-14 17:44:03 +053036 def set_missing_values(self, for_validate=False):
37 for fieldname in ["posting_date", "transaction_date"]:
38 if not self.doc.fields.get(fieldname) and self.meta.get_field(fieldname):
39 self.doc.fields[fieldname] = today()
40 if not self.doc.fiscal_year:
41 self.doc.fiscal_year = get_fiscal_year(self.doc.fields[fieldname])[0]
Nabin Haitcfecd2b2013-07-11 17:49:18 +053042
43 def validate_date_with_fiscal_year(self):
44 if self.meta.get_field("fiscal_year") :
45 date_field = ""
46 if self.meta.get_field("posting_date"):
47 date_field = "posting_date"
48 elif self.meta.get_field("transaction_date"):
49 date_field = "transaction_date"
50
51 if date_field and self.doc.fields[date_field]:
52 validate_fiscal_year(self.doc.fields[date_field], self.doc.fiscal_year,
53 label=self.meta.get_label(date_field))
Anand Doshiabc10032013-06-14 17:44:03 +053054
Anand Doshi3543f302013-05-24 19:25:01 +053055 def set_price_list_currency(self, buying_or_selling):
56 # TODO - change this, since price list now has only one currency allowed
57 if self.meta.get_field("price_list_name") and self.doc.price_list_name and \
58 not self.doc.price_list_currency:
Nabin Hait48a0bd32013-07-23 15:31:39 +053059 self.doc.fields.update(get_price_list_currency(self.doc.price_list_name))
Anand Doshid4e76bc2013-07-15 18:10:51 +053060
Anand Doshi61a2f682013-06-21 17:55:31 +053061 if self.doc.price_list_currency:
62 if not self.doc.plc_conversion_rate:
Anand Doshi99100a42013-07-04 17:13:53 +053063 company_currency = get_company_currency(self.doc.company)
64 if self.doc.price_list_currency == company_currency:
65 self.doc.plc_conversion_rate = 1.0
66 else:
67 exchange = self.doc.price_list_currency + "-" + company_currency
68 self.doc.plc_conversion_rate = flt(webnotes.conn.get_value("Currency Exchange",
69 exchange, "exchange_rate"))
Anand Doshiabc10032013-06-14 17:44:03 +053070
Anand Doshi61a2f682013-06-21 17:55:31 +053071 if not self.doc.currency:
72 self.doc.currency = self.doc.price_list_currency
73 self.doc.conversion_rate = self.doc.plc_conversion_rate
Anand Doshi99100a42013-07-04 17:13:53 +053074
Anand Doshi3543f302013-05-24 19:25:01 +053075 def set_missing_item_details(self, get_item_details):
76 """set missing item values"""
77 for item in self.doclist.get({"parentfield": self.fname}):
78 if item.fields.get("item_code"):
79 args = item.fields.copy().update(self.doc.fields)
80 ret = get_item_details(args)
81 for fieldname, value in ret.items():
82 if self.meta.get_field(fieldname, parentfield=self.fname) and \
Anand Doshi99100a42013-07-04 17:13:53 +053083 item.fields.get(fieldname) is None and value is not None:
Anand Doshi3543f302013-05-24 19:25:01 +053084 item.fields[fieldname] = value
85
Anand Doshi99100a42013-07-04 17:13:53 +053086 def set_taxes(self, tax_parentfield, tax_master_field):
Anand Doshi3543f302013-05-24 19:25:01 +053087 if not self.meta.get_field(tax_parentfield):
88 return
89
Anand Doshi99100a42013-07-04 17:13:53 +053090 tax_master_doctype = self.meta.get_field(tax_master_field).options
91
Anand Doshi3543f302013-05-24 19:25:01 +053092 if not self.doclist.get({"parentfield": tax_parentfield}):
93 if not self.doc.fields.get(tax_master_field):
94 # get the default tax master
95 self.doc.fields[tax_master_field] = \
Anand Doshi99100a42013-07-04 17:13:53 +053096 webnotes.conn.get_value(tax_master_doctype, {"is_default": 1})
Anand Doshi3543f302013-05-24 19:25:01 +053097
Anand Doshi99100a42013-07-04 17:13:53 +053098 self.append_taxes_from_master(tax_parentfield, tax_master_field, tax_master_doctype)
99
100 def append_taxes_from_master(self, tax_parentfield, tax_master_field, tax_master_doctype=None):
101 if self.doc.fields.get(tax_master_field):
102 if not tax_master_doctype:
103 tax_master_doctype = self.meta.get_field(tax_master_field).options
104
105 tax_doctype = self.meta.get_field(tax_parentfield).options
106
107 from webnotes.model import default_fields
108 tax_master = webnotes.bean(tax_master_doctype, self.doc.fields.get(tax_master_field))
109
110 for i, tax in enumerate(tax_master.doclist.get({"parentfield": tax_parentfield})):
111 for fieldname in default_fields:
112 tax.fields[fieldname] = None
113
114 tax.fields.update({
115 "doctype": tax_doctype,
116 "parentfield": tax_parentfield,
117 "idx": i+1
118 })
119
120 self.doclist.append(tax)
Anand Doshi3543f302013-05-24 19:25:01 +0530121
122 def calculate_taxes_and_totals(self):
Anand Doshid4e76bc2013-07-15 18:10:51 +0530123 # validate conversion rate
124 if not self.doc.currency:
125 self.doc.currency = get_company_currency(self.doc.company)
126 self.doc.conversion_rate = 1.0
127 else:
128 validate_conversion_rate(self.doc.currency, self.doc.conversion_rate,
129 self.meta.get_label("conversion_rate"), self.doc.company)
130
Anand Doshi3543f302013-05-24 19:25:01 +0530131 self.doc.conversion_rate = flt(self.doc.conversion_rate)
Anand Doshi3543f302013-05-24 19:25:01 +0530132 self.item_doclist = self.doclist.get({"parentfield": self.fname})
133 self.tax_doclist = self.doclist.get({"parentfield": self.other_fname})
134
135 self.calculate_item_values()
136 self.initialize_taxes()
137
138 if hasattr(self, "determine_exclusive_rate"):
139 self.determine_exclusive_rate()
140
141 self.calculate_net_total()
142 self.calculate_taxes()
143 self.calculate_totals()
144 self._cleanup()
145
146 # TODO
147 # print format: show net_total_export instead of net_total
148
149 def initialize_taxes(self):
150 for tax in self.tax_doclist:
151 tax.item_wise_tax_detail = {}
152 for fieldname in ["tax_amount", "total",
153 "tax_amount_for_current_item", "grand_total_for_current_item",
154 "tax_fraction_for_current_item", "grand_total_fraction_for_current_item"]:
155 tax.fields[fieldname] = 0.0
156
157 self.validate_on_previous_row(tax)
158 self.validate_inclusive_tax(tax)
159 self.round_floats_in(tax)
160
161 def validate_on_previous_row(self, tax):
162 """
163 validate if a valid row id is mentioned in case of
164 On Previous Row Amount and On Previous Row Total
165 """
166 if tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"] and \
167 (not tax.row_id or cint(tax.row_id) >= tax.idx):
168 msgprint((_("Row") + " # %(idx)s [%(taxes_doctype)s]: " + \
169 _("Please specify a valid") + " %(row_id_label)s") % {
170 "idx": tax.idx,
171 "taxes_doctype": tax.doctype,
172 "row_id_label": self.meta.get_label("row_id",
173 parentfield=self.other_fname)
174 }, raise_exception=True)
175
176 def validate_inclusive_tax(self, tax):
177 def _on_previous_row_error(row_range):
178 msgprint((_("Row") + " # %(idx)s [%(doctype)s]: " +
179 _("to be included in Item's rate, it is required that: ") +
180 " [" + _("Row") + " # %(row_range)s] " + _("also be included in Item's rate")) % {
181 "idx": tax.idx,
182 "doctype": tax.doctype,
183 "inclusive_label": self.meta.get_label("included_in_print_rate",
184 parentfield=self.other_fname),
185 "charge_type_label": self.meta.get_label("charge_type",
186 parentfield=self.other_fname),
187 "charge_type": tax.charge_type,
188 "row_range": row_range
189 }, raise_exception=True)
190
191 if cint(tax.included_in_print_rate):
192 if tax.charge_type == "Actual":
193 # inclusive tax cannot be of type Actual
194 msgprint((_("Row")
195 + " # %(idx)s [%(doctype)s]: %(charge_type_label)s = \"%(charge_type)s\" "
196 + "cannot be included in Item's rate") % {
197 "idx": tax.idx,
198 "doctype": tax.doctype,
199 "charge_type_label": self.meta.get_label("charge_type",
200 parentfield=self.other_fname),
201 "charge_type": tax.charge_type,
202 }, raise_exception=True)
203 elif tax.charge_type == "On Previous Row Amount" and \
204 not cint(self.tax_doclist[tax.row_id - 1].included_in_print_rate):
205 # referred row should also be inclusive
206 _on_previous_row_error(tax.row_id)
207 elif tax.charge_type == "On Previous Row Total" and \
208 not all([cint(t.included_in_print_rate) for t in self.tax_doclist[:tax.row_id - 1]]):
209 # all rows about the reffered tax should be inclusive
210 _on_previous_row_error("1 - %d" % (tax.row_id,))
211
212 def calculate_taxes(self):
213 for item in self.item_doclist:
214 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
215
216 for i, tax in enumerate(self.tax_doclist):
217 # tax_amount represents the amount of tax for the current step
218 current_tax_amount = self.get_current_tax_amount(item, tax, item_tax_map)
219
220 if hasattr(self, "set_item_tax_amount"):
221 self.set_item_tax_amount(item, tax, current_tax_amount)
222
223 # case when net total is 0 but there is an actual type charge
224 # in this case add the actual amount to tax.tax_amount
225 # and tax.grand_total_for_current_item for the first such iteration
226 if tax.charge_type=="Actual" and \
227 not (current_tax_amount or self.doc.net_total or tax.tax_amount):
228 zero_net_total_adjustment = flt(tax.rate, self.precision("tax_amount", tax))
229 current_tax_amount += zero_net_total_adjustment
230
231 # store tax_amount for current item as it will be used for
232 # charge type = 'On Previous Row Amount'
233 tax.tax_amount_for_current_item = current_tax_amount
234
235 # accumulate tax amount into tax.tax_amount
236 tax.tax_amount += current_tax_amount
237
Anand Doshi3543f302013-05-24 19:25:01 +0530238 if tax.category:
239 # if just for valuation, do not add the tax amount in total
240 # hence, setting it as 0 for further steps
241 current_tax_amount = 0.0 if (tax.category == "Valuation") else current_tax_amount
242
243 current_tax_amount *= -1.0 if (tax.add_deduct_tax == "Deduct") else 1.0
244
245 # Calculate tax.total viz. grand total till that step
246 # note: grand_total_for_current_item contains the contribution of
247 # item's amount, previously applied tax and the current tax on that item
248 if i==0:
249 tax.grand_total_for_current_item = flt(item.amount +
250 current_tax_amount, self.precision("total", tax))
251
252 else:
253 tax.grand_total_for_current_item = \
254 flt(self.tax_doclist[i-1].grand_total_for_current_item +
255 current_tax_amount, self.precision("total", tax))
256
257 # in tax.total, accumulate grand total of each item
258 tax.total += tax.grand_total_for_current_item
259
260 def get_current_tax_amount(self, item, tax, item_tax_map):
261 tax_rate = self._get_tax_rate(tax, item_tax_map)
262 current_tax_amount = 0.0
263
264 if tax.charge_type == "Actual":
265 # distribute the tax amount proportionally to each item row
266 actual = flt(tax.rate, self.precision("tax_amount", tax))
267 current_tax_amount = (self.doc.net_total
268 and ((item.amount / self.doc.net_total) * actual)
269 or 0)
270 elif tax.charge_type == "On Net Total":
271 current_tax_amount = (tax_rate / 100.0) * item.amount
272 elif tax.charge_type == "On Previous Row Amount":
273 current_tax_amount = (tax_rate / 100.0) * \
274 self.tax_doclist[cint(tax.row_id) - 1].tax_amount_for_current_item
275 elif tax.charge_type == "On Previous Row Total":
276 current_tax_amount = (tax_rate / 100.0) * \
277 self.tax_doclist[cint(tax.row_id) - 1].grand_total_for_current_item
Anand Doshi53b73422013-05-31 11:50:01 +0530278
279 current_tax_amount = flt(current_tax_amount, self.precision("tax_amount", tax))
280
281 # store tax breakup for each item
282 tax.item_wise_tax_detail[item.item_code or item.item_name] = [tax_rate, current_tax_amount]
Anand Doshi3543f302013-05-24 19:25:01 +0530283
Anand Doshi53b73422013-05-31 11:50:01 +0530284 return current_tax_amount
Anand Doshi3543f302013-05-24 19:25:01 +0530285
286 def _load_item_tax_rate(self, item_tax_rate):
287 return json.loads(item_tax_rate) if item_tax_rate else {}
288
289 def _get_tax_rate(self, tax, item_tax_map):
290 if item_tax_map.has_key(tax.account_head):
291 return flt(item_tax_map.get(tax.account_head), self.precision("rate", tax))
292 else:
293 return tax.rate
294
295 def _cleanup(self):
296 for tax in self.tax_doclist:
297 for fieldname in ("grand_total_for_current_item",
298 "tax_amount_for_current_item",
299 "tax_fraction_for_current_item",
300 "grand_total_fraction_for_current_item"):
301 if fieldname in tax.fields:
302 del tax.fields[fieldname]
303
304 tax.item_wise_tax_detail = json.dumps(tax.item_wise_tax_detail)
305
306 def _set_in_company_currency(self, item, print_field, base_field):
307 """set values in base currency"""
308 item.fields[base_field] = flt((flt(item.fields[print_field],
309 self.precision(print_field, item)) * self.doc.conversion_rate),
310 self.precision(base_field, item))
Anand Doshi923d41d2013-05-28 17:23:36 +0530311
312 def calculate_total_advance(self, parenttype, advance_parentfield):
313 if self.doc.doctype == parenttype and self.doc.docstatus < 2:
314 sum_of_allocated_amount = sum([flt(adv.allocated_amount, self.precision("allocated_amount", adv))
315 for adv in self.doclist.get({"parentfield": advance_parentfield})])
316
317 self.doc.total_advance = flt(sum_of_allocated_amount, self.precision("total_advance"))
318
319 self.calculate_outstanding_amount()
Saurabh6f753182013-03-20 12:55:28 +0530320
Nabin Hait8c7234f2013-03-11 16:32:33 +0530321 def get_gl_dict(self, args, cancel=None):
Nabin Hait2df4d542013-01-29 11:34:39 +0530322 """this method populates the common properties of a gl entry record"""
Anand Doshi1cf73912013-03-15 13:42:31 +0530323 if cancel is None:
324 cancel = (self.doc.docstatus == 2)
325
Nabin Hait2df4d542013-01-29 11:34:39 +0530326 gl_dict = {
327 'company': self.doc.company,
328 'posting_date': self.doc.posting_date,
329 'voucher_type': self.doc.doctype,
330 'voucher_no': self.doc.name,
331 'aging_date': self.doc.fields.get("aging_date") or self.doc.posting_date,
332 'remarks': self.doc.remarks,
Anand Doshi1cf73912013-03-15 13:42:31 +0530333 'is_cancelled': cancel and "Yes" or "No",
Nabin Hait2df4d542013-01-29 11:34:39 +0530334 'fiscal_year': self.doc.fiscal_year,
335 'debit': 0,
336 'credit': 0,
337 'is_opening': self.doc.fields.get("is_opening") or "No",
338 }
339 gl_dict.update(args)
340 return gl_dict
Anand Doshia1d4b782013-02-26 18:09:47 +0530341
Anand Doshi613cb6a2013-02-06 17:33:46 +0530342 def clear_unallocated_advances(self, childtype, parentfield):
343 self.doclist.remove_items({"parentfield": parentfield, "allocated_amount": ["in", [0, None, ""]]})
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530344
Anand Doshi613cb6a2013-02-06 17:33:46 +0530345 webnotes.conn.sql("""delete from `tab%s` where parentfield=%s and parent = %s
346 and ifnull(allocated_amount, 0) = 0""" % (childtype, '%s', '%s'), (parentfield, self.doc.name))
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530347
Anand Doshi613cb6a2013-02-06 17:33:46 +0530348 def get_advances(self, account_head, child_doctype, parentfield, dr_or_cr):
Nabin Haitfb3fd6e2013-01-30 19:16:13 +0530349 res = webnotes.conn.sql("""select t1.name as jv_no, t1.remark,
350 t2.%s as amount, t2.name as jv_detail_no
351 from `tabJournal Voucher` t1, `tabJournal Voucher Detail` t2
352 where t1.name = t2.parent and t2.account = %s and t2.is_advance = 'Yes'
353 and (t2.against_voucher is null or t2.against_voucher = '')
354 and (t2.against_invoice is null or t2.against_invoice = '')
355 and (t2.against_jv is null or t2.against_jv = '')
356 and t1.docstatus = 1 order by t1.posting_date""" %
357 (dr_or_cr, '%s'), account_head, as_dict=1)
358
359 self.doclist = self.doc.clear_table(self.doclist, parentfield)
360 for d in res:
Anand Doshi613cb6a2013-02-06 17:33:46 +0530361 self.doclist.append({
362 "doctype": child_doctype,
363 "parentfield": parentfield,
364 "journal_voucher": d.jv_no,
365 "jv_detail_no": d.jv_detail_no,
366 "remarks": d.remark,
367 "advance_amount": flt(d.amount),
368 "allocate_amount": 0
Anand Doshia1d4b782013-02-26 18:09:47 +0530369 })
Nabin Hait3b999222013-07-09 12:35:52 +0530370
371 def validate_multiple_billing(self, ref_dt, item_ref_dn, based_on):
372 for item in self.doclist.get({"parentfield": "entries"}):
373 if item.fields.get(item_ref_dn):
374 already_billed = webnotes.conn.sql("""select sum(%s) from `tab%s`
375 where %s=%s and docstatus=1""" % (based_on, self.tname, item_ref_dn, '%s'),
376 item.fields[item_ref_dn])[0][0]
Nabin Hait4166c352013-07-25 15:14:59 +0530377
378 max_allowed_amt = webnotes.conn.get_value(ref_dt + " Item",
379 item.fields[item_ref_dn], based_on)
380
381 if flt(already_billed) + flt(item.fields[based_on]) > max_allowed_amt:
382 webnotes.msgprint(_("Row ")+ cstr(item.idx) + ": " + cstr(item.item_code) +
383 _(" will be over-billed against mentioned ") + cstr(ref_dt) +
384 _(". Max allowed " + cstr(based_on) + ": " + cstr(max_allowed_amt)),
385 raise_exception=1)
Anand Doshia1d4b782013-02-26 18:09:47 +0530386
Nabin Hait0fc24542013-03-25 11:06:00 +0530387 def get_company_default(self, fieldname):
388 from accounts.utils import get_company_default
389 return get_company_default(self.doc.company, fieldname)
Nabin Hait2bd37772013-07-08 19:00:29 +0530390
Anand Doshia1d4b782013-02-26 18:09:47 +0530391
392 @property
393 def stock_items(self):
394 if not hasattr(self, "_stock_items"):
Nabin Haitebd51442013-04-23 15:36:26 +0530395 self._stock_items = []
396 item_codes = list(set(item.item_code for item in
397 self.doclist.get({"parentfield": self.fname})))
398 if item_codes:
399 self._stock_items = [r[0] for r in webnotes.conn.sql("""select name
400 from `tabItem` where name in (%s) and is_stock_item='Yes'""" % \
401 (", ".join((["%s"]*len(item_codes))),), item_codes)]
Nabin Hait80abad22013-03-19 18:18:52 +0530402
Anand Doshi4a7248e2013-02-27 18:10:30 +0530403 return self._stock_items
404
405 @property
406 def company_abbr(self):
407 if not hasattr(self, "_abbr"):
408 self._abbr = webnotes.conn.get_value("Company", self.doc.company, "abbr")
409
Anand Doshi21f4ea32013-05-10 18:08:32 +0530410 return self._abbr