blob: 0e35cb89e61ff040b04b6baf56389193d0edee35 [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Nabin Hait3237c752015-02-17 11:11:11 +05302# License: GNU General Public License v3. See license.txt
3
4from __future__ import unicode_literals
5import json
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +05306import frappe, erpnext
Nabin Hait3769d872015-12-18 13:12:02 +05307from frappe import _, scrub
Nabin Haitb962fc12017-07-17 18:02:31 +05308from frappe.utils import cint, flt, round_based_on_smallest_currency_fraction
Nabin Hait613d0812015-02-23 11:58:15 +05309from erpnext.controllers.accounts_controller import validate_conversion_rate, \
10 validate_taxes_and_charges, validate_inclusive_tax
Nabin Hait3237c752015-02-17 11:11:11 +053011
Nabin Haitfe81da22015-02-18 12:23:18 +053012class calculate_taxes_and_totals(object):
Nabin Hait3237c752015-02-17 11:11:11 +053013 def __init__(self, doc):
14 self.doc = doc
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"):
Nabin Hait3769d872015-12-18 13:12:02 +053022 self.set_discount_amount()
Nabin Hait3237c752015-02-17 11:11:11 +053023 self.apply_discount_amount()
24
Nabin Haitbd00e812015-02-17 12:50:51 +053025 if self.doc.doctype in ["Sales Invoice", "Purchase Invoice"]:
Nabin Hait3237c752015-02-17 11:11:11 +053026 self.calculate_total_advance()
Vishal Dhayaguded42242d2017-11-29 16:09:59 +053027
Nabin Hait852cb642017-07-05 12:58:19 +053028 if self.doc.meta.get_field("other_charges_calculation"):
29 self.set_item_wise_tax_breakup()
Nabin Hait3237c752015-02-17 11:11:11 +053030
31 def _calculate(self):
Nabin Haite7679702015-02-20 14:40:35 +053032 self.calculate_item_values()
33 self.initialize_taxes()
34 self.determine_exclusive_rate()
35 self.calculate_net_total()
36 self.calculate_taxes()
Nabin Haita1bf43b2015-03-17 10:50:47 +053037 self.manipulate_grand_total_for_inclusive_tax()
Nabin Haite7679702015-02-20 14:40:35 +053038 self.calculate_totals()
39 self._cleanup()
40
41 def validate_conversion_rate(self):
Nabin Hait3237c752015-02-17 11:11:11 +053042 # validate conversion rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053043 company_currency = erpnext.get_company_currency(self.doc.company)
Nabin Hait3237c752015-02-17 11:11:11 +053044 if not self.doc.currency or self.doc.currency == company_currency:
45 self.doc.currency = company_currency
46 self.doc.conversion_rate = 1.0
47 else:
48 validate_conversion_rate(self.doc.currency, self.doc.conversion_rate,
49 self.doc.meta.get_label("conversion_rate"), self.doc.company)
50
51 self.doc.conversion_rate = flt(self.doc.conversion_rate)
52
Nabin Hait3237c752015-02-17 11:11:11 +053053 def calculate_item_values(self):
54 if not self.discount_amount_applied:
55 for item in self.doc.get("items"):
56 self.doc.round_floats_in(item)
57
58 if item.discount_percentage == 100:
59 item.rate = 0.0
60 elif not item.rate:
Nabin Haite7679702015-02-20 14:40:35 +053061 item.rate = flt(item.price_list_rate *
62 (1.0 - (item.discount_percentage / 100.0)), item.precision("rate"))
Nabin Hait3237c752015-02-17 11:11:11 +053063
mbauskara52472c2016-03-05 15:10:25 +053064 if item.doctype in ['Quotation Item', 'Sales Order Item', 'Delivery Note Item', 'Sales Invoice Item']:
Shreya Shahbe690ef2017-11-14 17:22:41 +053065 item.rate_with_margin, item.base_rate_with_margin = self.calculate_margin(item)
mbauskar287fe812017-04-10 19:15:57 +053066
Makarand Bauskar0e4c5c92017-05-11 11:40:02 +053067 item.rate = flt(item.rate_with_margin * (1.0 - (item.discount_percentage / 100.0)), item.precision("rate"))\
68 if item.rate_with_margin > 0 else item.rate
mbauskara52472c2016-03-05 15:10:25 +053069
Nabin Haite7679702015-02-20 14:40:35 +053070 item.net_rate = item.rate
71 item.amount = flt(item.rate * item.qty, item.precision("amount"))
72 item.net_amount = item.amount
Nabin Hait3237c752015-02-17 11:11:11 +053073
Nabin Haite7679702015-02-20 14:40:35 +053074 self._set_in_company_currency(item, ["price_list_rate", "rate", "net_rate", "amount", "net_amount"])
Nabin Hait3237c752015-02-17 11:11:11 +053075
Nabin Haite7679702015-02-20 14:40:35 +053076 item.item_tax_amount = 0.0
77
78 def _set_in_company_currency(self, doc, fields):
Nabin Hait3237c752015-02-17 11:11:11 +053079 """set values in base currency"""
Nabin Haite7679702015-02-20 14:40:35 +053080 for f in fields:
81 val = flt(flt(doc.get(f), doc.precision(f)) * self.doc.conversion_rate, doc.precision("base_" + f))
82 doc.set("base_" + f, val)
Nabin Hait3237c752015-02-17 11:11:11 +053083
84 def initialize_taxes(self):
85 for tax in self.doc.get("taxes"):
Nabin Hait86cd4cc2015-02-28 19:11:51 +053086 if not self.discount_amount_applied:
87 validate_taxes_and_charges(tax)
88 validate_inclusive_tax(tax, self.doc)
Nabin Hait613d0812015-02-23 11:58:15 +053089
Nabin Hait3237c752015-02-17 11:11:11 +053090 tax.item_wise_tax_detail = {}
91 tax_fields = ["total", "tax_amount_after_discount_amount",
92 "tax_amount_for_current_item", "grand_total_for_current_item",
93 "tax_fraction_for_current_item", "grand_total_fraction_for_current_item"]
94
Nabin Haitde9c8a92015-02-23 01:06:00 +053095 if tax.charge_type != "Actual" and \
96 not (self.discount_amount_applied and self.doc.apply_discount_on=="Grand Total"):
97 tax_fields.append("tax_amount")
Nabin Hait3237c752015-02-17 11:11:11 +053098
99 for fieldname in tax_fields:
100 tax.set(fieldname, 0.0)
101
Nabin Hait3237c752015-02-17 11:11:11 +0530102 self.doc.round_floats_in(tax)
103
Nabin Hait3237c752015-02-17 11:11:11 +0530104 def determine_exclusive_rate(self):
Nabin Hait37b047d2015-02-23 16:01:33 +0530105 if not any((cint(tax.included_in_print_rate) for tax in self.doc.get("taxes"))):
106 return
Nabin Hait3237c752015-02-17 11:11:11 +0530107
108 for item in self.doc.get("items"):
109 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
110 cumulated_tax_fraction = 0
111 for i, tax in enumerate(self.doc.get("taxes")):
112 tax.tax_fraction_for_current_item = self.get_current_tax_fraction(tax, item_tax_map)
113
114 if i==0:
115 tax.grand_total_fraction_for_current_item = 1 + tax.tax_fraction_for_current_item
116 else:
117 tax.grand_total_fraction_for_current_item = \
118 self.doc.get("taxes")[i-1].grand_total_fraction_for_current_item \
119 + tax.tax_fraction_for_current_item
120
121 cumulated_tax_fraction += tax.tax_fraction_for_current_item
122
123 if cumulated_tax_fraction and not self.discount_amount_applied and item.qty:
Nabin Hait2e4de832017-09-19 14:53:16 +0530124 item.net_amount = flt(item.amount / (1 + cumulated_tax_fraction))
Nabin Haite7679702015-02-20 14:40:35 +0530125 item.net_rate = flt(item.net_amount / item.qty, item.precision("net_rate"))
Nabin Hait2e4de832017-09-19 14:53:16 +0530126 item.discount_percentage = flt(item.discount_percentage,
127 item.precision("discount_percentage"))
Nabin Hait3237c752015-02-17 11:11:11 +0530128
Nabin Haite7679702015-02-20 14:40:35 +0530129 self._set_in_company_currency(item, ["net_rate", "net_amount"])
130
Nabin Hait3237c752015-02-17 11:11:11 +0530131 def _load_item_tax_rate(self, item_tax_rate):
132 return json.loads(item_tax_rate) if item_tax_rate else {}
133
134 def get_current_tax_fraction(self, tax, item_tax_map):
135 """
136 Get tax fraction for calculating tax exclusive amount
137 from tax inclusive amount
138 """
139 current_tax_fraction = 0
140
141 if cint(tax.included_in_print_rate):
142 tax_rate = self._get_tax_rate(tax, item_tax_map)
143
144 if tax.charge_type == "On Net Total":
145 current_tax_fraction = tax_rate / 100.0
146
147 elif tax.charge_type == "On Previous Row Amount":
148 current_tax_fraction = (tax_rate / 100.0) * \
149 self.doc.get("taxes")[cint(tax.row_id) - 1].tax_fraction_for_current_item
150
151 elif tax.charge_type == "On Previous Row Total":
152 current_tax_fraction = (tax_rate / 100.0) * \
153 self.doc.get("taxes")[cint(tax.row_id) - 1].grand_total_fraction_for_current_item
154
Nabin Haita6ee8292015-05-15 12:02:01 +0530155 if getattr(tax, "add_deduct_tax", None):
156 current_tax_fraction *= -1.0 if (tax.add_deduct_tax == "Deduct") else 1.0
Nabin Hait3237c752015-02-17 11:11:11 +0530157 return current_tax_fraction
158
159 def _get_tax_rate(self, tax, item_tax_map):
160 if item_tax_map.has_key(tax.account_head):
161 return flt(item_tax_map.get(tax.account_head), self.doc.precision("rate", tax))
162 else:
163 return tax.rate
164
165 def calculate_net_total(self):
Vishal Dhayaguded3770182017-12-14 18:06:02 +0530166 self.doc.total = self.doc.base_total = self.doc.net_total = self.doc.base_net_total = 0.0
Nabin Hait3237c752015-02-17 11:11:11 +0530167 for item in self.doc.get("items"):
Nabin Haitf0bc9b62015-02-23 01:40:01 +0530168 self.doc.total += item.amount
169 self.doc.base_total += item.base_amount
Nabin Haite7679702015-02-20 14:40:35 +0530170 self.doc.net_total += item.net_amount
171 self.doc.base_net_total += item.base_net_amount
Nabin Hait3237c752015-02-17 11:11:11 +0530172
Nabin Haitf0bc9b62015-02-23 01:40:01 +0530173 self.doc.round_floats_in(self.doc, ["total", "base_total", "net_total", "base_net_total"])
Nabin Hait3237c752015-02-17 11:11:11 +0530174
175 def calculate_taxes(self):
Nabin Hait2e4de832017-09-19 14:53:16 +0530176 self.doc.rounding_adjustment = 0
Nabin Hait3237c752015-02-17 11:11:11 +0530177 # maintain actual tax rate based on idx
Nabin Haite7679702015-02-20 14:40:35 +0530178 actual_tax_dict = dict([[tax.idx, flt(tax.tax_amount, tax.precision("tax_amount"))]
Nabin Hait3237c752015-02-17 11:11:11 +0530179 for tax in self.doc.get("taxes") if tax.charge_type == "Actual"])
180
181 for n, item in enumerate(self.doc.get("items")):
182 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
Nabin Hait3237c752015-02-17 11:11:11 +0530183 for i, tax in enumerate(self.doc.get("taxes")):
184 # tax_amount represents the amount of tax for the current step
185 current_tax_amount = self.get_current_tax_amount(item, tax, item_tax_map)
186
187 # Adjust divisional loss to the last item
188 if tax.charge_type == "Actual":
189 actual_tax_dict[tax.idx] -= current_tax_amount
190 if n == len(self.doc.get("items")) - 1:
191 current_tax_amount += actual_tax_dict[tax.idx]
192
Nabin Hait2b019ed2015-02-22 23:03:07 +0530193 # accumulate tax amount into tax.tax_amount
Nabin Haitde9c8a92015-02-23 01:06:00 +0530194 if tax.charge_type != "Actual" and \
195 not (self.discount_amount_applied and self.doc.apply_discount_on=="Grand Total"):
196 tax.tax_amount += current_tax_amount
Nabin Hait2b019ed2015-02-22 23:03:07 +0530197
Nabin Hait3237c752015-02-17 11:11:11 +0530198 # store tax_amount for current item as it will be used for
199 # charge type = 'On Previous Row Amount'
200 tax.tax_amount_for_current_item = current_tax_amount
201
Nabin Hait2b019ed2015-02-22 23:03:07 +0530202 # set tax after discount
Nabin Hait3237c752015-02-17 11:11:11 +0530203 tax.tax_amount_after_discount_amount += current_tax_amount
204
Nabin Haitcd951342017-07-31 18:07:45 +0530205 current_tax_amount = self.get_tax_amount_if_for_valuation_or_deduction(current_tax_amount, tax)
Nabin Hait3237c752015-02-17 11:11:11 +0530206
Nabin Hait3237c752015-02-17 11:11:11 +0530207 # note: grand_total_for_current_item contains the contribution of
208 # item's amount, previously applied tax and the current tax on that item
209 if i==0:
Nabin Haitcd951342017-07-31 18:07:45 +0530210 tax.grand_total_for_current_item = flt(item.net_amount + current_tax_amount)
Nabin Hait3237c752015-02-17 11:11:11 +0530211 else:
212 tax.grand_total_for_current_item = \
Nabin Haitcd951342017-07-31 18:07:45 +0530213 flt(self.doc.get("taxes")[i-1].grand_total_for_current_item + current_tax_amount)
Nabin Hait3237c752015-02-17 11:11:11 +0530214
215 # set precision in the last item iteration
216 if n == len(self.doc.get("items")) - 1:
217 self.round_off_totals(tax)
Nabin Haitcd951342017-07-31 18:07:45 +0530218 self.set_cumulative_total(i, tax)
219
220 self._set_in_company_currency(tax,
221 ["total", "tax_amount", "tax_amount_after_discount_amount"])
Anand Doshiec5ec602015-03-05 19:31:23 +0530222
Nabin Hait3237c752015-02-17 11:11:11 +0530223 # adjust Discount Amount loss in last tax iteration
Nabin Haitde9c8a92015-02-23 01:06:00 +0530224 if i == (len(self.doc.get("taxes")) - 1) and self.discount_amount_applied \
Nabin Haitdb53a782015-07-31 16:53:13 +0530225 and self.doc.discount_amount and self.doc.apply_discount_on == "Grand Total":
Nabin Hait2e4de832017-09-19 14:53:16 +0530226 self.doc.rounding_adjustment = flt(self.doc.grand_total
227 - flt(self.doc.discount_amount) - tax.total,
228 self.doc.precision("rounding_adjustment"))
Anand Doshiec5ec602015-03-05 19:31:23 +0530229
Nabin Haitcd951342017-07-31 18:07:45 +0530230 def get_tax_amount_if_for_valuation_or_deduction(self, tax_amount, tax):
231 # if just for valuation, do not add the tax amount in total
232 # if tax/charges is for deduction, multiply by -1
233 if getattr(tax, "category", None):
234 tax_amount = 0.0 if (tax.category == "Valuation") else tax_amount
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530235 if self.doc.doctype in ["Purchase Order", "Purchase Invoice", "Purchase Receipt", "Supplier Quotation"]:
236 tax_amount *= -1.0 if (tax.add_deduct_tax == "Deduct") else 1.0
Nabin Haitcd951342017-07-31 18:07:45 +0530237 return tax_amount
Anand Doshiec5ec602015-03-05 19:31:23 +0530238
Nabin Haitcd951342017-07-31 18:07:45 +0530239 def set_cumulative_total(self, row_idx, tax):
240 tax_amount = tax.tax_amount_after_discount_amount
241 tax_amount = self.get_tax_amount_if_for_valuation_or_deduction(tax_amount, tax)
242
243 if row_idx == 0:
244 tax.total = flt(self.doc.net_total + tax_amount, tax.precision("total"))
245 else:
246 tax.total = flt(self.doc.get("taxes")[row_idx-1].total + tax_amount, tax.precision("total"))
Nabin Hait3237c752015-02-17 11:11:11 +0530247
248 def get_current_tax_amount(self, item, tax, item_tax_map):
249 tax_rate = self._get_tax_rate(tax, item_tax_map)
250 current_tax_amount = 0.0
251
252 if tax.charge_type == "Actual":
253 # distribute the tax amount proportionally to each item row
Nabin Haite7679702015-02-20 14:40:35 +0530254 actual = flt(tax.tax_amount, tax.precision("tax_amount"))
255 current_tax_amount = item.net_amount*actual / self.doc.net_total if self.doc.net_total else 0.0
256
Nabin Hait3237c752015-02-17 11:11:11 +0530257 elif tax.charge_type == "On Net Total":
Nabin Haite7679702015-02-20 14:40:35 +0530258 current_tax_amount = (tax_rate / 100.0) * item.net_amount
Nabin Hait3237c752015-02-17 11:11:11 +0530259 elif tax.charge_type == "On Previous Row Amount":
260 current_tax_amount = (tax_rate / 100.0) * \
261 self.doc.get("taxes")[cint(tax.row_id) - 1].tax_amount_for_current_item
262 elif tax.charge_type == "On Previous Row Total":
263 current_tax_amount = (tax_rate / 100.0) * \
264 self.doc.get("taxes")[cint(tax.row_id) - 1].grand_total_for_current_item
265
Nabin Haite7679702015-02-20 14:40:35 +0530266 self.set_item_wise_tax(item, tax, tax_rate, current_tax_amount)
Nabin Hait3237c752015-02-17 11:11:11 +0530267
268 return current_tax_amount
269
Nabin Haite7679702015-02-20 14:40:35 +0530270 def set_item_wise_tax(self, item, tax, tax_rate, current_tax_amount):
271 # store tax breakup for each item
272 key = item.item_code or item.item_name
273 item_wise_tax_amount = current_tax_amount*self.doc.conversion_rate
274 if tax.item_wise_tax_detail.get(key):
275 item_wise_tax_amount += tax.item_wise_tax_detail[key][1]
276
Nabin Haitcaab5822017-08-24 16:22:28 +0530277 tax.item_wise_tax_detail[key] = [tax_rate,flt(item_wise_tax_amount)]
Nabin Haite7679702015-02-20 14:40:35 +0530278
Nabin Hait3237c752015-02-17 11:11:11 +0530279 def round_off_totals(self, tax):
Nabin Haite7679702015-02-20 14:40:35 +0530280 tax.tax_amount = flt(tax.tax_amount, tax.precision("tax_amount"))
Vishal Dhayaguded42242d2017-11-29 16:09:59 +0530281 tax.tax_amount_after_discount_amount = flt(tax.tax_amount_after_discount_amount,
Nabin Haitcd951342017-07-31 18:07:45 +0530282 tax.precision("tax_amount"))
Nabin Haitce245122015-02-22 20:14:49 +0530283
Nabin Haita1bf43b2015-03-17 10:50:47 +0530284 def manipulate_grand_total_for_inclusive_tax(self):
285 # if fully inclusive taxes and diff
Nabin Hait2e4de832017-09-19 14:53:16 +0530286 if self.doc.get("taxes") and any([cint(t.included_in_print_rate) for t in self.doc.get("taxes")]):
Nabin Haita1bf43b2015-03-17 10:50:47 +0530287 last_tax = self.doc.get("taxes")[-1]
Nabin Hait2e4de832017-09-19 14:53:16 +0530288 non_inclusive_tax_amount = sum([flt(d.tax_amount_after_discount_amount)
289 for d in self.doc.get("taxes") if not d.included_in_print_rate])
290 diff = self.doc.total + non_inclusive_tax_amount \
291 - flt(last_tax.total, last_tax.precision("total"))
292 if diff and abs(diff) <= (5.0 / 10**last_tax.precision("tax_amount")):
293 self.doc.rounding_adjustment = flt(flt(self.doc.rounding_adjustment) +
294 flt(diff), self.doc.precision("rounding_adjustment"))
Nabin Hait3237c752015-02-17 11:11:11 +0530295
296 def calculate_totals(self):
Nabin Hait2e4de832017-09-19 14:53:16 +0530297 self.doc.grand_total = flt(self.doc.get("taxes")[-1].total) + flt(self.doc.rounding_adjustment) \
298 if self.doc.get("taxes") else flt(self.doc.net_total)
Nabin Hait3237c752015-02-17 11:11:11 +0530299
Nabin Hait2e4de832017-09-19 14:53:16 +0530300 self.doc.total_taxes_and_charges = flt(self.doc.grand_total - self.doc.net_total
301 - flt(self.doc.rounding_adjustment), self.doc.precision("total_taxes_and_charges"))
Anand Doshiec5ec602015-03-05 19:31:23 +0530302
Nabin Hait2e4de832017-09-19 14:53:16 +0530303 self._set_in_company_currency(self.doc, ["total_taxes_and_charges", "rounding_adjustment"])
Anand Doshiec5ec602015-03-05 19:31:23 +0530304
Nabin Haitbd00e812015-02-17 12:50:51 +0530305 if self.doc.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
Nabin Haite7679702015-02-20 14:40:35 +0530306 self.doc.base_grand_total = flt(self.doc.grand_total * self.doc.conversion_rate) \
307 if self.doc.total_taxes_and_charges else self.doc.base_net_total
Nabin Hait3237c752015-02-17 11:11:11 +0530308 else:
Anand Doshiec5ec602015-03-05 19:31:23 +0530309 self.doc.taxes_and_charges_added = self.doc.taxes_and_charges_deducted = 0.0
Nabin Hait3237c752015-02-17 11:11:11 +0530310 for tax in self.doc.get("taxes"):
311 if tax.category in ["Valuation and Total", "Total"]:
312 if tax.add_deduct_tax == "Add":
Nabin Haitdb53a782015-07-31 16:53:13 +0530313 self.doc.taxes_and_charges_added += flt(tax.tax_amount_after_discount_amount)
Nabin Hait3237c752015-02-17 11:11:11 +0530314 else:
Nabin Haitdb53a782015-07-31 16:53:13 +0530315 self.doc.taxes_and_charges_deducted += flt(tax.tax_amount_after_discount_amount)
Nabin Hait3237c752015-02-17 11:11:11 +0530316
Nabin Haite7679702015-02-20 14:40:35 +0530317 self.doc.round_floats_in(self.doc, ["taxes_and_charges_added", "taxes_and_charges_deducted"])
Nabin Hait3237c752015-02-17 11:11:11 +0530318
Nabin Haite7679702015-02-20 14:40:35 +0530319 self.doc.base_grand_total = flt(self.doc.grand_total * self.doc.conversion_rate) \
320 if (self.doc.taxes_and_charges_added or self.doc.taxes_and_charges_deducted) \
321 else self.doc.base_net_total
Nabin Hait3237c752015-02-17 11:11:11 +0530322
Nabin Hait2e4de832017-09-19 14:53:16 +0530323 self._set_in_company_currency(self.doc,
324 ["taxes_and_charges_added", "taxes_and_charges_deducted"])
Nabin Hait3237c752015-02-17 11:11:11 +0530325
Nabin Haite7679702015-02-20 14:40:35 +0530326 self.doc.round_floats_in(self.doc, ["grand_total", "base_grand_total"])
Nabin Hait3237c752015-02-17 11:11:11 +0530327
Nabin Hait2e4de832017-09-19 14:53:16 +0530328 self.set_rounded_total()
329
330 def set_rounded_total(self):
Nabin Hait3237c752015-02-17 11:11:11 +0530331 if self.doc.meta.get_field("rounded_total"):
Nabin Hait877e1bb2017-11-17 12:27:43 +0530332 if self.doc.is_rounded_total_disabled():
333 self.doc.rounded_total = self.doc.base_rounded_total = 0
334 return
335
Anand Doshi15f7b1e2016-04-04 15:03:28 +0530336 self.doc.rounded_total = round_based_on_smallest_currency_fraction(self.doc.grand_total,
Nabin Haitfb0b24a2016-01-20 14:46:26 +0530337 self.doc.currency, self.doc.precision("rounded_total"))
Nabin Hait2e4de832017-09-19 14:53:16 +0530338
Nabin Hait877e1bb2017-11-17 12:27:43 +0530339 #if print_in_rate is set, we would have already calculated rounding adjustment
340 self.doc.rounding_adjustment += flt(self.doc.rounded_total - self.doc.grand_total,
341 self.doc.precision("rounding_adjustment"))
342
Nabin Hait02ac9012017-11-22 16:12:20 +0530343 self._set_in_company_currency(self.doc, ["rounding_adjustment", "rounded_total"])
Nabin Hait877e1bb2017-11-17 12:27:43 +0530344
Nabin Hait3237c752015-02-17 11:11:11 +0530345 def _cleanup(self):
346 for tax in self.doc.get("taxes"):
347 tax.item_wise_tax_detail = json.dumps(tax.item_wise_tax_detail, separators=(',', ':'))
Anand Doshi15f7b1e2016-04-04 15:03:28 +0530348
Nabin Hait3769d872015-12-18 13:12:02 +0530349 def set_discount_amount(self):
Nabin Haite0405102016-10-13 12:14:32 +0530350 if self.doc.additional_discount_percentage:
Anand Doshi15f7b1e2016-04-04 15:03:28 +0530351 self.doc.discount_amount = flt(flt(self.doc.get(scrub(self.doc.apply_discount_on)))
Nabin Hait3769d872015-12-18 13:12:02 +0530352 * self.doc.additional_discount_percentage / 100, self.doc.precision("discount_amount"))
Nabin Hait3237c752015-02-17 11:11:11 +0530353
354 def apply_discount_amount(self):
355 if self.doc.discount_amount:
Nabin Hait37b047d2015-02-23 16:01:33 +0530356 if not self.doc.apply_discount_on:
357 frappe.throw(_("Please select Apply Discount On"))
358
Nabin Hait3237c752015-02-17 11:11:11 +0530359 self.doc.base_discount_amount = flt(self.doc.discount_amount * self.doc.conversion_rate,
360 self.doc.precision("base_discount_amount"))
361
Nabin Haite7679702015-02-20 14:40:35 +0530362 total_for_discount_amount = self.get_total_for_discount_amount()
Nabin Hait25bd84d2015-03-04 15:06:56 +0530363 taxes = self.doc.get("taxes")
364 net_total = 0
Nabin Hait3237c752015-02-17 11:11:11 +0530365
Nabin Haite7679702015-02-20 14:40:35 +0530366 if total_for_discount_amount:
Nabin Hait3237c752015-02-17 11:11:11 +0530367 # calculate item amount after Discount Amount
Nabin Hait25bd84d2015-03-04 15:06:56 +0530368 for i, item in enumerate(self.doc.get("items")):
369 distributed_amount = flt(self.doc.discount_amount) * \
370 item.net_amount / total_for_discount_amount
Anand Doshiec5ec602015-03-05 19:31:23 +0530371
Nabin Haite7679702015-02-20 14:40:35 +0530372 item.net_amount = flt(item.net_amount - distributed_amount, item.precision("net_amount"))
Nabin Hait25bd84d2015-03-04 15:06:56 +0530373 net_total += item.net_amount
Anand Doshiec5ec602015-03-05 19:31:23 +0530374
Nabin Hait25bd84d2015-03-04 15:06:56 +0530375 # discount amount rounding loss adjustment if no taxes
376 if (not taxes or self.doc.apply_discount_on == "Net Total") \
377 and i == len(self.doc.get("items")) - 1:
Rushabh Mehtac6bd7ad2016-12-21 17:30:29 +0530378 discount_amount_loss = flt(self.doc.net_total - net_total - self.doc.discount_amount,
Nabin Hait25bd84d2015-03-04 15:06:56 +0530379 self.doc.precision("net_total"))
Rushabh Mehtac6bd7ad2016-12-21 17:30:29 +0530380
Anand Doshiec5ec602015-03-05 19:31:23 +0530381 item.net_amount = flt(item.net_amount + discount_amount_loss,
Nabin Hait25bd84d2015-03-04 15:06:56 +0530382 item.precision("net_amount"))
Anand Doshiec5ec602015-03-05 19:31:23 +0530383
Nabin Hait51e980d2015-10-10 18:10:05 +0530384 item.net_rate = flt(item.net_amount / item.qty, item.precision("net_rate")) if item.qty else 0
Anand Doshiec5ec602015-03-05 19:31:23 +0530385
Nabin Haite7679702015-02-20 14:40:35 +0530386 self._set_in_company_currency(item, ["net_rate", "net_amount"])
Nabin Hait3237c752015-02-17 11:11:11 +0530387
388 self.discount_amount_applied = True
389 self._calculate()
390 else:
391 self.doc.base_discount_amount = 0
392
Nabin Haite7679702015-02-20 14:40:35 +0530393 def get_total_for_discount_amount(self):
Nabin Haitde9c8a92015-02-23 01:06:00 +0530394 if self.doc.apply_discount_on == "Net Total":
395 return self.doc.net_total
Nabin Haite7679702015-02-20 14:40:35 +0530396 else:
397 actual_taxes_dict = {}
Nabin Hait3237c752015-02-17 11:11:11 +0530398
Nabin Haite7679702015-02-20 14:40:35 +0530399 for tax in self.doc.get("taxes"):
400 if tax.charge_type == "Actual":
Nabin Haitaf9bdfe2017-12-12 18:50:05 +0530401 tax_amount = self.get_tax_amount_if_for_valuation_or_deduction(tax.tax_amount, tax)
402 actual_taxes_dict.setdefault(tax.idx, tax_amount)
Nabin Haite7679702015-02-20 14:40:35 +0530403 elif tax.row_id in actual_taxes_dict:
404 actual_tax_amount = flt(actual_taxes_dict.get(tax.row_id, 0)) * flt(tax.rate) / 100
405 actual_taxes_dict.setdefault(tax.idx, actual_tax_amount)
Nabin Hait3237c752015-02-17 11:11:11 +0530406
Nabin Hait877e1bb2017-11-17 12:27:43 +0530407 return flt(self.doc.grand_total - sum(actual_taxes_dict.values()),
408 self.doc.precision("grand_total"))
Nabin Hait3237c752015-02-17 11:11:11 +0530409
410
Nabin Hait7b19b9e2015-02-24 09:42:24 +0530411 def calculate_total_advance(self):
412 if self.doc.docstatus < 2:
Nabin Haite7679702015-02-20 14:40:35 +0530413 total_allocated_amount = sum([flt(adv.allocated_amount, adv.precision("allocated_amount"))
Nabin Hait3237c752015-02-17 11:11:11 +0530414 for adv in self.doc.get("advances")])
415
Nabin Haite7679702015-02-20 14:40:35 +0530416 self.doc.total_advance = flt(total_allocated_amount, self.doc.precision("total_advance"))
Anand Doshi15f7b1e2016-04-04 15:03:28 +0530417
Nabin Hait289ffb72016-02-08 11:06:55 +0530418 if self.doc.party_account_currency == self.doc.currency:
Vishal Dhayaguded42242d2017-11-29 16:09:59 +0530419 invoice_total = flt(self.doc.grand_total - flt(self.doc.write_off_amount),
Nabin Hait289ffb72016-02-08 11:06:55 +0530420 self.doc.precision("grand_total"))
Nabin Hait8d8cba72017-04-03 17:26:22 +0530421 else:
Vishal Dhayaguded42242d2017-11-29 16:09:59 +0530422 base_write_off_amount = flt(flt(self.doc.write_off_amount) * self.doc.conversion_rate,
Nabin Hait8d8cba72017-04-03 17:26:22 +0530423 self.doc.precision("base_write_off_amount"))
Vishal Dhayaguded42242d2017-11-29 16:09:59 +0530424 invoice_total = flt(self.doc.grand_total * self.doc.conversion_rate,
Nabin Hait8d8cba72017-04-03 17:26:22 +0530425 self.doc.precision("grand_total")) - base_write_off_amount
Vishal Dhayaguded42242d2017-11-29 16:09:59 +0530426
Nabin Haitadc09232016-02-09 10:31:11 +0530427 if invoice_total > 0 and self.doc.total_advance > invoice_total:
Nabin Hait289ffb72016-02-08 11:06:55 +0530428 frappe.throw(_("Advance amount cannot be greater than {0} {1}")
429 .format(self.doc.party_account_currency, invoice_total))
Nabin Hait3237c752015-02-17 11:11:11 +0530430
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530431 if self.doc.docstatus == 0:
Nabin Hait3237c752015-02-17 11:11:11 +0530432 self.calculate_outstanding_amount()
433
434 def calculate_outstanding_amount(self):
435 # NOTE:
436 # write_off_amount is only for POS Invoice
437 # total_advance is only for non POS Invoice
Rohit Waghchaureefb5bf22016-08-25 02:09:53 +0530438 if self.doc.doctype == "Sales Invoice":
439 self.calculate_paid_amount()
440
441 if self.doc.is_return: return
Anand Doshi15f7b1e2016-04-04 15:03:28 +0530442
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530443 self.doc.round_floats_in(self.doc, ["grand_total", "total_advance", "write_off_amount"])
Anand Doshi15f7b1e2016-04-04 15:03:28 +0530444 self._set_in_company_currency(self.doc, ['write_off_amount'])
445
Nabin Hait877e1bb2017-11-17 12:27:43 +0530446 if self.doc.doctype in ["Sales Invoice", "Purchase Invoice"]:
447 grand_total = self.doc.rounded_total or self.doc.grand_total
448 if self.doc.party_account_currency == self.doc.currency:
449 total_amount_to_pay = flt(grand_total - self.doc.total_advance
450 - flt(self.doc.write_off_amount), self.doc.precision("grand_total"))
451 else:
452 total_amount_to_pay = flt(flt(grand_total *
453 self.doc.conversion_rate, self.doc.precision("grand_total")) - self.doc.total_advance
454 - flt(self.doc.base_write_off_amount), self.doc.precision("grand_total"))
Anand Doshi15f7b1e2016-04-04 15:03:28 +0530455
Nabin Hait4ffd7f32015-08-27 12:28:36 +0530456 self.doc.round_floats_in(self.doc, ["paid_amount"])
Nabin Hait877e1bb2017-11-17 12:27:43 +0530457 change_amount = 0
458
459 if self.doc.doctype == "Sales Invoice":
460 self.calculate_write_off_amount()
461 self.calculate_change_amount()
462 change_amount = self.doc.change_amount \
463 if self.doc.party_account_currency == self.doc.currency else self.doc.base_change_amount
464
Nabin Haitac3b2aa2017-05-30 15:35:01 +0530465 paid_amount = self.doc.paid_amount \
466 if self.doc.party_account_currency == self.doc.currency else self.doc.base_paid_amount
Rohit Waghchaure6087fe12016-04-09 14:31:09 +0530467
Rohit Waghchaure609e2b42016-08-31 02:04:37 +0530468
Nabin Hait877e1bb2017-11-17 12:27:43 +0530469 self.doc.outstanding_amount = flt(total_amount_to_pay - flt(paid_amount) + flt(change_amount),
470 self.doc.precision("outstanding_amount"))
Rushabh Mehtac6bd7ad2016-12-21 17:30:29 +0530471
Rohit Waghchaure6087fe12016-04-09 14:31:09 +0530472 def calculate_paid_amount(self):
473 paid_amount = base_paid_amount = 0.0
Rohit Waghchauref58cad62017-01-17 12:11:57 +0530474
475 if self.doc.is_pos:
476 for payment in self.doc.get('payments'):
Ayush Shuklae9cf1ab2017-05-25 14:14:55 +0530477 payment.amount = flt(payment.amount)
478 payment.base_amount = payment.amount * flt(self.doc.conversion_rate)
Rohit Waghchauref58cad62017-01-17 12:11:57 +0530479 paid_amount += payment.amount
480 base_paid_amount += payment.base_amount
rohitwaghchaure73456ac2017-05-16 11:29:57 +0530481 elif not self.doc.is_return:
482 self.doc.set('payments', [])
Rohit Waghchaure6087fe12016-04-09 14:31:09 +0530483
484 self.doc.paid_amount = flt(paid_amount, self.doc.precision("paid_amount"))
485 self.doc.base_paid_amount = flt(base_paid_amount, self.doc.precision("base_paid_amount"))
486
Nabin Hait3bb1a422016-08-02 16:41:10 +0530487 def calculate_change_amount(self):
488 self.doc.change_amount = 0.0
Rohit Waghchaure609e2b42016-08-31 02:04:37 +0530489 self.doc.base_change_amount = 0.0
Nabin Hait877e1bb2017-11-17 12:27:43 +0530490
491 if self.doc.doctype == "Sales Invoice" \
492 and self.doc.paid_amount > self.doc.grand_total and not self.doc.is_return \
Nabin Haitac3b2aa2017-05-30 15:35:01 +0530493 and any([d.type == "Cash" for d in self.doc.payments]):
Rohit Waghchauree8d22bb2018-02-05 18:13:29 +0530494 grand_total = self.doc.rounded_total or self.doc.grand_total
495 base_grand_total = self.doc.base_rounded_total or self.doc.base_grand_total
Nabin Haitac3b2aa2017-05-30 15:35:01 +0530496
Rohit Waghchauree8d22bb2018-02-05 18:13:29 +0530497 self.doc.change_amount = flt(self.doc.paid_amount - grand_total +
Nabin Hait3bb1a422016-08-02 16:41:10 +0530498 self.doc.write_off_amount, self.doc.precision("change_amount"))
Rohit Waghchaure6087fe12016-04-09 14:31:09 +0530499
Rohit Waghchauree8d22bb2018-02-05 18:13:29 +0530500 self.doc.base_change_amount = flt(self.doc.base_paid_amount - base_grand_total +
Rohit Waghchaure609e2b42016-08-31 02:04:37 +0530501 self.doc.base_write_off_amount, self.doc.precision("base_change_amount"))
mbauskar36b51892016-01-18 16:31:10 +0530502
Rohit Waghchaure7127a8f2016-08-04 14:56:15 +0530503 def calculate_write_off_amount(self):
Rohit Waghchaurebaef2622016-08-05 15:41:36 +0530504 if flt(self.doc.change_amount) > 0:
Nabin Hait877e1bb2017-11-17 12:27:43 +0530505 self.doc.write_off_amount = flt(self.doc.grand_total - self.doc.paid_amount
506 + self.doc.change_amount, self.doc.precision("write_off_amount"))
Rohit Waghchaurebaef2622016-08-05 15:41:36 +0530507 self.doc.base_write_off_amount = flt(self.doc.write_off_amount * self.doc.conversion_rate,
508 self.doc.precision("base_write_off_amount"))
Rohit Waghchaure7127a8f2016-08-04 14:56:15 +0530509
mbauskar36b51892016-01-18 16:31:10 +0530510 def calculate_margin(self, item):
Makarand Bauskar0e4c5c92017-05-11 11:40:02 +0530511 rate_with_margin = 0.0
Shreya Shahbe690ef2017-11-14 17:22:41 +0530512 base_rate_with_margin = 0.0
mbauskar36b51892016-01-18 16:31:10 +0530513 if item.price_list_rate:
Rushabh Mehtac6bd7ad2016-12-21 17:30:29 +0530514 if item.pricing_rule and not self.doc.ignore_pricing_rule:
mbauskar36b51892016-01-18 16:31:10 +0530515 pricing_rule = frappe.get_doc('Pricing Rule', item.pricing_rule)
mbauskara52472c2016-03-05 15:10:25 +0530516 item.margin_type = pricing_rule.margin_type
517 item.margin_rate_or_amount = pricing_rule.margin_rate_or_amount
mbauskar36b51892016-01-18 16:31:10 +0530518
mbauskara52472c2016-03-05 15:10:25 +0530519 if item.margin_type and item.margin_rate_or_amount:
520 margin_value = item.margin_rate_or_amount if item.margin_type == 'Amount' else flt(item.price_list_rate) * flt(item.margin_rate_or_amount) / 100
Makarand Bauskar0e4c5c92017-05-11 11:40:02 +0530521 rate_with_margin = flt(item.price_list_rate) + flt(margin_value)
Shreya Shahbe690ef2017-11-14 17:22:41 +0530522 base_rate_with_margin = flt(rate_with_margin) * flt(self.doc.conversion_rate)
mbauskar36b51892016-01-18 16:31:10 +0530523
Shreya Shahbe690ef2017-11-14 17:22:41 +0530524 return rate_with_margin, base_rate_with_margin
Nabin Hait852cb642017-07-05 12:58:19 +0530525
526 def set_item_wise_tax_breakup(self):
Nabin Hait9c421612017-07-20 13:32:01 +0530527 self.doc.other_charges_calculation = get_itemised_tax_breakup_html(self.doc)
Vishal Dhayaguded42242d2017-11-29 16:09:59 +0530528
Nabin Hait9c421612017-07-20 13:32:01 +0530529def get_itemised_tax_breakup_html(doc):
530 if not doc.taxes:
531 return
532 frappe.flags.company = doc.company
Vishal Dhayaguded42242d2017-11-29 16:09:59 +0530533
Nabin Hait9c421612017-07-20 13:32:01 +0530534 # get headers
Nabin Haitcaab5822017-08-24 16:22:28 +0530535 tax_accounts = []
536 for tax in doc.taxes:
537 if getattr(tax, "category", None) and tax.category=="Valuation":
538 continue
rohitwaghchaure4e17fae2017-12-12 14:40:52 +0530539 if tax.description not in tax_accounts:
Nabin Haitcaab5822017-08-24 16:22:28 +0530540 tax_accounts.append(tax.description)
541
Nabin Hait9c421612017-07-20 13:32:01 +0530542 headers = get_itemised_tax_breakup_header(doc.doctype + " Item", tax_accounts)
Vishal Dhayaguded42242d2017-11-29 16:09:59 +0530543
Nabin Hait9c421612017-07-20 13:32:01 +0530544 # get tax breakup data
545 itemised_tax, itemised_taxable_amount = get_itemised_tax_breakup_data(doc)
Nabin Haitcaab5822017-08-24 16:22:28 +0530546
547 get_rounded_tax_amount(itemised_tax, doc.precision("tax_amount", "taxes"))
548
rohitwaghchaured4526682017-12-28 14:20:13 +0530549 update_itemised_tax_data(doc)
Nabin Hait9c421612017-07-20 13:32:01 +0530550 frappe.flags.company = None
Vishal Dhayaguded42242d2017-11-29 16:09:59 +0530551
Nabin Hait9c421612017-07-20 13:32:01 +0530552 return frappe.render_template(
553 "templates/includes/itemised_tax_breakup.html", dict(
554 headers=headers,
555 itemised_tax=itemised_tax,
556 itemised_taxable_amount=itemised_taxable_amount,
557 tax_accounts=tax_accounts,
558 company_currency=erpnext.get_company_currency(doc.company)
Nabin Haitb962fc12017-07-17 18:02:31 +0530559 )
Nabin Hait9c421612017-07-20 13:32:01 +0530560 )
Nabin Hait852cb642017-07-05 12:58:19 +0530561
rohitwaghchaured4526682017-12-28 14:20:13 +0530562
563@erpnext.allow_regional
564def update_itemised_tax_data(doc):
565 #Don't delete this method, used for localization
566 pass
567
Nabin Haitb962fc12017-07-17 18:02:31 +0530568@erpnext.allow_regional
569def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
570 return [_("Item"), _("Taxable Amount")] + tax_accounts
571
572@erpnext.allow_regional
573def get_itemised_tax_breakup_data(doc):
574 itemised_tax = get_itemised_tax(doc.taxes)
575
576 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
577
578 return itemised_tax, itemised_taxable_amount
579
580def get_itemised_tax(taxes):
581 itemised_tax = {}
582 for tax in taxes:
Nabin Haitcaab5822017-08-24 16:22:28 +0530583 if getattr(tax, "category", None) and tax.category=="Valuation":
584 continue
585
Nabin Haitb962fc12017-07-17 18:02:31 +0530586 item_tax_map = json.loads(tax.item_wise_tax_detail) if tax.item_wise_tax_detail else {}
Nabin Hait2e4de832017-09-19 14:53:16 +0530587 if item_tax_map:
588 for item_code, tax_data in item_tax_map.items():
589 itemised_tax.setdefault(item_code, frappe._dict())
Vishal Dhayaguded42242d2017-11-29 16:09:59 +0530590
Nabin Hait2e4de832017-09-19 14:53:16 +0530591 if isinstance(tax_data, list):
592 itemised_tax[item_code][tax.description] = frappe._dict(dict(
593 tax_rate=flt(tax_data[0]),
594 tax_amount=flt(tax_data[1])
595 ))
596 else:
597 itemised_tax[item_code][tax.description] = frappe._dict(dict(
598 tax_rate=flt(tax_data),
599 tax_amount=0.0
600 ))
Rohit Waghchaure296fbfe2017-07-10 13:03:29 +0530601
Nabin Haitb962fc12017-07-17 18:02:31 +0530602 return itemised_tax
603
604def get_itemised_taxable_amount(items):
605 itemised_taxable_amount = frappe._dict()
606 for item in items:
Rohit Waghchaure296fbfe2017-07-10 13:03:29 +0530607 item_code = item.item_code or item.item_name
Nabin Haitb962fc12017-07-17 18:02:31 +0530608 itemised_taxable_amount.setdefault(item_code, 0)
609 itemised_taxable_amount[item_code] += item.net_amount
610
Nabin Haitcaab5822017-08-24 16:22:28 +0530611 return itemised_taxable_amount
612
613def get_rounded_tax_amount(itemised_tax, precision):
614 # Rounding based on tax_amount precision
615 for taxes in itemised_tax.values():
616 for tax_account in taxes:
617 taxes[tax_account]["tax_amount"] = flt(taxes[tax_account]["tax_amount"], precision)