blob: a075ad4c4b366ece2593cac55782b8f40c78884a [file] [log] [blame]
Rushabh Mehtaad45e312013-11-20 12:59:58 +05301# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Nabin Haitec52db82013-01-22 11:53:14 +05303
4from __future__ import unicode_literals
5import webnotes
Nabin Haitd1fd1e22013-10-18 12:29:11 +05306from webnotes.utils import cint, flt, comma_or, _round, cstr
Rushabh Mehta1f847992013-12-12 19:12:19 +05307from erpnext.setup.utils import get_company_currency
8from erpnext.selling.utils import get_item_details
Nabin Hait0fc24542013-03-25 11:06:00 +05309from webnotes import msgprint, _
Nabin Haitec52db82013-01-22 11:53:14 +053010
Rushabh Mehta1f847992013-12-12 19:12:19 +053011from erpnext.controllers.stock_controller import StockController
Nabin Haitbf495c92013-01-30 12:49:08 +053012
Nabin Haitc3afb252013-03-19 12:01:24 +053013class SellingController(StockController):
Anand Doshif3096132013-05-21 19:35:06 +053014 def onload_post_render(self):
Anand Doshif3096132013-05-21 19:35:06 +053015 # contact, address, item details and pos details (if applicable)
16 self.set_missing_values()
Nabin Haitd1fd1e22013-10-18 12:29:11 +053017
18 def validate(self):
19 super(SellingController, self).validate()
20 self.validate_max_discount()
21 check_active_sales_items(self)
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053022
23 def get_sender(self, comm):
24 return webnotes.conn.get_value('Sales Email Settings', None, 'email_id')
25
Anand Doshif3096132013-05-21 19:35:06 +053026 def set_missing_values(self, for_validate=False):
Anand Doshiabc10032013-06-14 17:44:03 +053027 super(SellingController, self).set_missing_values(for_validate)
28
Anand Doshif3096132013-05-21 19:35:06 +053029 # set contact and address details for customer, if they are not mentioned
Anand Doshiabc10032013-06-14 17:44:03 +053030 self.set_missing_lead_customer_details()
Nabin Hait096d3632013-10-17 17:01:14 +053031 self.set_price_list_and_item_details()
Rushabh Mehtae89c5332013-08-29 15:32:46 +053032 if self.doc.fields.get("__islocal"):
Akhilesh Darjee2ced3b02014-01-28 19:16:05 +053033 self.set_taxes("other_charges", "taxes_and_charges")
Nabin Hait7a75e102013-09-17 10:21:20 +053034
Anand Doshiabc10032013-06-14 17:44:03 +053035 def set_missing_lead_customer_details(self):
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053036 from erpnext.accounts.party import get_party_details
Anand Doshiabc10032013-06-14 17:44:03 +053037 if self.doc.customer:
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053038 self.doc.update_if_missing(get_party_details(self.doc.customer))
Anand Doshiabc10032013-06-14 17:44:03 +053039
Anand Doshiabc10032013-06-14 17:44:03 +053040 elif self.doc.lead:
Rushabh Mehta24da7612014-01-29 15:26:04 +053041 self.doc.update_if_missing(self.get_lead_defaults())
Anand Doshi99100a42013-07-04 17:13:53 +053042
Nabin Hait096d3632013-10-17 17:01:14 +053043 def set_price_list_and_item_details(self):
44 self.set_price_list_currency("Selling")
Anand Doshi99100a42013-07-04 17:13:53 +053045 self.set_missing_item_details(get_item_details)
Nabin Hait2bd37772013-07-08 19:00:29 +053046
Anand Doshi99100a42013-07-04 17:13:53 +053047 def apply_shipping_rule(self):
48 if self.doc.shipping_rule:
49 shipping_rule = webnotes.bean("Shipping Rule", self.doc.shipping_rule)
50 value = self.doc.net_total
51
52 # TODO
53 # shipping rule calculation based on item's net weight
54
55 shipping_amount = 0.0
56 for condition in shipping_rule.doclist.get({"parentfield": "shipping_rule_conditions"}):
57 if not condition.to_value or (flt(condition.from_value) <= value <= flt(condition.to_value)):
58 shipping_amount = condition.shipping_amount
59 break
Anand Doshi0b4943c2013-07-04 23:45:22 +053060
61 self.doclist.append({
62 "doctype": "Sales Taxes and Charges",
63 "parentfield": "other_charges",
64 "charge_type": "Actual",
65 "account_head": shipping_rule.doc.account,
66 "cost_center": shipping_rule.doc.cost_center,
67 "description": shipping_rule.doc.label,
68 "rate": shipping_amount
69 })
Anand Doshifc777182013-05-27 19:29:07 +053070
Nabin Haitec52db82013-01-22 11:53:14 +053071 def set_total_in_words(self):
72 from webnotes.utils import money_in_words
73 company_currency = get_company_currency(self.doc.company)
Nabin Hait6f1a5ec2013-02-20 16:25:05 +053074
75 disable_rounded_total = cint(webnotes.conn.get_value("Global Defaults", None,
76 "disable_rounded_total"))
77
Nabin Haitec52db82013-01-22 11:53:14 +053078 if self.meta.get_field("in_words"):
Nabin Hait6f1a5ec2013-02-20 16:25:05 +053079 self.doc.in_words = money_in_words(disable_rounded_total and
80 self.doc.grand_total or self.doc.rounded_total, company_currency)
Nabin Haitec52db82013-01-22 11:53:14 +053081 if self.meta.get_field("in_words_export"):
Nabin Hait6f1a5ec2013-02-20 16:25:05 +053082 self.doc.in_words_export = money_in_words(disable_rounded_total and
Nabin Hait8c7234f2013-03-11 16:32:33 +053083 self.doc.grand_total_export or self.doc.rounded_total_export, self.doc.currency)
Anand Doshi21f4ea32013-05-10 18:08:32 +053084
85 def calculate_taxes_and_totals(self):
Anand Doshi3543f302013-05-24 19:25:01 +053086 self.other_fname = "other_charges"
Anand Doshi21f4ea32013-05-10 18:08:32 +053087
Anand Doshi3543f302013-05-24 19:25:01 +053088 super(SellingController, self).calculate_taxes_and_totals()
89
Anand Doshi923d41d2013-05-28 17:23:36 +053090 self.calculate_total_advance("Sales Invoice", "advance_adjustment_details")
Anand Doshif3096132013-05-21 19:35:06 +053091 self.calculate_commission()
92 self.calculate_contribution()
Anand Doshi3543f302013-05-24 19:25:01 +053093
Anand Doshif3096132013-05-21 19:35:06 +053094 def determine_exclusive_rate(self):
Anand Doshi21f4ea32013-05-10 18:08:32 +053095 if not any((cint(tax.included_in_print_rate) for tax in self.tax_doclist)):
96 # no inclusive tax
97 return
98
99 for item in self.item_doclist:
100 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
101 cumulated_tax_fraction = 0
102 for i, tax in enumerate(self.tax_doclist):
Anand Doshif3096132013-05-21 19:35:06 +0530103 tax.tax_fraction_for_current_item = self.get_current_tax_fraction(tax, item_tax_map)
104
Anand Doshi21f4ea32013-05-10 18:08:32 +0530105 if i==0:
Anand Doshif3096132013-05-21 19:35:06 +0530106 tax.grand_total_fraction_for_current_item = 1 + tax.tax_fraction_for_current_item
Anand Doshi21f4ea32013-05-10 18:08:32 +0530107 else:
108 tax.grand_total_fraction_for_current_item = \
109 self.tax_doclist[i-1].grand_total_fraction_for_current_item \
110 + tax.tax_fraction_for_current_item
111
112 cumulated_tax_fraction += tax.tax_fraction_for_current_item
113
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530114 if cumulated_tax_fraction and not self.discount_amount_applied:
Anand Doshifbe1e162013-08-06 19:38:19 +0530115 item.amount = flt((item.export_amount * self.doc.conversion_rate) /
116 (1 + cumulated_tax_fraction), self.precision("amount", item))
117
118 item.basic_rate = flt(item.amount / item.qty, self.precision("basic_rate", item))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530119
Anand Doshif3096132013-05-21 19:35:06 +0530120 if item.adj_rate == 100:
121 item.base_ref_rate = item.basic_rate
122 item.basic_rate = 0.0
123 else:
124 item.base_ref_rate = flt(item.basic_rate / (1 - (item.adj_rate / 100.0)),
125 self.precision("base_ref_rate", item))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530126
127 def get_current_tax_fraction(self, tax, item_tax_map):
128 """
129 Get tax fraction for calculating tax exclusive amount
130 from tax inclusive amount
131 """
132 current_tax_fraction = 0
133
134 if cint(tax.included_in_print_rate):
135 tax_rate = self._get_tax_rate(tax, item_tax_map)
136
137 if tax.charge_type == "On Net Total":
138 current_tax_fraction = tax_rate / 100.0
139
140 elif tax.charge_type == "On Previous Row Amount":
141 current_tax_fraction = (tax_rate / 100.0) * \
142 self.tax_doclist[cint(tax.row_id) - 1].tax_fraction_for_current_item
143
144 elif tax.charge_type == "On Previous Row Total":
145 current_tax_fraction = (tax_rate / 100.0) * \
146 self.tax_doclist[cint(tax.row_id) - 1].grand_total_fraction_for_current_item
147
148 return current_tax_fraction
149
150 def calculate_item_values(self):
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530151 if not self.discount_amount_applied:
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530152 for item in self.item_doclist:
153 self.round_floats_in(item)
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530154
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530155 if item.adj_rate == 100:
156 item.export_rate = 0
157 elif not item.export_rate:
158 item.export_rate = flt(item.ref_rate * (1.0 - (item.adj_rate / 100.0)),
159 self.precision("export_rate", item))
160
161 item.export_amount = flt(item.export_rate * item.qty,
162 self.precision("export_amount", item))
163
164 self._set_in_company_currency(item, "ref_rate", "base_ref_rate")
165 self._set_in_company_currency(item, "export_rate", "basic_rate")
166 self._set_in_company_currency(item, "export_amount", "amount")
167
Anand Doshi21f4ea32013-05-10 18:08:32 +0530168 def calculate_net_total(self):
Anand Doshif3096132013-05-21 19:35:06 +0530169 self.doc.net_total = self.doc.net_total_export = 0.0
Anand Doshi21f4ea32013-05-10 18:08:32 +0530170
171 for item in self.item_doclist:
172 self.doc.net_total += item.amount
173 self.doc.net_total_export += item.export_amount
Anand Doshif3096132013-05-21 19:35:06 +0530174
175 self.round_floats_in(self.doc, ["net_total", "net_total_export"])
Anand Doshi21f4ea32013-05-10 18:08:32 +0530176
177 def calculate_totals(self):
178 self.doc.grand_total = flt(self.tax_doclist and \
Anand Doshi5af812a2013-05-10 19:23:02 +0530179 self.tax_doclist[-1].total or self.doc.net_total, self.precision("grand_total"))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530180 self.doc.grand_total_export = flt(self.doc.grand_total / self.doc.conversion_rate,
Anand Doshi5af812a2013-05-10 19:23:02 +0530181 self.precision("grand_total_export"))
Anand Doshif3096132013-05-21 19:35:06 +0530182
183 self.doc.other_charges_total = flt(self.doc.grand_total - self.doc.net_total,
184 self.precision("other_charges_total"))
Nabin Hait5c6d13a2014-01-20 17:18:16 +0530185
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530186 self.doc.other_charges_total_export = flt(self.doc.grand_total_export -
Nabin Hait5c6d13a2014-01-20 17:18:16 +0530187 self.doc.net_total_export + flt(self.doc.discount_amount),
Anand Doshif3096132013-05-21 19:35:06 +0530188 self.precision("other_charges_total_export"))
Anand Doshi21f4ea32013-05-10 18:08:32 +0530189
Anand Doshi2e31e092013-08-19 19:58:23 +0530190 self.doc.rounded_total = _round(self.doc.grand_total)
191 self.doc.rounded_total_export = _round(self.doc.grand_total_export)
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530192
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530193 def apply_discount_amount(self):
194 if self.doc.discount_amount:
195 grand_total_for_discount_amount = self.get_grand_total_for_discount_amount()
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530196
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530197 if grand_total_for_discount_amount:
198 # calculate item amount after Discount Amount
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530199 for item in self.item_doclist:
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530200 distributed_amount = flt(self.doc.discount_amount) * item.amount / grand_total_for_discount_amount
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530201 item.amount = flt(item.amount - distributed_amount, self.precision("amount", item))
202
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530203 self.discount_amount_applied = True
204 self._calculate_taxes_and_totals()
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530205
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530206 def get_grand_total_for_discount_amount(self):
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530207 actual_taxes_dict = {}
208
209 for tax in self.tax_doclist:
210 if tax.charge_type == "Actual":
211 actual_taxes_dict.setdefault(tax.idx, tax.tax_amount)
212 elif tax.row_id in actual_taxes_dict:
213 actual_tax_amount = flt(actual_taxes_dict.get(tax.row_id, 0)) * \
214 flt(tax.rate) / 100
215 actual_taxes_dict.setdefault(tax.idx, actual_tax_amount)
216
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530217 grand_total_for_discount_amount = flt(self.doc.grand_total - sum(actual_taxes_dict.values()),
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530218 self.precision("grand_total"))
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530219 return grand_total_for_discount_amount
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530220
Anand Doshi923d41d2013-05-28 17:23:36 +0530221 def calculate_outstanding_amount(self):
222 # NOTE:
223 # write_off_amount is only for POS Invoice
224 # total_advance is only for non POS Invoice
225 if self.doc.doctype == "Sales Invoice" and self.doc.docstatus < 2:
226 self.round_floats_in(self.doc, ["grand_total", "total_advance", "write_off_amount",
227 "paid_amount"])
228 total_amount_to_pay = self.doc.grand_total - self.doc.write_off_amount
Rushabh Mehta54047782013-12-26 11:07:46 +0530229 self.doc.outstanding_amount = flt(total_amount_to_pay - self.doc.total_advance \
230 - self.doc.paid_amount, self.precision("outstanding_amount"))
Anand Doshi923d41d2013-05-28 17:23:36 +0530231
232 def calculate_commission(self):
233 if self.meta.get_field("commission_rate"):
234 self.round_floats_in(self.doc, ["net_total", "commission_rate"])
235 if self.doc.commission_rate > 100.0:
236 msgprint(_(self.meta.get_label("commission_rate")) + " " +
237 _("cannot be greater than 100"), raise_exception=True)
238
239 self.doc.total_commission = flt(self.doc.net_total * self.doc.commission_rate / 100.0,
240 self.precision("total_commission"))
Anand Doshif3096132013-05-21 19:35:06 +0530241
242 def calculate_contribution(self):
243 total = 0.0
244 sales_team = self.doclist.get({"parentfield": "sales_team"})
245 for sales_person in sales_team:
246 self.round_floats_in(sales_person)
247
248 sales_person.allocated_amount = flt(
249 self.doc.net_total * sales_person.allocated_percentage / 100.0,
250 self.precision("allocated_amount", sales_person))
251
252 total += sales_person.allocated_percentage
253
254 if sales_team and total != 100.0:
255 msgprint(_("Total") + " " +
256 _(self.meta.get_label("allocated_percentage", parentfield="sales_team")) +
257 " " + _("should be 100%"), raise_exception=True)
Anand Doshi1dde46a2013-05-15 21:15:57 +0530258
259 def validate_order_type(self):
Anand Doshiabc10032013-06-14 17:44:03 +0530260 valid_types = ["Sales", "Maintenance", "Shopping Cart"]
Rushabh Mehta080fcc82013-07-04 15:27:04 +0530261 if not self.doc.order_type:
262 self.doc.order_type = "Sales"
263 elif self.doc.order_type not in valid_types:
Anand Doshi1dde46a2013-05-15 21:15:57 +0530264 msgprint(_(self.meta.get_label("order_type")) + " " +
Anand Doshi373680b2013-10-10 16:04:40 +0530265 _("must be one of") + ": " + comma_or(valid_types), raise_exception=True)
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530266
267 def check_credit(self, grand_total):
268 customer_account = webnotes.conn.get_value("Account", {"company": self.doc.company,
269 "master_name": self.doc.customer}, "name")
270 if customer_account:
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530271 total_outstanding = webnotes.conn.sql("""select
272 sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
Anand Doshi0c26f812013-11-15 19:12:09 +0530273 from `tabGL Entry` where account = %s""", customer_account)
274 total_outstanding = total_outstanding[0][0] if total_outstanding else 0
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530275
276 outstanding_including_current = flt(total_outstanding) + flt(grand_total)
277 webnotes.bean('Account', customer_account).run_method("check_credit_limit",
Anand Doshi0c26f812013-11-15 19:12:09 +0530278 outstanding_including_current)
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530279
280 def validate_max_discount(self):
281 for d in self.doclist.get({"parentfield": self.fname}):
282 discount = flt(webnotes.conn.get_value("Item", d.item_code, "max_discount"))
283
284 if discount and flt(d.adj_rate) > discount:
285 webnotes.throw(_("You cannot give more than ") + cstr(discount) + "% " +
286 _("discount on Item Code") + ": " + cstr(d.item_code))
287
288 def get_item_list(self):
289 il = []
290 for d in self.doclist.get({"parentfield": self.fname}):
291 reserved_warehouse = ""
292 reserved_qty_for_main_item = 0
293
294 if self.doc.doctype == "Sales Order":
295 if (webnotes.conn.get_value("Item", d.item_code, "is_stock_item") == 'Yes' or
296 self.has_sales_bom(d.item_code)) and not d.reserved_warehouse:
297 webnotes.throw(_("Please enter Reserved Warehouse for item ") +
298 d.item_code + _(" as it is stock Item or packing item"))
299 reserved_warehouse = d.reserved_warehouse
300 if flt(d.qty) > flt(d.delivered_qty):
301 reserved_qty_for_main_item = flt(d.qty) - flt(d.delivered_qty)
302
303 if self.doc.doctype == "Delivery Note" and d.against_sales_order:
304 # if SO qty is 10 and there is tolerance of 20%, then it will allow DN of 12.
305 # But in this case reserved qty should only be reduced by 10 and not 12
306
307 already_delivered_qty = self.get_already_delivered_qty(self.doc.name,
308 d.against_sales_order, d.prevdoc_detail_docname)
309 so_qty, reserved_warehouse = self.get_so_qty_and_warehouse(d.prevdoc_detail_docname)
310
311 if already_delivered_qty + d.qty > so_qty:
312 reserved_qty_for_main_item = -(so_qty - already_delivered_qty)
313 else:
314 reserved_qty_for_main_item = -flt(d.qty)
315
316 if self.has_sales_bom(d.item_code):
317 for p in self.doclist.get({"parentfield": "packing_details"}):
318 if p.parent_detail_docname == d.name and p.parent_item == d.item_code:
319 # the packing details table's qty is already multiplied with parent's qty
320 il.append(webnotes._dict({
321 'warehouse': p.warehouse,
322 'reserved_warehouse': reserved_warehouse,
323 'item_code': p.item_code,
324 'qty': flt(p.qty),
325 'reserved_qty': (flt(p.qty)/flt(d.qty)) * reserved_qty_for_main_item,
326 'uom': p.uom,
327 'batch_no': cstr(p.batch_no).strip(),
328 'serial_no': cstr(p.serial_no).strip(),
329 'name': d.name
330 }))
331 else:
332 il.append(webnotes._dict({
333 'warehouse': d.warehouse,
334 'reserved_warehouse': reserved_warehouse,
335 'item_code': d.item_code,
336 'qty': d.qty,
337 'reserved_qty': reserved_qty_for_main_item,
338 'uom': d.stock_uom,
339 'batch_no': cstr(d.batch_no).strip(),
340 'serial_no': cstr(d.serial_no).strip(),
341 'name': d.name
342 }))
343 return il
344
345 def has_sales_bom(self, item_code):
346 return webnotes.conn.sql("""select name from `tabSales BOM`
347 where new_item_code=%s and docstatus != 2""", item_code)
348
349 def get_already_delivered_qty(self, dn, so, so_detail):
350 qty = webnotes.conn.sql("""select sum(qty) from `tabDelivery Note Item`
351 where prevdoc_detail_docname = %s and docstatus = 1
352 and against_sales_order = %s
353 and parent != %s""", (so_detail, so, dn))
354 return qty and flt(qty[0][0]) or 0.0
355
356 def get_so_qty_and_warehouse(self, so_detail):
357 so_item = webnotes.conn.sql("""select qty, reserved_warehouse from `tabSales Order Item`
358 where name = %s and docstatus = 1""", so_detail, as_dict=1)
359 so_qty = so_item and flt(so_item[0]["qty"]) or 0.0
360 so_warehouse = so_item and so_item[0]["reserved_warehouse"] or ""
361 return so_qty, so_warehouse
362
363 def check_stop_sales_order(self, ref_fieldname):
364 for d in self.doclist.get({"parentfield": self.fname}):
365 if d.fields.get(ref_fieldname):
366 status = webnotes.conn.get_value("Sales Order", d.fields[ref_fieldname], "status")
367 if status == "Stopped":
368 webnotes.throw(self.doc.doctype +
369 _(" can not be created/modified against stopped Sales Order ") +
370 d.fields[ref_fieldname])
371
372def check_active_sales_items(obj):
373 for d in obj.doclist.get({"parentfield": obj.fname}):
374 if d.item_code:
375 item = webnotes.conn.sql("""select docstatus, is_sales_item,
376 is_service_item, default_income_account from tabItem where name = %s""",
377 d.item_code, as_dict=True)[0]
378 if item.is_sales_item == 'No' and item.is_service_item == 'No':
379 webnotes.throw(_("Item is neither Sales nor Service Item") + ": " + d.item_code)
380 if d.income_account and not item.default_income_account:
381 webnotes.conn.set_value("Item", d.item_code, "default_income_account",
Nabin Hait89ad6f22013-10-18 12:55:59 +0530382 d.income_account)