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