blob: 020e2af3159035cf8f76aa1fc2b8640d53ab3b12 [file] [log] [blame]
Nabin Haitec52db82013-01-22 11:53:14 +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 Doshi21f4ea32013-05-10 18:08:32 +053019from webnotes.utils import cint, flt
Nabin Haitec52db82013-01-22 11:53:14 +053020from setup.utils import get_company_currency
Nabin Hait0fc24542013-03-25 11:06:00 +053021from webnotes import msgprint, _
Anand Doshi21f4ea32013-05-10 18:08:32 +053022import json
Nabin Haitec52db82013-01-22 11:53:14 +053023
Nabin Haitc3afb252013-03-19 12:01:24 +053024from controllers.stock_controller import StockController
Nabin Haitbf495c92013-01-30 12:49:08 +053025
Nabin Haitc3afb252013-03-19 12:01:24 +053026class SellingController(StockController):
Nabin Haitec52db82013-01-22 11:53:14 +053027 def validate(self):
Saurabh6f753182013-03-20 12:55:28 +053028 super(SellingController, self).validate()
Nabin Haitec52db82013-01-22 11:53:14 +053029 self.set_total_in_words()
30
31 def set_total_in_words(self):
32 from webnotes.utils import money_in_words
33 company_currency = get_company_currency(self.doc.company)
Nabin Hait6f1a5ec2013-02-20 16:25:05 +053034
35 disable_rounded_total = cint(webnotes.conn.get_value("Global Defaults", None,
36 "disable_rounded_total"))
37
Nabin Haitec52db82013-01-22 11:53:14 +053038 if self.meta.get_field("in_words"):
Nabin Hait6f1a5ec2013-02-20 16:25:05 +053039 self.doc.in_words = money_in_words(disable_rounded_total and
40 self.doc.grand_total or self.doc.rounded_total, company_currency)
Nabin Haitec52db82013-01-22 11:53:14 +053041 if self.meta.get_field("in_words_export"):
Nabin Hait6f1a5ec2013-02-20 16:25:05 +053042 self.doc.in_words_export = money_in_words(disable_rounded_total and
Nabin Hait8c7234f2013-03-11 16:32:33 +053043 self.doc.grand_total_export or self.doc.rounded_total_export, self.doc.currency)
Nabin Haita0e7c152013-03-21 18:37:06 +053044
Nabin Hait787c02e2013-03-29 16:42:33 +053045 def set_buying_amount(self, stock_ledger_entries = None):
Anand Doshi8c5844e2013-03-21 20:24:10 +053046 from stock.utils import get_buying_amount
Nabin Hait787c02e2013-03-29 16:42:33 +053047 if not stock_ledger_entries:
48 stock_ledger_entries = self.get_stock_ledger_entries()
Anand Doshi8c5844e2013-03-21 20:24:10 +053049
50 item_sales_bom = {}
51 for d in self.doclist.get({"parentfield": "packing_details"}):
52 new_d = webnotes._dict(d.fields.copy())
53 new_d.total_qty = -1 * d.qty
54 item_sales_bom.setdefault(d.parent_item, []).append(new_d)
Nabin Haita0e7c152013-03-21 18:37:06 +053055
56 if stock_ledger_entries:
57 for item in self.doclist.get({"parentfield": self.fname}):
58 if item.item_code in self.stock_items or \
59 (item_sales_bom and item_sales_bom.get(item.item_code)):
60 buying_amount = get_buying_amount(item.item_code, item.warehouse, -1*item.qty,
61 self.doc.doctype, self.doc.name, item.name, stock_ledger_entries,
62 item_sales_bom)
Nabin Haitf2d4df92013-05-07 13:12:02 +053063
64 item.buying_amount = buying_amount >= 0.01 and buying_amount or 0
Nabin Hait0fc24542013-03-25 11:06:00 +053065 webnotes.conn.set_value(item.doctype, item.name, "buying_amount",
66 item.buying_amount)
67
68 def check_expense_account(self, item):
69 if item.buying_amount and not item.expense_account:
70 msgprint(_("""Expense account is mandatory for item: """) + item.item_code,
Nabin Hait787c02e2013-03-29 16:42:33 +053071 raise_exception=1)
72
73 if item.buying_amount and not item.cost_center:
74 msgprint(_("""Cost Center is mandatory for item: """) + item.item_code,
Anand Doshi21f4ea32013-05-10 18:08:32 +053075 raise_exception=1)
76
77 def calculate_taxes_and_totals(self):
78 self.doc.conversion_rate = flt(self.doc.conversion_rate)
79 self.item_doclist = self.doclist.get({"parentfield": self.fname})
80 self.tax_doclist = self.doclist.get({"parentfield": "other_charges"})
81
82 self.calculate_item_values()
83 self.initialize_taxes()
84
85 self.determin_exclusive_rate()
86
87 # TODO
88 # code: save net_total_export on client side
89 # print format: show net_total_export instead of net_total
90
91 self.calculate_net_total()
92 self.calculate_taxes()
93 self.calculate_totals()
94 # self.calculate_outstanding_amount()
95 #
96 self._cleanup()
97
98 def determin_exclusive_rate(self):
99 if not any((cint(tax.included_in_print_rate) for tax in self.tax_doclist)):
100 # no inclusive tax
101 return
102
103 for item in self.item_doclist:
104 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
105 cumulated_tax_fraction = 0
106 for i, tax in enumerate(self.tax_doclist):
107 if cint(tax.included_in_print_rate):
108 tax.tax_fraction_for_current_item = \
109 self.get_current_tax_fraction(tax, item_tax_map)
110 else:
111 tax.tax_fraction_for_current_item = 0
112
113 if i==0:
114 tax.grand_total_fraction_for_current_item = 1 + \
115 tax.tax_fraction_for_current_item
116 else:
117 tax.grand_total_fraction_for_current_item = \
118 self.tax_doclist[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:
124 item.basic_rate = flt((item.export_rate * self.doc.conversion_rate) /
Anand Doshi5af812a2013-05-10 19:23:02 +0530125 (1 + cumulated_tax_fraction), self.precision("basic_rate", item.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530126
Anand Doshi5af812a2013-05-10 19:23:02 +0530127 item.amount = flt(item.basic_rate * item.qty, self.precision("amount", item.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530128
129 item.base_ref_rate = flt(item.basic_rate / (1 - (item.adj_rate / 100.0)),
Anand Doshi5af812a2013-05-10 19:23:02 +0530130 self.precision("base_ref_rate", item.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530131
132 def get_current_tax_fraction(self, tax, item_tax_map):
133 """
134 Get tax fraction for calculating tax exclusive amount
135 from tax inclusive amount
136 """
137 current_tax_fraction = 0
138
139 if cint(tax.included_in_print_rate):
140 tax_rate = self._get_tax_rate(tax, item_tax_map)
141
142 if tax.charge_type == "On Net Total":
143 current_tax_fraction = tax_rate / 100.0
144
145 elif tax.charge_type == "On Previous Row Amount":
146 current_tax_fraction = (tax_rate / 100.0) * \
147 self.tax_doclist[cint(tax.row_id) - 1].tax_fraction_for_current_item
148
149 elif tax.charge_type == "On Previous Row Total":
150 current_tax_fraction = (tax_rate / 100.0) * \
151 self.tax_doclist[cint(tax.row_id) - 1].grand_total_fraction_for_current_item
152
153 return current_tax_fraction
154
155 def calculate_item_values(self):
156 def _set_base(item, print_field, base_field):
157 """set values in base currency"""
158 item.fields[base_field] = flt((flt(item.fields[print_field],
Anand Doshi5af812a2013-05-10 19:23:02 +0530159 self.precision(print_field, item.parentfield)) * self.doc.conversion_rate),
160 self.precision(base_field, item.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530161
162 for item in self.item_doclist:
163 self.round_floats_in_doc(item, item.parentfield)
164
165 if item.adj_rate == 100:
166 item.ref_rate = item.ref_rate or item.export_rate
167 item.export_rate = 0
168 else:
169 if item.ref_rate:
170 item.export_rate = flt(item.ref_rate * (1.0 - (item.adj_rate / 100.0)),
Anand Doshi5af812a2013-05-10 19:23:02 +0530171 self.precision("export_rate", item.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530172 else:
173 # assume that print rate and discount are specified
174 item.ref_rate = flt(item.export_rate / (1.0 - (item.adj_rate / 100.0)),
Anand Doshi5af812a2013-05-10 19:23:02 +0530175 self.precision("ref_rate", item.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530176
177 item.export_amount = flt(item.export_rate * item.qty,
Anand Doshi5af812a2013-05-10 19:23:02 +0530178 self.precision("export_amount", item.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530179
180 _set_base(item, "ref_rate", "base_ref_rate")
181 _set_base(item, "export_rate", "basic_rate")
182 _set_base(item, "export_amount", "amount")
183
184 def initialize_taxes(self):
185 for tax in self.tax_doclist:
186 tax.tax_amount = tax.total = 0.0
187 # temporary fields
188 tax.tax_amount_for_current_item = tax.grand_total_for_current_item = 0.0
189 tax.item_wise_tax_detail = {}
190 self.validate_on_previous_row(tax)
191 self.validate_inclusive_tax(tax)
192 self.round_floats_in_doc(tax, tax.parentfield)
193
194 def calculate_net_total(self):
195 self.doc.net_total = 0
196 self.doc.net_total_export = 0
197
198 for item in self.item_doclist:
199 self.doc.net_total += item.amount
200 self.doc.net_total_export += item.export_amount
201
Anand Doshi5af812a2013-05-10 19:23:02 +0530202 self.doc.net_total = flt(self.doc.net_total, self.precision("net_total"))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530203 self.doc.net_total_export = flt(self.doc.net_total_export,
Anand Doshi5af812a2013-05-10 19:23:02 +0530204 self.precision("net_total_export"))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530205
206 def calculate_taxes(self):
207 for item in self.item_doclist:
208 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
209
210 for i, tax in enumerate(self.tax_doclist):
211 # tax_amount represents the amount of tax for the current step
212 current_tax_amount = self.get_current_tax_amount(item, tax, item_tax_map)
213
214 # case when net total is 0 but there is an actual type charge
215 # in this case add the actual amount to tax.tax_amount
216 # and tax.grand_total_for_current_item for the first such iteration
217 if not (current_tax_amount or self.doc.net_total or tax.tax_amount) and \
218 tax.charge_type=="Actual":
Anand Doshi5af812a2013-05-10 19:23:02 +0530219 zero_net_total_adjustment = flt(tax.rate, self.precision("tax_amount", tax.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530220 current_tax_amount += zero_net_total_adjustment
221
222 # store tax_amount for current item as it will be used for
223 # charge type = 'On Previous Row Amount'
224 tax.tax_amount_for_current_item = current_tax_amount
225
226 # accumulate tax amount into tax.tax_amount
227 tax.tax_amount += tax.tax_amount_for_current_item
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.amount +
Anand Doshi5af812a2013-05-10 19:23:02 +0530234 current_tax_amount, self.precision("total", tax.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530235
236 else:
237 tax.grand_total_for_current_item = \
238 flt(self.tax_doclist[i-1].grand_total_for_current_item +
Anand Doshi5af812a2013-05-10 19:23:02 +0530239 current_tax_amount, self.precision("total", tax.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530240
241 # in tax.total, accumulate grand total of each item
242 tax.total += tax.grand_total_for_current_item
243
244 # store tax_breakup for each item
245 # DOUBT: should valuation type amount also be stored?
246 tax.item_wise_tax_detail[item.item_code] = current_tax_amount
247
248 def calculate_totals(self):
249 self.doc.grand_total = flt(self.tax_doclist and \
Anand Doshi5af812a2013-05-10 19:23:02 +0530250 self.tax_doclist[-1].total or self.doc.net_total, self.precision("grand_total"))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530251 self.doc.grand_total_export = flt(self.doc.grand_total / self.doc.conversion_rate,
Anand Doshi5af812a2013-05-10 19:23:02 +0530252 self.precision("grand_total_export"))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530253
254 self.doc.rounded_total = round(self.doc.grand_total)
255 self.doc.rounded_total_export = round(self.doc.grand_total_export)
256
257 def get_current_tax_amount(self, item, tax, item_tax_map):
258 tax_rate = self._get_tax_rate(tax, item_tax_map)
259
260 if tax.charge_type == "Actual":
261 # distribute the tax amount proportionally to each item row
Anand Doshi5af812a2013-05-10 19:23:02 +0530262 actual = flt(tax.rate, self.precision("tax_amount", tax.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530263 current_tax_amount = (self.doc.net_total
264 and ((item.amount / self.doc.net_total) * actual)
265 or 0)
266 elif tax.charge_type == "On Net Total":
267 current_tax_amount = (tax_rate / 100.0) * item.amount
268 elif tax.charge_type == "On Previous Row Amount":
269 current_tax_amount = (tax_rate / 100.0) * \
270 self.tax_doclist[cint(tax.row_id) - 1].tax_amount_for_current_item
271 elif tax.charge_type == "On Previous Row Total":
272 current_tax_amount = (tax_rate / 100.0) * \
273 self.tax_doclist[cint(tax.row_id) - 1].grand_total_for_current_item
274
Anand Doshi5af812a2013-05-10 19:23:02 +0530275 return flt(current_tax_amount, self.precision("tax_amount", tax.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530276
277 def validate_on_previous_row(self, tax):
278 """
279 validate if a valid row id is mentioned in case of
280 On Previous Row Amount and On Previous Row Total
281 """
282 if tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"] and \
283 (not tax.row_id or cint(tax.row_id) >= tax.idx):
284 msgprint((_("Row") + " # %(idx)s [%(taxes_doctype)s]: " + \
285 _("Please specify a valid") + " %(row_id_label)s") % {
286 "idx": tax.idx,
287 "taxes_doctype": tax.parenttype,
288 "row_id_label": self.meta.get_label("row_id",
289 parentfield="other_charges")
290 }, raise_exception=True)
291
292 def validate_inclusive_tax(self, tax):
293 def _on_previous_row_error(tax, row_range):
294 msgprint((_("Row")
295 + " # %(idx)s [%(taxes_doctype)s] [%(charge_type_label)s = \"%(charge_type)s\"]: "
296 + _("If:") + ' "%(inclusive_label)s" = ' + _("checked") + ", "
297 + _("then it is required that:") + " [" + _("Row") + " # %(row_range)s] "
298 + '"%(inclusive_label)s" = ' + _("checked")) % {
299 "idx": tax.idx,
300 "taxes_doctype": tax.doctype,
301 "inclusive_label": self.meta.get_label("included_in_print_rate",
302 parentfield="other_charges"),
303 "charge_type_label": self.meta.get_label("charge_type",
304 parentfield="other_charges"),
305 "charge_type": tax.charge_type,
306 "row_range": row_range
307 }, raise_exception=True)
308
309 if cint(tax.included_in_print_rate):
310 if tax.charge_type == "Actual":
311 # inclusive cannot be of type Actual
312 msgprint((_("Row")
313 + " # %(idx)s [%(taxes_doctype)s]: %(charge_type_label)s = \"%(charge_type)s\" "
314 + "cannot be included in Item's rate") % {
315 "idx": tax.idx,
316 "taxes_doctype": tax.doctype,
317 "charge_type_label": self.meta.get_label("charge_type",
318 parentfield="other_charges"),
319 "charge_type": tax.charge_type,
320 }, raise_exception=True)
321 elif tax.charge_type == "On Previous Row Amount" and \
322 not cint(self.tax_doclist[tax.row_id - 1].included_in_print_rate):
323 # referred row should also be inclusive
324 _on_previous_row_error(tax, tax.row_id)
325 elif tax.charge_type == "On Previous Row Total" and \
326 not all([cint(t.included_in_print_rate) for t in self.tax_doclist[:tax.idx - 1]]):
327 # all rows about this tax should be inclusive
328 _on_previous_row_error(tax, "1 - %d" % (tax.idx - 1,))
329
330 def _load_item_tax_rate(self, item_tax_rate):
331 if not item_tax_rate:
332 return {}
333 return json.loads(item_tax_rate)
334
335 def _get_tax_rate(self, tax, item_tax_map):
336 if item_tax_map.has_key(tax.account_head):
Anand Doshi5af812a2013-05-10 19:23:02 +0530337 return flt(item_tax_map.get(tax.account_head), self.precision("rate", tax.parentfield))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530338 else:
339 return tax.rate
340
341 def _cleanup(self):
342 for tax in self.tax_doclist:
343 del tax.fields["grand_total_for_current_item"]
344 del tax.fields["tax_amount_for_current_item"]
345
346 for fieldname in ("tax_fraction_for_current_item",
347 "grand_total_fraction_for_current_item"):
348 if fieldname in tax.fields:
349 del tax.fields[fieldname]
350
351 tax.item_wise_tax_detail = json.dumps(tax.item_wise_tax_detail)