blob: 341b3ca879f70a6cc983945aee0fe37602672f3e [file] [log] [blame]
Nabin Hait3237c752015-02-17 11:11:11 +05301# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
2# License: GNU General Public License v3. See license.txt
3
4from __future__ import unicode_literals
5import json
6from frappe import _, throw
7from frappe.utils import cint, flt, rounded
8from erpnext.setup.utils import get_company_currency
9from erpnext.controllers.accounts_controller import validate_conversion_rate
10
Nabin Haitfe81da22015-02-18 12:23:18 +053011class calculate_taxes_and_totals(object):
Nabin Hait3237c752015-02-17 11:11:11 +053012 def __init__(self, doc):
13 self.doc = doc
14
Nabin Haitfe81da22015-02-18 12:23:18 +053015 self.calculate()
16
Nabin Hait3237c752015-02-17 11:11:11 +053017 def calculate(self):
18 self.discount_amount_applied = False
19 self._calculate()
20
21 if self.doc.meta.get_field("discount_amount"):
22 self.apply_discount_amount()
23
Nabin Haitbd00e812015-02-17 12:50:51 +053024 if self.doc.doctype in ["Sales Invoice", "Purchase Invoice"]:
Nabin Hait3237c752015-02-17 11:11:11 +053025 self.calculate_total_advance()
26
27 def _calculate(self):
28 # validate conversion rate
29 company_currency = get_company_currency(self.doc.company)
30 if not self.doc.currency or self.doc.currency == company_currency:
31 self.doc.currency = company_currency
32 self.doc.conversion_rate = 1.0
33 else:
34 validate_conversion_rate(self.doc.currency, self.doc.conversion_rate,
35 self.doc.meta.get_label("conversion_rate"), self.doc.company)
36
37 self.doc.conversion_rate = flt(self.doc.conversion_rate)
38
39 self.calculate_item_values()
40 self.initialize_taxes()
41
Nabin Haitbd00e812015-02-17 12:50:51 +053042 if self.doc.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
Nabin Hait3237c752015-02-17 11:11:11 +053043 self.determine_exclusive_rate()
44
45 self.calculate_net_total()
46 self.calculate_taxes()
47 self.calculate_totals()
48 self._cleanup()
49
50 def calculate_item_values(self):
51 if not self.discount_amount_applied:
52 for item in self.doc.get("items"):
53 self.doc.round_floats_in(item)
54
55 if item.discount_percentage == 100:
56 item.rate = 0.0
57 elif not item.rate:
58 item.rate = flt(item.price_list_rate * (1.0 - (item.discount_percentage / 100.0)),
59 self.doc.precision("rate", item))
60
61 item.amount = flt(item.rate * item.qty, self.doc.precision("amount", item))
62 item.item_tax_amount = 0.0;
63
64 self._set_in_company_currency(item, "price_list_rate", "base_price_list_rate")
65 self._set_in_company_currency(item, "rate", "base_rate")
66 self._set_in_company_currency(item, "amount", "base_amount")
67
68 def _set_in_company_currency(self, item, print_field, base_field):
69 """set values in base currency"""
70 value_in_company_currency = flt(self.doc.conversion_rate *
71 flt(item.get(print_field), self.doc.precision(print_field, item)), self.doc.precision(base_field, item))
72 item.set(base_field, value_in_company_currency)
73
74 def initialize_taxes(self):
75 for tax in self.doc.get("taxes"):
76 tax.item_wise_tax_detail = {}
77 tax_fields = ["total", "tax_amount_after_discount_amount",
78 "tax_amount_for_current_item", "grand_total_for_current_item",
79 "tax_fraction_for_current_item", "grand_total_fraction_for_current_item"]
80
81 if not self.discount_amount_applied:
82 tax_fields.append("tax_amount")
83
84 for fieldname in tax_fields:
85 tax.set(fieldname, 0.0)
86
87 self.validate_on_previous_row(tax)
88 self.validate_inclusive_tax(tax)
89 self.doc.round_floats_in(tax)
90
91 def validate_on_previous_row(self, tax):
92 """
93 validate if a valid row id is mentioned in case of
94 On Previous Row Amount and On Previous Row Total
95 """
96 if tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"] and \
97 (not tax.row_id or cint(tax.row_id) >= tax.idx):
98 throw(_("Please specify a valid Row ID for {0} in row {1}").format(_(tax.doctype), tax.idx))
99
100 def validate_inclusive_tax(self, tax):
101 def _on_previous_row_error(row_range):
102 throw(_("To include tax in row {0} in Item rate, taxes in rows {1} must also be included").format(tax.idx,
103 row_range))
104
105 if cint(getattr(tax, "included_in_print_rate", None)):
106 if tax.charge_type == "Actual":
107 # inclusive tax cannot be of type Actual
108 throw(_("Charge of type 'Actual' in row {0} cannot be included in Item Rate").format(tax.idx))
109 elif tax.charge_type == "On Previous Row Amount" and \
110 not cint(self.doc.get("taxes")[cint(tax.row_id) - 1].included_in_print_rate):
111 # referred row should also be inclusive
112 _on_previous_row_error(tax.row_id)
113 elif tax.charge_type == "On Previous Row Total" and \
114 not all([cint(t.included_in_print_rate) for t in self.doc.get("taxes")[:cint(tax.row_id) - 1]]):
115 # all rows about the reffered tax should be inclusive
116 _on_previous_row_error("1 - %d" % (tax.row_id,))
117
118 def determine_exclusive_rate(self):
119 if not any((cint(tax.included_in_print_rate) for tax in self.doc.get("taxes"))):
120 # no inclusive tax
121 return
122
123 for item in self.doc.get("items"):
124 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
125 cumulated_tax_fraction = 0
126 for i, tax in enumerate(self.doc.get("taxes")):
127 tax.tax_fraction_for_current_item = self.get_current_tax_fraction(tax, item_tax_map)
128
129 if i==0:
130 tax.grand_total_fraction_for_current_item = 1 + tax.tax_fraction_for_current_item
131 else:
132 tax.grand_total_fraction_for_current_item = \
133 self.doc.get("taxes")[i-1].grand_total_fraction_for_current_item \
134 + tax.tax_fraction_for_current_item
135
136 cumulated_tax_fraction += tax.tax_fraction_for_current_item
137
138 if cumulated_tax_fraction and not self.discount_amount_applied and item.qty:
139 item.base_amount = flt((item.amount * self.doc.conversion_rate) /
140 (1 + cumulated_tax_fraction), self.doc.precision("base_amount", item))
141
142 item.base_rate = flt(item.base_amount / item.qty, self.doc.precision("base_rate", item))
143 item.discount_percentage = flt(item.discount_percentage, self.doc.precision("discount_percentage", item))
144
145 if item.discount_percentage == 100:
146 item.base_price_list_rate = item.base_rate
147 item.base_rate = 0.0
148 else:
149 item.base_price_list_rate = flt(item.base_rate / (1 - (item.discount_percentage / 100.0)),
150 self.doc.precision("base_price_list_rate", item))
151
152 def _load_item_tax_rate(self, item_tax_rate):
153 return json.loads(item_tax_rate) if item_tax_rate else {}
154
155 def get_current_tax_fraction(self, tax, item_tax_map):
156 """
157 Get tax fraction for calculating tax exclusive amount
158 from tax inclusive amount
159 """
160 current_tax_fraction = 0
161
162 if cint(tax.included_in_print_rate):
163 tax_rate = self._get_tax_rate(tax, item_tax_map)
164
165 if tax.charge_type == "On Net Total":
166 current_tax_fraction = tax_rate / 100.0
167
168 elif tax.charge_type == "On Previous Row Amount":
169 current_tax_fraction = (tax_rate / 100.0) * \
170 self.doc.get("taxes")[cint(tax.row_id) - 1].tax_fraction_for_current_item
171
172 elif tax.charge_type == "On Previous Row Total":
173 current_tax_fraction = (tax_rate / 100.0) * \
174 self.doc.get("taxes")[cint(tax.row_id) - 1].grand_total_fraction_for_current_item
175
176 return current_tax_fraction
177
178 def _get_tax_rate(self, tax, item_tax_map):
179 if item_tax_map.has_key(tax.account_head):
180 return flt(item_tax_map.get(tax.account_head), self.doc.precision("rate", tax))
181 else:
182 return tax.rate
183
184 def calculate_net_total(self):
185 self.doc.base_net_total = self.doc.net_total = 0.0
186
187 for item in self.doc.get("items"):
188 self.doc.base_net_total += item.base_amount
189 self.doc.net_total += item.amount
190
Nabin Haitbd00e812015-02-17 12:50:51 +0530191 self.doc.round_floats_in(self.doc, ["base_net_total", "net_total"])
Nabin Hait3237c752015-02-17 11:11:11 +0530192
193 def calculate_taxes(self):
194 # maintain actual tax rate based on idx
195 actual_tax_dict = dict([[tax.idx, flt(tax.rate, self.doc.precision("tax_amount", tax))]
196 for tax in self.doc.get("taxes") if tax.charge_type == "Actual"])
197
198 for n, item in enumerate(self.doc.get("items")):
199 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
200
201 for i, tax in enumerate(self.doc.get("taxes")):
202 # tax_amount represents the amount of tax for the current step
203 current_tax_amount = self.get_current_tax_amount(item, tax, item_tax_map)
204
205 # Adjust divisional loss to the last item
206 if tax.charge_type == "Actual":
207 actual_tax_dict[tax.idx] -= current_tax_amount
208 if n == len(self.doc.get("items")) - 1:
209 current_tax_amount += actual_tax_dict[tax.idx]
210
211 # store tax_amount for current item as it will be used for
212 # charge type = 'On Previous Row Amount'
213 tax.tax_amount_for_current_item = current_tax_amount
214
215 # accumulate tax amount into tax.tax_amount
216 if not self.discount_amount_applied:
217 tax.tax_amount += current_tax_amount
218
219 tax.tax_amount_after_discount_amount += current_tax_amount
220
221 if getattr(tax, "category", None):
222 # if just for valuation, do not add the tax amount in total
223 # hence, setting it as 0 for further steps
224 current_tax_amount = 0.0 if (tax.category == "Valuation") \
225 else current_tax_amount
226
227 current_tax_amount *= -1.0 if (tax.add_deduct_tax == "Deduct") else 1.0
228
229 # Calculate tax.total viz. grand total till that step
230 # note: grand_total_for_current_item contains the contribution of
231 # item's amount, previously applied tax and the current tax on that item
232 if i==0:
233 tax.grand_total_for_current_item = flt(item.base_amount + current_tax_amount,
234 self.doc.precision("total", tax))
235 else:
236 tax.grand_total_for_current_item = \
237 flt(self.doc.get("taxes")[i-1].grand_total_for_current_item +
238 current_tax_amount, self.doc.precision("total", tax))
239
240 # in tax.total, accumulate grand total of each item
241 tax.total += tax.grand_total_for_current_item
242
243 # set precision in the last item iteration
244 if n == len(self.doc.get("items")) - 1:
245 self.round_off_totals(tax)
246
247 # adjust Discount Amount loss in last tax iteration
248 if i == (len(self.doc.get("taxes")) - 1) and self.discount_amount_applied:
249 self.adjust_discount_amount_loss(tax)
250
251 def get_current_tax_amount(self, item, tax, item_tax_map):
252 tax_rate = self._get_tax_rate(tax, item_tax_map)
253 current_tax_amount = 0.0
254
255 if tax.charge_type == "Actual":
256 # distribute the tax amount proportionally to each item row
257 actual = flt(tax.rate, self.doc.precision("tax_amount", tax))
258 current_tax_amount = (self.doc.base_net_total
259 and ((item.base_amount / self.doc.base_net_total) * actual)
260 or 0)
261 elif tax.charge_type == "On Net Total":
262 current_tax_amount = (tax_rate / 100.0) * item.base_amount
263 elif tax.charge_type == "On Previous Row Amount":
264 current_tax_amount = (tax_rate / 100.0) * \
265 self.doc.get("taxes")[cint(tax.row_id) - 1].tax_amount_for_current_item
266 elif tax.charge_type == "On Previous Row Total":
267 current_tax_amount = (tax_rate / 100.0) * \
268 self.doc.get("taxes")[cint(tax.row_id) - 1].grand_total_for_current_item
269
270 current_tax_amount = flt(current_tax_amount, self.doc.precision("tax_amount", tax))
271
272 # store tax breakup for each item
273 key = item.item_code or item.item_name
274 if tax.item_wise_tax_detail.get(key):
275 item_wise_tax_amount = tax.item_wise_tax_detail[key][1] + current_tax_amount
276 tax.item_wise_tax_detail[key] = [tax_rate,item_wise_tax_amount]
277 else:
278 tax.item_wise_tax_detail[key] = [tax_rate,current_tax_amount]
279
280 return current_tax_amount
281
282 def round_off_totals(self, tax):
283 tax.total = flt(tax.total, self.doc.precision("total", tax))
284 tax.tax_amount = flt(tax.tax_amount, self.doc.precision("tax_amount", tax))
285 tax.tax_amount_after_discount_amount = flt(tax.tax_amount_after_discount_amount,
286 self.doc.precision("tax_amount", tax))
287
288 def adjust_discount_amount_loss(self, tax):
289 discount_amount_loss = self.doc.base_grand_total - flt(self.doc.base_discount_amount) - tax.total
290 tax.tax_amount_after_discount_amount = flt(tax.tax_amount_after_discount_amount +
291 discount_amount_loss, self.doc.precision("tax_amount", tax))
292 tax.total = flt(tax.total + discount_amount_loss, self.doc.precision("total", tax))
293
294 def calculate_totals(self):
295 self.doc.base_grand_total = flt(self.doc.get("taxes")[-1].total
296 if self.doc.get("taxes") else self.doc.base_net_total)
297
298 self.doc.base_total_taxes_and_charges = flt(self.doc.base_grand_total - self.doc.base_net_total,
299 self.doc.precision("base_total_taxes_and_charges"))
300
Nabin Haitbd00e812015-02-17 12:50:51 +0530301 if self.doc.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
Nabin Hait3237c752015-02-17 11:11:11 +0530302 self.doc.grand_total = flt(self.doc.base_grand_total / self.doc.conversion_rate) \
303 if (self.doc.base_total_taxes_and_charges or self.doc.discount_amount) else self.doc.net_total
304
305 self.doc.total_taxes_and_charges = flt(self.doc.grand_total - self.doc.net_total +
306 flt(self.doc.discount_amount), self.doc.precision("total_taxes_and_charges"))
307 else:
308 self.doc.base_taxes_and_charges_added, self.base_taxes_and_charges_deducted = 0.0, 0.0
309 for tax in self.doc.get("taxes"):
310 if tax.category in ["Valuation and Total", "Total"]:
311 if tax.add_deduct_tax == "Add":
312 self.doc.base_taxes_and_charges_added += flt(tax.tax_amount)
313 else:
314 self.doc.base_taxes_and_charges_deducted += flt(tax.tax_amount)
315
316 self.doc.round_floats_in(self.doc, ["base_taxes_and_charges_added", "base_taxes_and_charges_deducted"])
317
318 self.doc.grand_total = flt(self.doc.base_grand_total / self.doc.conversion_rate) \
319 if (self.doc.base_taxes_and_charges_added or self.doc.base_taxes_and_charges_deducted) else self.doc.net_total
320
321 self.doc.total_taxes_and_charges = flt(self.doc.grand_total - self.doc.net_total,
322 self.doc.precision("total_taxes_and_charges"))
323
324 self.doc.taxes_and_charges_added = flt(self.doc.base_taxes_and_charges_added / self.doc.conversion_rate,
325 self.doc.precision("taxes_and_charges_added"))
326 self.doc.taxes_and_charges_deducted = flt(self.doc.base_taxes_and_charges_deducted / self.doc.conversion_rate,
327 self.doc.precision("taxes_and_charges_deducted"))
328
329 self.doc.base_grand_total = flt(self.doc.base_grand_total, self.doc.precision("base_grand_total"))
330 self.doc.grand_total = flt(self.doc.grand_total, self.doc.precision("grand_total"))
331
332 if self.doc.meta.get_field("base_rounded_total"):
333 self.doc.base_rounded_total = rounded(self.doc.base_grand_total)
334 if self.doc.meta.get_field("rounded_total"):
335 self.doc.rounded_total = rounded(self.doc.grand_total)
336
337 def _cleanup(self):
338 for tax in self.doc.get("taxes"):
339 tax.item_wise_tax_detail = json.dumps(tax.item_wise_tax_detail, separators=(',', ':'))
340
341 def apply_discount_amount(self):
342 if self.doc.discount_amount:
343 self.doc.base_discount_amount = flt(self.doc.discount_amount * self.doc.conversion_rate,
344 self.doc.precision("base_discount_amount"))
345
346 grand_total_for_discount_amount = self.get_grand_total_for_discount_amount()
347
348 if grand_total_for_discount_amount:
349 # calculate item amount after Discount Amount
350 for item in self.doc.get("items"):
351 distributed_amount = flt(self.doc.base_discount_amount) * item.base_amount / grand_total_for_discount_amount
352 item.base_amount = flt(item.base_amount - distributed_amount, self.doc.precision("base_amount", item))
353
354 self.discount_amount_applied = True
355 self._calculate()
356 else:
357 self.doc.base_discount_amount = 0
358
359 def get_grand_total_for_discount_amount(self):
360 actual_taxes_dict = {}
361
362 for tax in self.doc.get("taxes"):
363 if tax.charge_type == "Actual":
364 actual_taxes_dict.setdefault(tax.idx, tax.tax_amount)
365 elif tax.row_id in actual_taxes_dict:
366 actual_tax_amount = flt(actual_taxes_dict.get(tax.row_id, 0)) * flt(tax.rate) / 100
367 actual_taxes_dict.setdefault(tax.idx, actual_tax_amount)
368
369 grand_total_for_discount_amount = flt(self.doc.base_grand_total - sum(actual_taxes_dict.values()),
370 self.doc.precision("base_grand_total"))
371 return grand_total_for_discount_amount
372
373
374 def calculate_total_advance(self, parenttype, advance_parentfield):
375 if self.docstatus < 2:
376 sum_of_allocated_amount = sum([flt(adv.allocated_amount, self.doc.precision("allocated_amount", adv))
377 for adv in self.doc.get("advances")])
378
379 self.doc.total_advance = flt(sum_of_allocated_amount, self.doc.precision("total_advance"))
380
381 if self.docstatus == 0:
382 self.calculate_outstanding_amount()
383
384 def calculate_outstanding_amount(self):
385 # NOTE:
386 # write_off_amount is only for POS Invoice
387 # total_advance is only for non POS Invoice
388
Nabin Haitbd00e812015-02-17 12:50:51 +0530389 if self.doc.doctype == "Sales Invoice":
390 self.doc.round_floats_in(self.doc, ["base_grand_total", "total_advance", "write_off_amount", "paid_amount"])
Nabin Hait3237c752015-02-17 11:11:11 +0530391 total_amount_to_pay = self.doc.base_grand_total - self.doc.write_off_amount
392 self.doc.outstanding_amount = flt(total_amount_to_pay - self.doc.total_advance - self.doc.paid_amount,
393 self.doc.precision("outstanding_amount"))
394 else:
Nabin Haitbd00e812015-02-17 12:50:51 +0530395 self.doc.round_floats_in(self.doc, ["total_advance", "write_off_amount"])
Nabin Hait3237c752015-02-17 11:11:11 +0530396 self.doc.total_amount_to_pay = flt(self.doc.base_grand_total - self.doc.write_off_amount,
397 self.doc.precision("total_amount_to_pay"))
398 self.doc.outstanding_amount = flt(self.doc.total_amount_to_pay - self.doc.total_advance,
399 self.doc.precision("outstanding_amount"))