blob: 86d883784bad42c692d72d661526521ada6b30d9 [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
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
Anand Doshi62b1cbf2014-07-25 12:50:00 +05306from frappe.utils import cint, flt, rounded, cstr, comma_or
Rushabh Mehta1f847992013-12-12 19:12:19 +05307from erpnext.setup.utils import get_company_currency
Rushabh Mehta9f0d6252014-04-14 19:20:45 +05308from frappe import _, throw
Rushabh Mehtab5e76892014-07-29 16:07:43 +05309from erpnext.stock.get_item_details import get_available_qty
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):
Rushabh Mehtaf84c2402014-07-18 16:39:31 +053014 def __setup__(self):
Rushabh Mehta5b51cc82014-07-21 18:25:45 +053015 if hasattr(self, "fname"):
16 self.table_print_templates = {
17 self.fname: "templates/print_formats/includes/item_grid.html",
18 "other_charges": "templates/print_formats/includes/taxes.html",
19 }
Rushabh Mehtaf84c2402014-07-18 16:39:31 +053020
Rushabh Mehtab5e76892014-07-29 16:07:43 +053021 def onload(self):
22 if self.doctype in ("Sales Order", "Delivery Note", "Sales Invoice"):
23 for item in self.get(self.fname):
24 item.update(get_available_qty(item.item_code,
25 item.warehouse))
26
Nabin Haitd1fd1e22013-10-18 12:29:11 +053027 def validate(self):
28 super(SellingController, self).validate()
29 self.validate_max_discount()
30 check_active_sales_items(self)
Anand Doshid2946502014-04-08 20:10:03 +053031
Rushabh Mehta800b3aa2013-10-03 17:26:33 +053032 def get_sender(self, comm):
Anand Doshi4aa23802014-06-30 12:10:57 +053033 sender = None
34 if cint(frappe.db.get_value('Sales Email Settings', None, 'extract_emails')):
35 sender = frappe.db.get_value('Sales Email Settings', None, 'email_id')
36
37 return sender or comm.sender or frappe.session.user
Anand Doshid2946502014-04-08 20:10:03 +053038
Anand Doshif3096132013-05-21 19:35:06 +053039 def set_missing_values(self, for_validate=False):
Anand Doshiabc10032013-06-14 17:44:03 +053040 super(SellingController, self).set_missing_values(for_validate)
Anand Doshid2946502014-04-08 20:10:03 +053041
Anand Doshif3096132013-05-21 19:35:06 +053042 # set contact and address details for customer, if they are not mentioned
Anand Doshiabc10032013-06-14 17:44:03 +053043 self.set_missing_lead_customer_details()
Nabin Hait096d3632013-10-17 17:01:14 +053044 self.set_price_list_and_item_details()
Anand Doshif78d1ae2014-03-28 13:55:00 +053045 if self.get("__islocal"):
Akhilesh Darjee2ced3b02014-01-28 19:16:05 +053046 self.set_taxes("other_charges", "taxes_and_charges")
Anand Doshid2946502014-04-08 20:10:03 +053047
Anand Doshiabc10032013-06-14 17:44:03 +053048 def set_missing_lead_customer_details(self):
Rushabh Mehtaf14b8092014-04-03 14:30:42 +053049 if getattr(self, "customer", None):
Anand Doshi43624432014-02-25 15:42:16 +053050 from erpnext.accounts.party import _get_party_details
Nabin Hait6b039142014-05-02 15:45:10 +053051 party_details = _get_party_details(self.customer,
52 ignore_permissions=getattr(self, "ignore_permissions", None))
53 if not self.meta.get_field("sales_team"):
54 party_details.pop("sales_team")
55
56 self.update_if_missing(party_details)
Anand Doshid2946502014-04-08 20:10:03 +053057
Rushabh Mehtaf14b8092014-04-03 14:30:42 +053058 elif getattr(self, "lead", None):
Nabin Hait9d1f0772014-02-19 17:43:24 +053059 from erpnext.selling.doctype.lead.lead import get_lead_details
Anand Doshif78d1ae2014-03-28 13:55:00 +053060 self.update_if_missing(get_lead_details(self.lead))
Anand Doshid2946502014-04-08 20:10:03 +053061
Nabin Hait096d3632013-10-17 17:01:14 +053062 def set_price_list_and_item_details(self):
63 self.set_price_list_currency("Selling")
Nabin Hait0aa71a52014-02-11 16:14:52 +053064 self.set_missing_item_details()
Anand Doshid2946502014-04-08 20:10:03 +053065
Anand Doshi99100a42013-07-04 17:13:53 +053066 def apply_shipping_rule(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +053067 if self.shipping_rule:
Rushabh Mehtab385ecf2014-03-28 16:44:37 +053068 shipping_rule = frappe.get_doc("Shipping Rule", self.shipping_rule)
Anand Doshif78d1ae2014-03-28 13:55:00 +053069 value = self.net_total
Anand Doshid2946502014-04-08 20:10:03 +053070
Anand Doshi99100a42013-07-04 17:13:53 +053071 # TODO
72 # shipping rule calculation based on item's net weight
Anand Doshid2946502014-04-08 20:10:03 +053073
Anand Doshi99100a42013-07-04 17:13:53 +053074 shipping_amount = 0.0
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +053075 for condition in shipping_rule.get("shipping_rule_conditions"):
Anand Doshi99100a42013-07-04 17:13:53 +053076 if not condition.to_value or (flt(condition.from_value) <= value <= flt(condition.to_value)):
77 shipping_amount = condition.shipping_amount
78 break
Anand Doshid2946502014-04-08 20:10:03 +053079
Anand Doshiac32bad2014-04-18 01:30:14 +053080 shipping_charge = {
Anand Doshi0b4943c2013-07-04 23:45:22 +053081 "doctype": "Sales Taxes and Charges",
Anand Doshi0b4943c2013-07-04 23:45:22 +053082 "charge_type": "Actual",
Anand Doshif78d1ae2014-03-28 13:55:00 +053083 "account_head": shipping_rule.account,
Anand Doshiac32bad2014-04-18 01:30:14 +053084 "cost_center": shipping_rule.cost_center
85 }
86
87 existing_shipping_charge = self.get("other_charges", filters=shipping_charge)
88 if existing_shipping_charge:
89 # take the last record found
90 existing_shipping_charge[-1].rate = shipping_amount
91 else:
92 shipping_charge["rate"] = shipping_amount
93 shipping_charge["description"] = shipping_rule.label
94 self.append("other_charges", shipping_charge)
95
96 self.calculate_taxes_and_totals()
97
98 def remove_shipping_charge(self):
99 if self.shipping_rule:
100 shipping_rule = frappe.get_doc("Shipping Rule", self.shipping_rule)
101 existing_shipping_charge = self.get("other_charges", {
102 "doctype": "Sales Taxes and Charges",
103 "charge_type": "Actual",
104 "account_head": shipping_rule.account,
105 "cost_center": shipping_rule.cost_center
Anand Doshi0b4943c2013-07-04 23:45:22 +0530106 })
Anand Doshiac32bad2014-04-18 01:30:14 +0530107 if existing_shipping_charge:
108 self.get("other_charges").remove(existing_shipping_charge[-1])
109 self.calculate_taxes_and_totals()
Anand Doshid2946502014-04-08 20:10:03 +0530110
Nabin Haitec52db82013-01-22 11:53:14 +0530111 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530112 from frappe.utils import money_in_words
Anand Doshif78d1ae2014-03-28 13:55:00 +0530113 company_currency = get_company_currency(self.company)
Anand Doshid2946502014-04-08 20:10:03 +0530114
115 disable_rounded_total = cint(frappe.db.get_value("Global Defaults", None,
Nabin Hait6f1a5ec2013-02-20 16:25:05 +0530116 "disable_rounded_total"))
Anand Doshid2946502014-04-08 20:10:03 +0530117
Nabin Haitec52db82013-01-22 11:53:14 +0530118 if self.meta.get_field("in_words"):
Anand Doshid2946502014-04-08 20:10:03 +0530119 self.in_words = money_in_words(disable_rounded_total and
Anand Doshif78d1ae2014-03-28 13:55:00 +0530120 self.grand_total or self.rounded_total, company_currency)
Nabin Haitec52db82013-01-22 11:53:14 +0530121 if self.meta.get_field("in_words_export"):
Anand Doshid2946502014-04-08 20:10:03 +0530122 self.in_words_export = money_in_words(disable_rounded_total and
Anand Doshif78d1ae2014-03-28 13:55:00 +0530123 self.grand_total_export or self.rounded_total_export, self.currency)
Anand Doshid2946502014-04-08 20:10:03 +0530124
Anand Doshi21f4ea32013-05-10 18:08:32 +0530125 def calculate_taxes_and_totals(self):
Anand Doshi3543f302013-05-24 19:25:01 +0530126 self.other_fname = "other_charges"
Anand Doshid2946502014-04-08 20:10:03 +0530127
Anand Doshi3543f302013-05-24 19:25:01 +0530128 super(SellingController, self).calculate_taxes_and_totals()
Anand Doshid2946502014-04-08 20:10:03 +0530129
Anand Doshi923d41d2013-05-28 17:23:36 +0530130 self.calculate_total_advance("Sales Invoice", "advance_adjustment_details")
Anand Doshif3096132013-05-21 19:35:06 +0530131 self.calculate_commission()
132 self.calculate_contribution()
Anand Doshid2946502014-04-08 20:10:03 +0530133
Anand Doshif3096132013-05-21 19:35:06 +0530134 def determine_exclusive_rate(self):
Anand Doshi21f4ea32013-05-10 18:08:32 +0530135 if not any((cint(tax.included_in_print_rate) for tax in self.tax_doclist)):
136 # no inclusive tax
137 return
Anand Doshid2946502014-04-08 20:10:03 +0530138
Anand Doshi21f4ea32013-05-10 18:08:32 +0530139 for item in self.item_doclist:
140 item_tax_map = self._load_item_tax_rate(item.item_tax_rate)
141 cumulated_tax_fraction = 0
142 for i, tax in enumerate(self.tax_doclist):
Anand Doshif3096132013-05-21 19:35:06 +0530143 tax.tax_fraction_for_current_item = self.get_current_tax_fraction(tax, item_tax_map)
Anand Doshid2946502014-04-08 20:10:03 +0530144
Anand Doshi21f4ea32013-05-10 18:08:32 +0530145 if i==0:
Anand Doshif3096132013-05-21 19:35:06 +0530146 tax.grand_total_fraction_for_current_item = 1 + tax.tax_fraction_for_current_item
Anand Doshi21f4ea32013-05-10 18:08:32 +0530147 else:
148 tax.grand_total_fraction_for_current_item = \
149 self.tax_doclist[i-1].grand_total_fraction_for_current_item \
150 + tax.tax_fraction_for_current_item
Anand Doshid2946502014-04-08 20:10:03 +0530151
Anand Doshi21f4ea32013-05-10 18:08:32 +0530152 cumulated_tax_fraction += tax.tax_fraction_for_current_item
Anand Doshid2946502014-04-08 20:10:03 +0530153
Nabin Haitc41a9482014-08-18 15:40:15 +0530154 if cumulated_tax_fraction and not self.discount_amount_applied and item.qty:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530155 item.base_amount = flt((item.amount * self.conversion_rate) /
Nabin Hait1eb56012014-02-10 19:20:15 +0530156 (1 + cumulated_tax_fraction), self.precision("base_amount", item))
Anand Doshid2946502014-04-08 20:10:03 +0530157
Nabin Hait1eb56012014-02-10 19:20:15 +0530158 item.base_rate = flt(item.base_amount / item.qty, self.precision("base_rate", item))
Anand Doshi8f49cf72014-07-25 13:01:00 +0530159 item.discount_percentage = flt(item.discount_percentage, self.precision("discount_percentage", item))
Anand Doshid2946502014-04-08 20:10:03 +0530160
Nabin Haita7f757a2014-02-10 17:54:04 +0530161 if item.discount_percentage == 100:
Nabin Hait7979f7e2014-02-10 18:26:49 +0530162 item.base_price_list_rate = item.base_rate
163 item.base_rate = 0.0
Anand Doshif3096132013-05-21 19:35:06 +0530164 else:
Nabin Hait7979f7e2014-02-10 18:26:49 +0530165 item.base_price_list_rate = flt(item.base_rate / (1 - (item.discount_percentage / 100.0)),
Nabin Haita7f757a2014-02-10 17:54:04 +0530166 self.precision("base_price_list_rate", item))
Anand Doshid2946502014-04-08 20:10:03 +0530167
Anand Doshi21f4ea32013-05-10 18:08:32 +0530168 def get_current_tax_fraction(self, tax, item_tax_map):
169 """
170 Get tax fraction for calculating tax exclusive amount
171 from tax inclusive amount
172 """
173 current_tax_fraction = 0
Anand Doshid2946502014-04-08 20:10:03 +0530174
Anand Doshi21f4ea32013-05-10 18:08:32 +0530175 if cint(tax.included_in_print_rate):
176 tax_rate = self._get_tax_rate(tax, item_tax_map)
Anand Doshid2946502014-04-08 20:10:03 +0530177
Anand Doshi21f4ea32013-05-10 18:08:32 +0530178 if tax.charge_type == "On Net Total":
179 current_tax_fraction = tax_rate / 100.0
Anand Doshid2946502014-04-08 20:10:03 +0530180
Anand Doshi21f4ea32013-05-10 18:08:32 +0530181 elif tax.charge_type == "On Previous Row Amount":
182 current_tax_fraction = (tax_rate / 100.0) * \
183 self.tax_doclist[cint(tax.row_id) - 1].tax_fraction_for_current_item
Anand Doshid2946502014-04-08 20:10:03 +0530184
Anand Doshi21f4ea32013-05-10 18:08:32 +0530185 elif tax.charge_type == "On Previous Row Total":
186 current_tax_fraction = (tax_rate / 100.0) * \
187 self.tax_doclist[cint(tax.row_id) - 1].grand_total_fraction_for_current_item
Anand Doshid2946502014-04-08 20:10:03 +0530188
Anand Doshi21f4ea32013-05-10 18:08:32 +0530189 return current_tax_fraction
Anand Doshid2946502014-04-08 20:10:03 +0530190
Anand Doshi21f4ea32013-05-10 18:08:32 +0530191 def calculate_item_values(self):
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530192 if not self.discount_amount_applied:
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530193 for item in self.item_doclist:
194 self.round_floats_in(item)
Rushabh Mehta4dca4012013-07-25 17:45:59 +0530195
Nabin Haita7f757a2014-02-10 17:54:04 +0530196 if item.discount_percentage == 100:
Nabin Hait7979f7e2014-02-10 18:26:49 +0530197 item.rate = 0
198 elif not item.rate:
199 item.rate = flt(item.price_list_rate * (1.0 - (item.discount_percentage / 100.0)),
200 self.precision("rate", item))
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530201
Nabin Hait1eb56012014-02-10 19:20:15 +0530202 item.amount = flt(item.rate * item.qty,
203 self.precision("amount", item))
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530204
Nabin Haita7f757a2014-02-10 17:54:04 +0530205 self._set_in_company_currency(item, "price_list_rate", "base_price_list_rate")
Nabin Hait7979f7e2014-02-10 18:26:49 +0530206 self._set_in_company_currency(item, "rate", "base_rate")
Nabin Hait1eb56012014-02-10 19:20:15 +0530207 self._set_in_company_currency(item, "amount", "base_amount")
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530208
Anand Doshi21f4ea32013-05-10 18:08:32 +0530209 def calculate_net_total(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530210 self.net_total = self.net_total_export = 0.0
Anand Doshi21f4ea32013-05-10 18:08:32 +0530211
212 for item in self.item_doclist:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530213 self.net_total += item.base_amount
214 self.net_total_export += item.amount
Anand Doshid2946502014-04-08 20:10:03 +0530215
Anand Doshi81ba0b22014-03-28 15:23:26 +0530216 self.round_floats_in(self, ["net_total", "net_total_export"])
Anand Doshid2946502014-04-08 20:10:03 +0530217
Anand Doshi21f4ea32013-05-10 18:08:32 +0530218 def calculate_totals(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530219 self.grand_total = flt(self.tax_doclist and \
220 self.tax_doclist[-1].total or self.net_total, self.precision("grand_total"))
Anand Doshid2946502014-04-08 20:10:03 +0530221 self.grand_total_export = flt(self.grand_total / self.conversion_rate,
Anand Doshi5af812a2013-05-10 19:23:02 +0530222 self.precision("grand_total_export"))
Anand Doshid2946502014-04-08 20:10:03 +0530223
Anand Doshif78d1ae2014-03-28 13:55:00 +0530224 self.other_charges_total = flt(self.grand_total - self.net_total,
Anand Doshif3096132013-05-21 19:35:06 +0530225 self.precision("other_charges_total"))
Nabin Hait5c6d13a2014-01-20 17:18:16 +0530226
Anand Doshid2946502014-04-08 20:10:03 +0530227 self.other_charges_total_export = flt(self.grand_total_export -
228 self.net_total_export + flt(self.discount_amount),
Anand Doshif3096132013-05-21 19:35:06 +0530229 self.precision("other_charges_total_export"))
Anand Doshid2946502014-04-08 20:10:03 +0530230
Anand Doshi62b1cbf2014-07-25 12:50:00 +0530231 self.rounded_total = rounded(self.grand_total)
232 self.rounded_total_export = rounded(self.grand_total_export)
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530233
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530234 def apply_discount_amount(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530235 if self.discount_amount:
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530236 grand_total_for_discount_amount = self.get_grand_total_for_discount_amount()
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530237
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530238 if grand_total_for_discount_amount:
239 # calculate item amount after Discount Amount
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530240 for item in self.item_doclist:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530241 distributed_amount = flt(self.discount_amount) * item.base_amount / grand_total_for_discount_amount
Nabin Hait1eb56012014-02-10 19:20:15 +0530242 item.base_amount = flt(item.base_amount - distributed_amount, self.precision("base_amount", item))
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530243
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530244 self.discount_amount_applied = True
245 self._calculate_taxes_and_totals()
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530246
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530247 def get_grand_total_for_discount_amount(self):
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530248 actual_taxes_dict = {}
249
250 for tax in self.tax_doclist:
251 if tax.charge_type == "Actual":
252 actual_taxes_dict.setdefault(tax.idx, tax.tax_amount)
253 elif tax.row_id in actual_taxes_dict:
254 actual_tax_amount = flt(actual_taxes_dict.get(tax.row_id, 0)) * \
255 flt(tax.rate) / 100
256 actual_taxes_dict.setdefault(tax.idx, actual_tax_amount)
257
Anand Doshid2946502014-04-08 20:10:03 +0530258 grand_total_for_discount_amount = flt(self.grand_total - sum(actual_taxes_dict.values()),
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530259 self.precision("grand_total"))
Akhilesh Darjee57738a02014-01-03 18:15:07 +0530260 return grand_total_for_discount_amount
Akhilesh Darjeed203aea2013-12-27 17:49:57 +0530261
Anand Doshi923d41d2013-05-28 17:23:36 +0530262 def calculate_outstanding_amount(self):
Anand Doshid2946502014-04-08 20:10:03 +0530263 # NOTE:
Anand Doshi923d41d2013-05-28 17:23:36 +0530264 # write_off_amount is only for POS Invoice
265 # total_advance is only for non POS Invoice
Anand Doshif78d1ae2014-03-28 13:55:00 +0530266 if self.doctype == "Sales Invoice" and self.docstatus == 0:
Anand Doshi81ba0b22014-03-28 15:23:26 +0530267 self.round_floats_in(self, ["grand_total", "total_advance", "write_off_amount",
Anand Doshi923d41d2013-05-28 17:23:36 +0530268 "paid_amount"])
Anand Doshif78d1ae2014-03-28 13:55:00 +0530269 total_amount_to_pay = self.grand_total - self.write_off_amount
270 self.outstanding_amount = flt(total_amount_to_pay - self.total_advance \
271 - self.paid_amount, self.precision("outstanding_amount"))
Anand Doshid2946502014-04-08 20:10:03 +0530272
Anand Doshi923d41d2013-05-28 17:23:36 +0530273 def calculate_commission(self):
274 if self.meta.get_field("commission_rate"):
Anand Doshi81ba0b22014-03-28 15:23:26 +0530275 self.round_floats_in(self, ["net_total", "commission_rate"])
Anand Doshif78d1ae2014-03-28 13:55:00 +0530276 if self.commission_rate > 100.0:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530277 throw(_("Commission rate cannot be greater than 100"))
Anand Doshid2946502014-04-08 20:10:03 +0530278
Anand Doshif78d1ae2014-03-28 13:55:00 +0530279 self.total_commission = flt(self.net_total * self.commission_rate / 100.0,
Anand Doshi923d41d2013-05-28 17:23:36 +0530280 self.precision("total_commission"))
Anand Doshif3096132013-05-21 19:35:06 +0530281
282 def calculate_contribution(self):
Anand Doshiac32bad2014-04-18 01:30:14 +0530283 if not self.meta.get_field("sales_team"):
284 return
285
Anand Doshif3096132013-05-21 19:35:06 +0530286 total = 0.0
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530287 sales_team = self.get("sales_team")
Anand Doshif3096132013-05-21 19:35:06 +0530288 for sales_person in sales_team:
289 self.round_floats_in(sales_person)
290
291 sales_person.allocated_amount = flt(
Anand Doshif78d1ae2014-03-28 13:55:00 +0530292 self.net_total * sales_person.allocated_percentage / 100.0,
Anand Doshif3096132013-05-21 19:35:06 +0530293 self.precision("allocated_amount", sales_person))
Anand Doshid2946502014-04-08 20:10:03 +0530294
Anand Doshif3096132013-05-21 19:35:06 +0530295 total += sales_person.allocated_percentage
Anand Doshid2946502014-04-08 20:10:03 +0530296
Anand Doshif3096132013-05-21 19:35:06 +0530297 if sales_team and total != 100.0:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530298 throw(_("Total allocated percentage for sales team should be 100"))
Anand Doshid2946502014-04-08 20:10:03 +0530299
Anand Doshi1dde46a2013-05-15 21:15:57 +0530300 def validate_order_type(self):
Anand Doshiabc10032013-06-14 17:44:03 +0530301 valid_types = ["Sales", "Maintenance", "Shopping Cart"]
Anand Doshif78d1ae2014-03-28 13:55:00 +0530302 if not self.order_type:
303 self.order_type = "Sales"
304 elif self.order_type not in valid_types:
Anand Doshi80a988c2014-07-07 11:35:54 +0530305 throw(_("Order Type must be one of {0}").format(comma_or(valid_types)))
Anand Doshid2946502014-04-08 20:10:03 +0530306
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530307 def check_credit(self, grand_total):
Anand Doshid2946502014-04-08 20:10:03 +0530308 customer_account = frappe.db.get_value("Account", {"company": self.company,
Anand Doshif78d1ae2014-03-28 13:55:00 +0530309 "master_name": self.customer}, "name")
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530310 if customer_account:
Nabin Haitc41a9482014-08-18 15:40:15 +0530311 invoice_outstanding = frappe.db.sql("""select
Anand Doshid2946502014-04-08 20:10:03 +0530312 sum(ifnull(debit, 0)) - sum(ifnull(credit, 0))
Anand Doshi0c26f812013-11-15 19:12:09 +0530313 from `tabGL Entry` where account = %s""", customer_account)
Nabin Haitc41a9482014-08-18 15:40:15 +0530314 invoice_outstanding = flt(invoice_outstanding[0][0]) if invoice_outstanding else 0
Anand Doshid2946502014-04-08 20:10:03 +0530315
Nabin Haitc41a9482014-08-18 15:40:15 +0530316 ordered_amount_to_be_billed = frappe.db.sql("""
317 select sum(grand_total*(100 - ifnull(per_billed, 0))/100)
318 from `tabSales Order`
319 where customer=%s and docstatus = 1
320 and ifnull(per_billed, 0) < 100 and status != 'Stopped'""", self.customer)
321
322 ordered_amount_to_be_billed = flt(ordered_amount_to_be_billed[0][0]) \
323 if ordered_amount_to_be_billed else 0.0
324
325 total_outstanding = invoice_outstanding + ordered_amount_to_be_billed
326
327 frappe.get_doc('Account', customer_account).check_credit_limit(total_outstanding)
Anand Doshid2946502014-04-08 20:10:03 +0530328
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530329 def validate_max_discount(self):
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530330 for d in self.get(self.fname):
Anand Doshie9baaa62014-02-26 12:35:33 +0530331 discount = flt(frappe.db.get_value("Item", d.item_code, "max_discount"))
Anand Doshid2946502014-04-08 20:10:03 +0530332
Nabin Haita7f757a2014-02-10 17:54:04 +0530333 if discount and flt(d.discount_percentage) > discount:
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530334 frappe.throw(_("Maxiumm discount for Item {0} is {1}%").format(d.item_code, discount))
Anand Doshid2946502014-04-08 20:10:03 +0530335
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530336 def get_item_list(self):
337 il = []
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530338 for d in self.get(self.fname):
Nabin Hait0aa71a52014-02-11 16:14:52 +0530339 reserved_warehouse = ""
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530340 reserved_qty_for_main_item = 0
Anand Doshid2946502014-04-08 20:10:03 +0530341
nathando247e9ff2014-09-03 15:03:31 +0800342 if d.qty is None:
Nabin Haitc41a9482014-08-18 15:40:15 +0530343 frappe.throw(_("Row {0}: Qty is mandatory").format(d.idx))
344
Anand Doshif78d1ae2014-03-28 13:55:00 +0530345 if self.doctype == "Sales Order":
Anand Doshid2946502014-04-08 20:10:03 +0530346 if (frappe.db.get_value("Item", d.item_code, "is_stock_item") == 'Yes' or
Nabin Haita7f757a2014-02-10 17:54:04 +0530347 self.has_sales_bom(d.item_code)) and not d.warehouse:
Nabin Hait2cebf9b2014-05-02 16:12:07 +0530348 frappe.throw(_("Reserved Warehouse required for stock Item {0} in row {1}").format(d.item_code, d.idx))
Nabin Hait0aa71a52014-02-11 16:14:52 +0530349 reserved_warehouse = d.warehouse
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530350 if flt(d.qty) > flt(d.delivered_qty):
351 reserved_qty_for_main_item = flt(d.qty) - flt(d.delivered_qty)
Anand Doshid2946502014-04-08 20:10:03 +0530352
353 elif self.doctype == "Delivery Note" and d.against_sales_order:
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530354 # if SO qty is 10 and there is tolerance of 20%, then it will allow DN of 12.
355 # But in this case reserved qty should only be reduced by 10 and not 12
Anand Doshid2946502014-04-08 20:10:03 +0530356
357 already_delivered_qty = self.get_already_delivered_qty(self.name,
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530358 d.against_sales_order, d.prevdoc_detail_docname)
Nabin Hait0aa71a52014-02-11 16:14:52 +0530359 so_qty, reserved_warehouse = self.get_so_qty_and_warehouse(d.prevdoc_detail_docname)
Anand Doshid2946502014-04-08 20:10:03 +0530360
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530361 if already_delivered_qty + d.qty > so_qty:
362 reserved_qty_for_main_item = -(so_qty - already_delivered_qty)
363 else:
364 reserved_qty_for_main_item = -flt(d.qty)
365
366 if self.has_sales_bom(d.item_code):
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530367 for p in self.get("packing_details"):
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530368 if p.parent_detail_docname == d.name and p.parent_item == d.item_code:
369 # the packing details table's qty is already multiplied with parent's qty
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530370 il.append(frappe._dict({
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530371 'warehouse': p.warehouse,
Nabin Hait0aa71a52014-02-11 16:14:52 +0530372 'reserved_warehouse': reserved_warehouse,
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530373 'item_code': p.item_code,
374 'qty': flt(p.qty),
375 'reserved_qty': (flt(p.qty)/flt(d.qty)) * reserved_qty_for_main_item,
376 'uom': p.uom,
377 'batch_no': cstr(p.batch_no).strip(),
378 'serial_no': cstr(p.serial_no).strip(),
379 'name': d.name
380 }))
381 else:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530382 il.append(frappe._dict({
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530383 'warehouse': d.warehouse,
Nabin Hait0aa71a52014-02-11 16:14:52 +0530384 'reserved_warehouse': reserved_warehouse,
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530385 'item_code': d.item_code,
386 'qty': d.qty,
387 'reserved_qty': reserved_qty_for_main_item,
388 'uom': d.stock_uom,
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530389 'batch_no': cstr(d.get("batch_no")).strip(),
390 'serial_no': cstr(d.get("serial_no")).strip(),
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530391 'name': d.name
392 }))
393 return il
Anand Doshid2946502014-04-08 20:10:03 +0530394
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530395 def has_sales_bom(self, item_code):
Anand Doshid2946502014-04-08 20:10:03 +0530396 return frappe.db.sql("""select name from `tabSales BOM`
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530397 where new_item_code=%s and docstatus != 2""", item_code)
Anand Doshid2946502014-04-08 20:10:03 +0530398
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530399 def get_already_delivered_qty(self, dn, so, so_detail):
Anand Doshid2946502014-04-08 20:10:03 +0530400 qty = frappe.db.sql("""select sum(qty) from `tabDelivery Note Item`
401 where prevdoc_detail_docname = %s and docstatus = 1
402 and against_sales_order = %s
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530403 and parent != %s""", (so_detail, so, dn))
404 return qty and flt(qty[0][0]) or 0.0
405
406 def get_so_qty_and_warehouse(self, so_detail):
Anand Doshie9baaa62014-02-26 12:35:33 +0530407 so_item = frappe.db.sql("""select qty, warehouse from `tabSales Order Item`
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530408 where name = %s and docstatus = 1""", so_detail, as_dict=1)
409 so_qty = so_item and flt(so_item[0]["qty"]) or 0.0
Nabin Haita7f757a2014-02-10 17:54:04 +0530410 so_warehouse = so_item and so_item[0]["warehouse"] or ""
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530411 return so_qty, so_warehouse
Anand Doshid2946502014-04-08 20:10:03 +0530412
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530413 def check_stop_sales_order(self, ref_fieldname):
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530414 for d in self.get(self.fname):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530415 if d.get(ref_fieldname):
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530416 status = frappe.db.get_value("Sales Order", d.get(ref_fieldname), "status")
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530417 if status == "Stopped":
Rushabh Mehta8a40c132014-04-15 16:30:55 +0530418 frappe.throw(_("Sales Order {0} is stopped").format(d.get(ref_fieldname)))
Anand Doshid2946502014-04-08 20:10:03 +0530419
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530420def check_active_sales_items(obj):
Rushabh Mehtad36cb5c2014-04-03 12:38:42 +0530421 for d in obj.get(obj.fname):
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530422 if d.item_code:
Anand Doshid2946502014-04-08 20:10:03 +0530423 item = frappe.db.sql("""select docstatus, is_sales_item,
424 is_service_item, income_account from tabItem where name = %s""",
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530425 d.item_code, as_dict=True)[0]
426 if item.is_sales_item == 'No' and item.is_service_item == 'No':
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530427 frappe.throw(_("Item {0} must be Sales or Service Item in {1}").format(d.item_code, d.idx))
Nabin Hait365ae272014-04-03 17:38:54 +0530428 if getattr(d, "income_account", None) and not item.income_account:
Anand Doshid2946502014-04-08 20:10:03 +0530429 frappe.db.set_value("Item", d.item_code, "income_account",
Nabin Hait89ad6f22013-10-18 12:55:59 +0530430 d.income_account)