blob: 63b87e1eea2cd1f2f975e763cc227bd26da22942 [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()
Anand Doshi39384d32013-05-11 19:39:53 +053095
96 # TODO
97 # allocated amount of sales person
98 # total commission
99
Anand Doshi21f4ea32013-05-10 18:08:32 +0530100 self._cleanup()
101
102 def determin_exclusive_rate(self):
103 if not any((cint(tax.included_in_print_rate) for tax in self.tax_doclist)):
104 # no inclusive tax
105 return
106
107 for item in self.item_doclist:
108 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
109 cumulated_tax_fraction = 0
110 for i, tax in enumerate(self.tax_doclist):
111 if cint(tax.included_in_print_rate):
112 tax.tax_fraction_for_current_item = \
113 self.get_current_tax_fraction(tax, item_tax_map)
114 else:
115 tax.tax_fraction_for_current_item = 0
116
117 if i==0:
118 tax.grand_total_fraction_for_current_item = 1 + \
119 tax.tax_fraction_for_current_item
120 else:
121 tax.grand_total_fraction_for_current_item = \
122 self.tax_doclist[i-1].grand_total_fraction_for_current_item \
123 + tax.tax_fraction_for_current_item
124
125 cumulated_tax_fraction += tax.tax_fraction_for_current_item
126
127 if cumulated_tax_fraction:
128 item.basic_rate = flt((item.export_rate * self.doc.conversion_rate) /
Anand Doshi39384d32013-05-11 19:39:53 +0530129 (1 + cumulated_tax_fraction), self.precision("basic_rate", item))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530130
Anand Doshi39384d32013-05-11 19:39:53 +0530131 item.amount = flt(item.basic_rate * item.qty, self.precision("amount", item))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530132
133 item.base_ref_rate = flt(item.basic_rate / (1 - (item.adj_rate / 100.0)),
Anand Doshi39384d32013-05-11 19:39:53 +0530134 self.precision("base_ref_rate", item))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530135
136 def get_current_tax_fraction(self, tax, item_tax_map):
137 """
138 Get tax fraction for calculating tax exclusive amount
139 from tax inclusive amount
140 """
141 current_tax_fraction = 0
142
143 if cint(tax.included_in_print_rate):
144 tax_rate = self._get_tax_rate(tax, item_tax_map)
145
146 if tax.charge_type == "On Net Total":
147 current_tax_fraction = tax_rate / 100.0
148
149 elif tax.charge_type == "On Previous Row Amount":
150 current_tax_fraction = (tax_rate / 100.0) * \
151 self.tax_doclist[cint(tax.row_id) - 1].tax_fraction_for_current_item
152
153 elif tax.charge_type == "On Previous Row Total":
154 current_tax_fraction = (tax_rate / 100.0) * \
155 self.tax_doclist[cint(tax.row_id) - 1].grand_total_fraction_for_current_item
156
157 return current_tax_fraction
158
159 def calculate_item_values(self):
160 def _set_base(item, print_field, base_field):
161 """set values in base currency"""
162 item.fields[base_field] = flt((flt(item.fields[print_field],
Anand Doshi39384d32013-05-11 19:39:53 +0530163 self.precision(print_field, item)) * self.doc.conversion_rate),
164 self.precision(base_field, item))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530165
166 for item in self.item_doclist:
Anand Doshi39384d32013-05-11 19:39:53 +0530167 self.round_floats_in(item)
Anand Doshi21f4ea32013-05-10 18:08:32 +0530168
169 if item.adj_rate == 100:
170 item.ref_rate = item.ref_rate or item.export_rate
171 item.export_rate = 0
172 else:
173 if item.ref_rate:
174 item.export_rate = flt(item.ref_rate * (1.0 - (item.adj_rate / 100.0)),
Anand Doshi39384d32013-05-11 19:39:53 +0530175 self.precision("export_rate", item))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530176 else:
177 # assume that print rate and discount are specified
178 item.ref_rate = flt(item.export_rate / (1.0 - (item.adj_rate / 100.0)),
Anand Doshi39384d32013-05-11 19:39:53 +0530179 self.precision("ref_rate", item))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530180
181 item.export_amount = flt(item.export_rate * item.qty,
Anand Doshi39384d32013-05-11 19:39:53 +0530182 self.precision("export_amount", item))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530183
184 _set_base(item, "ref_rate", "base_ref_rate")
185 _set_base(item, "export_rate", "basic_rate")
186 _set_base(item, "export_amount", "amount")
187
188 def initialize_taxes(self):
189 for tax in self.tax_doclist:
190 tax.tax_amount = tax.total = 0.0
191 # temporary fields
192 tax.tax_amount_for_current_item = tax.grand_total_for_current_item = 0.0
193 tax.item_wise_tax_detail = {}
194 self.validate_on_previous_row(tax)
195 self.validate_inclusive_tax(tax)
Anand Doshi39384d32013-05-11 19:39:53 +0530196 self.round_floats_in(tax)
Anand Doshi21f4ea32013-05-10 18:08:32 +0530197
198 def calculate_net_total(self):
199 self.doc.net_total = 0
200 self.doc.net_total_export = 0
201
202 for item in self.item_doclist:
203 self.doc.net_total += item.amount
204 self.doc.net_total_export += item.export_amount
205
Anand Doshi5af812a2013-05-10 19:23:02 +0530206 self.doc.net_total = flt(self.doc.net_total, self.precision("net_total"))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530207 self.doc.net_total_export = flt(self.doc.net_total_export,
Anand Doshi5af812a2013-05-10 19:23:02 +0530208 self.precision("net_total_export"))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530209
210 def calculate_taxes(self):
211 for item in self.item_doclist:
212 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
213
214 for i, tax in enumerate(self.tax_doclist):
215 # tax_amount represents the amount of tax for the current step
216 current_tax_amount = self.get_current_tax_amount(item, tax, item_tax_map)
217
218 # case when net total is 0 but there is an actual type charge
219 # in this case add the actual amount to tax.tax_amount
220 # and tax.grand_total_for_current_item for the first such iteration
221 if not (current_tax_amount or self.doc.net_total or tax.tax_amount) and \
222 tax.charge_type=="Actual":
Anand Doshi39384d32013-05-11 19:39:53 +0530223 zero_net_total_adjustment = flt(tax.rate, self.precision("tax_amount", tax))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530224 current_tax_amount += zero_net_total_adjustment
225
226 # store tax_amount for current item as it will be used for
227 # charge type = 'On Previous Row Amount'
228 tax.tax_amount_for_current_item = current_tax_amount
229
230 # accumulate tax amount into tax.tax_amount
231 tax.tax_amount += tax.tax_amount_for_current_item
232
233 # Calculate tax.total viz. grand total till that step
234 # note: grand_total_for_current_item contains the contribution of
235 # item's amount, previously applied tax and the current tax on that item
236 if i==0:
237 tax.grand_total_for_current_item = flt(item.amount +
Anand Doshi39384d32013-05-11 19:39:53 +0530238 current_tax_amount, self.precision("total", tax))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530239
240 else:
241 tax.grand_total_for_current_item = \
242 flt(self.tax_doclist[i-1].grand_total_for_current_item +
Anand Doshi39384d32013-05-11 19:39:53 +0530243 current_tax_amount, self.precision("total", tax))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530244
245 # in tax.total, accumulate grand total of each item
246 tax.total += tax.grand_total_for_current_item
247
248 # store tax_breakup for each item
249 # DOUBT: should valuation type amount also be stored?
250 tax.item_wise_tax_detail[item.item_code] = current_tax_amount
251
252 def calculate_totals(self):
253 self.doc.grand_total = flt(self.tax_doclist and \
Anand Doshi5af812a2013-05-10 19:23:02 +0530254 self.tax_doclist[-1].total or self.doc.net_total, self.precision("grand_total"))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530255 self.doc.grand_total_export = flt(self.doc.grand_total / self.doc.conversion_rate,
Anand Doshi5af812a2013-05-10 19:23:02 +0530256 self.precision("grand_total_export"))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530257
258 self.doc.rounded_total = round(self.doc.grand_total)
259 self.doc.rounded_total_export = round(self.doc.grand_total_export)
260
261 def get_current_tax_amount(self, item, tax, item_tax_map):
262 tax_rate = self._get_tax_rate(tax, item_tax_map)
263
264 if tax.charge_type == "Actual":
265 # distribute the tax amount proportionally to each item row
Anand Doshi39384d32013-05-11 19:39:53 +0530266 actual = flt(tax.rate, self.precision("tax_amount", tax))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530267 current_tax_amount = (self.doc.net_total
268 and ((item.amount / self.doc.net_total) * actual)
269 or 0)
270 elif tax.charge_type == "On Net Total":
271 current_tax_amount = (tax_rate / 100.0) * item.amount
272 elif tax.charge_type == "On Previous Row Amount":
273 current_tax_amount = (tax_rate / 100.0) * \
274 self.tax_doclist[cint(tax.row_id) - 1].tax_amount_for_current_item
275 elif tax.charge_type == "On Previous Row Total":
276 current_tax_amount = (tax_rate / 100.0) * \
277 self.tax_doclist[cint(tax.row_id) - 1].grand_total_for_current_item
278
Anand Doshi39384d32013-05-11 19:39:53 +0530279 return flt(current_tax_amount, self.precision("tax_amount", tax))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530280
281 def validate_on_previous_row(self, tax):
282 """
283 validate if a valid row id is mentioned in case of
284 On Previous Row Amount and On Previous Row Total
285 """
286 if tax.charge_type in ["On Previous Row Amount", "On Previous Row Total"] and \
287 (not tax.row_id or cint(tax.row_id) >= tax.idx):
288 msgprint((_("Row") + " # %(idx)s [%(taxes_doctype)s]: " + \
289 _("Please specify a valid") + " %(row_id_label)s") % {
290 "idx": tax.idx,
291 "taxes_doctype": tax.parenttype,
292 "row_id_label": self.meta.get_label("row_id",
293 parentfield="other_charges")
294 }, raise_exception=True)
295
296 def validate_inclusive_tax(self, tax):
297 def _on_previous_row_error(tax, row_range):
298 msgprint((_("Row")
299 + " # %(idx)s [%(taxes_doctype)s] [%(charge_type_label)s = \"%(charge_type)s\"]: "
300 + _("If:") + ' "%(inclusive_label)s" = ' + _("checked") + ", "
301 + _("then it is required that:") + " [" + _("Row") + " # %(row_range)s] "
302 + '"%(inclusive_label)s" = ' + _("checked")) % {
303 "idx": tax.idx,
304 "taxes_doctype": tax.doctype,
305 "inclusive_label": self.meta.get_label("included_in_print_rate",
306 parentfield="other_charges"),
307 "charge_type_label": self.meta.get_label("charge_type",
308 parentfield="other_charges"),
309 "charge_type": tax.charge_type,
310 "row_range": row_range
311 }, raise_exception=True)
312
313 if cint(tax.included_in_print_rate):
314 if tax.charge_type == "Actual":
315 # inclusive cannot be of type Actual
316 msgprint((_("Row")
317 + " # %(idx)s [%(taxes_doctype)s]: %(charge_type_label)s = \"%(charge_type)s\" "
318 + "cannot be included in Item's rate") % {
319 "idx": tax.idx,
320 "taxes_doctype": tax.doctype,
321 "charge_type_label": self.meta.get_label("charge_type",
322 parentfield="other_charges"),
323 "charge_type": tax.charge_type,
324 }, raise_exception=True)
325 elif tax.charge_type == "On Previous Row Amount" and \
326 not cint(self.tax_doclist[tax.row_id - 1].included_in_print_rate):
327 # referred row should also be inclusive
328 _on_previous_row_error(tax, tax.row_id)
329 elif tax.charge_type == "On Previous Row Total" and \
330 not all([cint(t.included_in_print_rate) for t in self.tax_doclist[:tax.idx - 1]]):
331 # all rows about this tax should be inclusive
332 _on_previous_row_error(tax, "1 - %d" % (tax.idx - 1,))
333
334 def _load_item_tax_rate(self, item_tax_rate):
335 if not item_tax_rate:
336 return {}
337 return json.loads(item_tax_rate)
338
339 def _get_tax_rate(self, tax, item_tax_map):
340 if item_tax_map.has_key(tax.account_head):
Anand Doshi39384d32013-05-11 19:39:53 +0530341 return flt(item_tax_map.get(tax.account_head), self.precision("rate", tax))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530342 else:
343 return tax.rate
344
345 def _cleanup(self):
346 for tax in self.tax_doclist:
347 del tax.fields["grand_total_for_current_item"]
348 del tax.fields["tax_amount_for_current_item"]
349
350 for fieldname in ("tax_fraction_for_current_item",
351 "grand_total_fraction_for_current_item"):
352 if fieldname in tax.fields:
353 del tax.fields[fieldname]
354
355 tax.item_wise_tax_detail = json.dumps(tax.item_wise_tax_detail)
Anand Doshi1dde46a2013-05-15 21:15:57 +0530356
357 def validate_order_type(self):
358 valid_types = ["Sales", "Maintenance"]
359 if self.doc.order_type not in valid_types:
360 msgprint(_(self.meta.get_label("order_type")) + " " +
361 _("must be one of") + ": " + comma_or(valid_types),
362 raise_exception=True)