blob: 7aa8e239d6d77dd62d96e52fc5fe97c2defc584c [file] [log] [blame]
Anand Doshic2fb0392012-11-29 19:55:30 +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
19import webnotes.model
20from webnotes import _, msgprint
21from webnotes.utils import cint, flt
22from webnotes.model.utils import round_doc
23import json
24
25from controllers.transaction_controller import TransactionController
26
27class TaxController(TransactionController):
28 def append_taxes(self):
29 """append taxes as per tax master link field"""
30 # clear tax table
31 self.doclist = self.doclist.get({"parentfield": ["!=",
32 self.fmap.taxes_and_charges]})
33
34 tax_master_doctype = self.meta.get_options(self.fmap.taxes_and_charges_master)
35 master_tax_list = webnotes.get_doclist(tax_master_doctype,
36 self.doc.fields.get(self.fmap.taxes_and_charges_master)).get(
37 {"parentfield": self.fmap.taxes_and_charges})
38
39 for base_tax in master_tax_list:
40 tax = DictObj([[field, base_tax.fields.get(field)]
41 for field in base_tax.fields
42 if field not in webnotes.model.default_fields])
43 tax.update({
44 "doctype": self.meta.get_options(self.fmap.taxes_and_charges),
45 "parentfield": self.fmap.taxes_and_charges,
46 "rate": flt(tax.rate, self.precision.tax.rate),
47 })
48 self.doclist.append(tax)
49
50 def calculate_taxes_and_totals(self):
51 """
52 Calculates:
53 * amount for each item
54 * valuation_tax_amount for each item,
55 * tax amount and tax total for each tax
56 * net total
57 * total taxes
58 * grand total
59 """
60 self.doc.fields[self.fmap.exchange_rate] = \
61 flt(self.doc.fields.get(self.fmap.exchange_rate),
62 self.precision.main[self.fmap.exchange_rate])
63
64 self.calculate_item_values()
65
66 self.initialize_taxes()
67 if self.meta.get_field("included_in_print_rate",
68 parentfield=self.fmap.taxes_and_charges):
69 self.determine_exclusive_rate()
70
71 self.calculate_net_total()
72 self.calculate_taxes()
73 self.calculate_totals()
74 self.set_amount_in_words()
Anand Doshid3b82cf2012-12-04 11:49:37 +053075 self.cleanup()
Anand Doshic2fb0392012-11-29 19:55:30 +053076
77 def calculate_item_values(self):
78 def _set_base(item, print_field, base_field):
79 """set values in base currency"""
80 item.fields[base_field] = flt((flt(item.fields[print_field],
81 self.precision.item[print_field]) * \
82 self.doc.fields.get(self.fmap.exchange_rate)),
83 self.precision.item[base_field])
84
85 for item in self.item_doclist:
86 round_doc(item, self.precision.item)
87
88 if item.fields.get(self.fmap.discount) == 100:
89 if not item.fields.get(self.fmap.print_ref_rate):
90 item.fields[self.fmap.print_ref_rate] = \
91 item.fields.get(self.fmap.print_rate)
92 item.fields[self.fmap.print_rate] = 0
93 else:
94 if item.fields.get(self.fmap.print_ref_rate):
95 item.fields[self.fmap.print_rate] = \
96 flt(item.fields.get(self.fmap.print_ref_rate) *
97 (1.0 - (item.fields.get(self.fmap.discount) / 100.0)),
98 self.precision.item[self.fmap.print_rate])
99 else:
100 # assume that print rate and discount are specified
101 item.fields[self.fmap.print_ref_rate] = \
102 flt(item.fields.get(self.fmap.print_rate) /
103 (1.0 - (item.fields.get(self.fmap.discount) / 100.0)),
104 self.precision.item[self.fmap.print_ref_rate])
105
106 item.fields[self.fmap.print_amount] = \
107 flt(item.fields.get(self.fmap.print_rate) * \
Anand Doshid3b82cf2012-12-04 11:49:37 +0530108 item.fields.get("qty"),
Anand Doshic2fb0392012-11-29 19:55:30 +0530109 self.precision.item[self.fmap.print_amount])
110
111 _set_base(item, self.fmap.print_ref_rate, self.fmap.ref_rate)
112 _set_base(item, self.fmap.print_rate, self.fmap.rate)
Anand Doshid3b82cf2012-12-04 11:49:37 +0530113 _set_base(item, self.fmap.print_amount, "amount")
Anand Doshic2fb0392012-11-29 19:55:30 +0530114
115 def initialize_taxes(self):
116 for tax in self.tax_doclist:
117 # initialize totals to 0
118 tax.tax_amount = tax.total = tax.total_print = 0
119 tax.grand_total_for_current_item = tax.tax_amount_for_current_item = 0
120
121 # for actual type, user can mention actual tax amount in tax.tax_amount_print
122 if tax.charge_type != "Actual" or tax.rate:
123 tax.tax_amount_print = 0
124
125 self.validate_on_previous_row(tax)
126 self.validate_included_tax(tax)
127
128 # round relevant values
129 round_doc(tax, self.precision.tax)
130
131 def calculate_net_total(self):
132 self.doc.net_total = 0
133 self.doc.fields[self.fmap.net_total_print] = 0
134
135 for item in self.item_doclist:
136 self.doc.net_total += item.amount
137 self.doc.fields[self.fmap.net_total_print] += \
138 item.fields.get(self.fmap.print_amount)
Anand Doshi188f9772012-12-04 16:17:48 +0530139
Anand Doshic2fb0392012-11-29 19:55:30 +0530140 self.doc.net_total = flt(self.doc.net_total, self.precision.main.net_total)
141 self.doc.fields[self.fmap.net_total_print] = \
142 flt(self.doc.fields.get(self.fmap.net_total_print),
143 self.precision.main[self.fmap.net_total_print])
144
145 def calculate_taxes(self):
146 for item in self.item_doclist:
147 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
148 item.fields[self.fmap.valuation_tax_amount] = 0
149
150 for i, tax in enumerate(self.tax_doclist):
151 # tax_amount represents the amount of tax for the current step
152 current_tax_amount = self.get_current_tax_amount(item, tax, item_tax_map)
153
154 if hasattr(self, "set_valuation_tax_amount"):
155 self.set_valuation_tax_amount(item, tax, current_tax_amount)
156
157 # case when net total is 0 but there is an actual type charge
158 # in this case add the actual amount to tax.tax_amount
159 # and tax.grand_total_for_current_item for the first such iteration
160 if not (current_tax_amount or self.doc.net_total or tax.tax_amount) and \
161 tax.charge_type=="Actual":
162 zero_net_total_adjustment = flt((tax.tax_amount_print *
163 self.doc.fields.get(self.fmap.exchange_rate)) or tax.rate,
164 self.precision.tax.tax_amount)
165 current_tax_amount += zero_net_total_adjustment
166
167 # store tax_amount for current item as it will be used for
168 # charge type = 'On Previous Row Amount'
169 tax.tax_amount_for_current_item = current_tax_amount
170
171 # accumulate tax amount into tax.tax_amount
172 tax.tax_amount += tax.tax_amount_for_current_item
173
174 # accumulate tax_amount_print only if tax is not included
175 # and if tax amount of actual type is entered in 'rate' field
176 if not cint(tax.included_in_print_rate) and (tax.charge_type != "Actual"
177 or tax.rate):
178 tax.tax_amount_print += flt((tax.tax_amount_for_current_item /
179 self.doc.fields.get(self.fmap.exchange_rate)),
180 self.precision.tax.tax_amount_print)
181
182 if tax.category == "Valuation":
183 # if just for valuation, do not add the tax amount in total
184 # hence, setting it as 0 for further steps
185 current_tax_amount = 0
186
187 # Calculate tax.total viz. grand total till that step
188 # note: grand_total_for_current_item contains the contribution of
189 # item's amount, previously applied tax and the current tax on that item
190 if i==0:
191 tax.grand_total_for_current_item = flt(item.amount +
192 current_tax_amount, self.precision.tax.total)
193
194 # if inclusive pricing, current_tax_amount should not be considered
195 if cint(tax.included_in_print_rate):
196 current_tax_amount = 0
197
198 tax.grand_total_print_for_current_item = \
199 flt(item.fields.get(self.fmap.print_amount) +
200 (current_tax_amount / self.doc.fields.get(
201 self.fmap.exchange_rate)),
202 self.precision.tax.total_print)
203 else:
204 tax.grand_total_for_current_item = \
205 flt(self.tax_doclist[i-1].grand_total_for_current_item +
206 current_tax_amount, self.precision.tax.total)
207
208 # if inclusive pricing, current_tax_amount should not be considered
209 if cint(tax.included_in_print_rate):
210 current_tax_amount = 0
211
212 tax.grand_total_print_for_current_item = \
213 flt(self.tax_doclist[i-1].grand_total_print_for_current_item +
214 (current_tax_amount / self.doc.fields.get(
215 self.fmap.exchange_rate)),
216 self.precision.tax.total_print)
217
218 # in tax.total, accumulate grand total of each item
219 tax.total += tax.grand_total_for_current_item
220 tax.total_print += tax.grand_total_print_for_current_item
221
222 # TODO store tax_breakup for each item
223
224 def get_current_tax_amount(self, item, tax, item_tax_map):
225 tax_rate = self._get_tax_rate(tax, item_tax_map)
226
227 if tax.charge_type == "Actual":
228 # distribute the tax amount proportionally to each item row
229 actual = flt(tax.rate or (tax.tax_amount_print * \
230 self.doc.fields.get(self.fmap.exchange_rate)),
231 self.precision.tax.tax_amount)
232 current_tax_amount = (self.doc.net_total
233 and ((item.amount / self.doc.net_total) * actual)
234 or 0)
235 elif tax.charge_type == "On Net Total":
236 current_tax_amount = (tax_rate / 100.0) * item.amount
237 elif tax.charge_type == "On Previous Row Amount":
238 current_tax_amount = (tax_rate / 100.0) * \
239 self.tax_doclist[cint(tax.row_id) - 1].tax_amount_for_current_item
240 elif tax.charge_type == "On Previous Row Total":
241 current_tax_amount = (tax_rate / 100.0) * \
242 self.tax_doclist[cint(tax.row_id) - 1].grand_total_for_current_item
243
244 return flt(current_tax_amount, self.precision.tax.tax_amount)
245
246 def calculate_totals(self):
247 if self.tax_doclist:
248 self.doc.grand_total = flt(self.tax_doclist[-1].total,
249 self.precision.main.grand_total)
250 self.doc.fields[self.fmap.grand_total_print] = \
251 flt(self.tax_doclist[-1].total_print,
252 self.precision.main[self.fmap.grand_total_print])
253 else:
254 self.doc.grand_total = flt(self.doc.net_total,
255 self.precision.main.grand_total)
256 self.doc.fields[self.fmap.grand_total_print] = \
257 flt(self.doc.fields.get(self.fmap.net_total_print),
258 self.precision.main[self.fmap.grand_total_print])
259
260 self.doc.fields[self.fmap.taxes_and_charges_total] = \
261 flt(self.doc.grand_total - self.doc.net_total,
262 self.precision.main[self.fmap.taxes_and_charges_total])
263
264 self.doc.taxes_and_charges_total_print = \
265 flt(self.doc.fields.get(self.fmap.grand_total_print) - \
266 self.doc.fields.get(self.fmap.net_total_print),
267 self.precision.main.taxes_and_charges_total_print)
268
269 self.doc.rounded_total = round(self.doc.grand_total)
270 self.doc.fields[self.fmap.rounded_total_print] = \
271 round(self.doc.fields.get(self.fmap.grand_total_print))
Anand Doshi188f9772012-12-04 16:17:48 +0530272
Anand Doshic2fb0392012-11-29 19:55:30 +0530273 def set_amount_in_words(self):
274 from webnotes.utils import money_in_words
275 base_currency = webnotes.conn.get_value("Company", self.doc.currency,
276 "default_currency")
277
278 self.doc.fields[self.fmap.grand_total_in_words] = \
279 money_in_words(self.doc.grand_total, base_currency)
280 self.doc.fields[self.fmap.rounded_total_in_words] = \
281 money_in_words(self.doc.rounded_total, base_currency)
282
283 self.doc.fields[self.fmap.grand_total_in_words_print] = \
284 money_in_words(self.doc.fields.get(self.fmap.grand_total_print),
285 self.doc.currency)
286 self.doc.fields[self.fmap.rounded_total_in_words_print] = \
287 money_in_words(self.doc.fields.get(self.fmap.rounded_total_print),
288 self.doc.currency)
289
290 def validate_on_previous_row(self, tax):
291 """
292 validate if a valid row id is mentioned in case of
293 On Previous Row Amount and On Previous Row Total
294 """
295 if tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"] and \
296 (not tax.row_id or cint(tax.row_id) >= tax.idx):
297 msgprint((_("Row") + " # %(idx)s [%(taxes_doctype)s]: " + \
298 _("Please specify a valid") + " %(row_id_label)s") % {
299 "idx": tax.idx,
300 "taxes_doctype": tax.parenttype,
301 "row_id_label": self.meta.get_label("row_id",
302 parentfield=self.fmap.taxes_and_charges)
303 }, raise_exception=True)
304
305 def validate_included_tax(self, tax):
306 """
307 validate conditions related to "Is this Tax Included in Rate?"
308 """
309 def _on_previous_row_error(tax, row_range):
310 msgprint((_("Row") + " # %(idx)s [%(taxes_doctype)s]: " + \
311 _("If") + " '%(inclusive_label)s' " + _("is checked for") + \
312 " '%(charge_type_label)s' = '%(charge_type)s', " + _("then") + " " + \
313 _("Row") + " # %(row_range)s " + _("should also have") + \
314 " '%(inclusive_label)s' = " + _("checked")) % {
315 "idx": tax.idx,
316 "taxes_doctype": tax.doctype,
317 "inclusive_label": self.meta.get_label("included_in_print_rate",
318 parentfield=self.fmap.taxes_and_charges),
319 "charge_type_label": self.meta.get_label("charge_type",
320 parentfield=self.fmap.taxes_and_charges),
321 "charge_type": tax.charge_type,
322 "row_range": row_range,
323 }, raise_exception=True)
324
325 if cint(tax.included_in_print_rate):
326 if tax.charge_type == "Actual":
327 # now inclusive rate for type 'Actual'
328 msgprint((_("Row") + " # %(idx)s [%(taxes_doctype)s]: " + \
329 "'%(charge_type_label)s' = '%(charge_type)s' " + \
330 _("cannot be included in item's rate")) % {
331 "idx": tax.idx,
332 "taxes_doctype": self.meta.get_options(
333 self.fmap.taxes_and_charges),
334 "charge_type_label": self.meta.get_label("charge_type",
335 parentfield=self.fmap.taxes_and_charges),
336 "charge_type": tax.charge_type,
337 }, raise_exception=True)
338
339 elif tax.charge_type == "On Previous Row Amount" and \
340 not cint(self.tax_doclist[cint(tax.row_id) - 1]\
341 .included_in_print_rate):
342 # for an inclusive tax of type "On Previous Row Amount",
343 # dependent row should also be inclusive
344 _on_previous_row_error(tax, tax.row_id)
345
346 elif tax.charge_type == "On Previous Row Total" and \
347 not all([cint(t.included_in_print_rate) \
348 for t in self.tax_doclist[:tax.idx - 1]]):
349 # for an inclusive tax of type "On Previous Row Total",
350 # all rows above it should also be inclusive
351 _on_previous_row_error(tax, "1 - %d" % (tax.idx - 1))
352
353 def determine_exclusive_rate(self):
354 if not any((cint(tax.included_in_print_rate) for tax in self.tax_doclist)):
355 # if no tax is marked as included in print rate, no need to proceed further
356 return
357
358 for item in self.item_doclist:
359 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
360
361 cumulated_tax_fraction = 0
362
363 for i, tax in enumerate(self.tax_doclist):
364 if cint(tax.included_in_print_rate):
365 tax.tax_fraction_for_current_item = \
366 self.get_current_tax_fraction(tax, item_tax_map)
367 else:
368 tax.tax_fraction_for_current_item = 0
369
370 if i==0:
371 tax.grand_total_fraction_for_current_item = 1 + \
372 tax.tax_fraction_for_current_item
373 else:
374 tax.grand_total_fraction_for_current_item = \
375 self.tax_doclist[i-1].grand_total_fraction_for_current_item \
376 + tax.tax_fraction_for_current_item
377
378 cumulated_tax_fraction += tax.tax_fraction_for_current_item
379
380 if cumulated_tax_fraction:
381 item.fields[self.fmap.rate] = \
382 flt((item.fields.get(self.fmap.print_rate) * \
383 self.doc.fields.get(self.fmap.exchange_rate)) /
384 (1 + cumulated_tax_fraction), self.precision.item[self.fmap.rate])
385
386 item.amount = flt(item.fields.get(self.fmap.rate) * item.qty,
387 self.precision.item.amount)
388
389 item.fields[self.fmap.ref_rate] = \
390 flt(item.fields.get(self.fmap.rate) / (1 - \
391 (item.fields.get(self.fmap.discount) / 100.0)),
392 self.precision.item[self.fmap.ref_rate])
393
394 # print item.print_rate, 1+cumulated_tax_fraction, item.rate, item.amount
395 # print "-"*10
396
397 def get_current_tax_fraction(self, tax, item_tax_map):
398 """
399 Get tax fraction for calculating tax exclusive amount
400 from tax inclusive amount
401 """
402 current_tax_fraction = 0
403
404 if cint(tax.included_in_print_rate):
405 tax_rate = self._get_tax_rate(tax, item_tax_map)
406
407 if tax.charge_type == "On Net Total":
408 current_tax_fraction = tax_rate / 100.0
409
410 elif tax.charge_type == "On Previous Row Amount":
411 current_tax_fraction = (tax_rate / 100.0) * \
412 self.tax_doclist[cint(tax.row_id) - 1]\
413 .tax_fraction_for_current_item
414
415 elif tax.charge_type == "On Previous Row Total":
416 current_tax_fraction = (tax_rate / 100.0) * \
417 self.tax_doclist[cint(tax.row_id) - 1]\
418 .grand_total_fraction_for_current_item
419
420 # print tax.account_head, tax_rate, current_tax_fraction
421
422 return current_tax_fraction
423
424 def _load_item_tax_rate(self, item_tax_rate):
425 if not item_tax_rate:
426 return {}
427
428 return json.loads(item_tax_rate)
429
430 def _get_tax_rate(self, tax, item_tax_map):
431 if item_tax_map.has_key(tax.account_head):
432 return flt(item_tax_map.get(tax.account_head), self.precision.tax.rate)
433 else:
434 return tax.rate
Anand Doshid3b82cf2012-12-04 11:49:37 +0530435
436 def cleanup(self):
Anand Doshi188f9772012-12-04 16:17:48 +0530437 def _del(f, doc):
438 if f in doc.fields:
439 del doc.fields[f]
440 elif self.fmap.get(f) and self.fmap.get(f) in doc.fields:
441 del doc.fields[self.fmap.get(f)]
442
Anand Doshid3b82cf2012-12-04 11:49:37 +0530443 for f in ["taxes_and_charges_total_print", "rounded_total_in_words_print",
Anand Doshi188f9772012-12-04 16:17:48 +0530444 "rounded_total_print", "rounded_total_in_words", "rounded_total"]:
445 _del(f, self.doc)
Anand Doshid3b82cf2012-12-04 11:49:37 +0530446
447 for f in ["grand_total_print_for_current_item", "tax_amount_print",
448 "grand_total_for_current_item", "tax_amount_for_current_item",
449 "total_print"]:
450 for doc in self.doclist.get({"parentfield": self.fmap.taxes_and_charges}):
Anand Doshi188f9772012-12-04 16:17:48 +0530451 _del(f, doc)
452
453 for f in ["item_tax_amount"]:
454 for doc in self.doclist.get({"parentfield": self.item_table_field}):
455 _del(f, doc)
456