blob: 8b4d28bc7ddda52e9aa08018ae345fd4aa307036 [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe 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
Nabin Haitec52db82013-01-22 11:53:14 +05304
Chillar Anand915b3432021-09-02 16:44:59 +05305import frappe
6from frappe import _, bold, throw
7from frappe.contacts.doctype.address.address import get_address_display
8from frappe.utils import cint, cstr, flt, get_link_to_form, nowtime
9
10from erpnext.controllers.accounts_controller import get_taxes_and_charges
Nabin Haita77b8c92020-12-21 14:45:50 +053011from erpnext.controllers.sales_and_purchase_return import get_rate_for_return
Chillar Anand915b3432021-09-02 16:44:59 +053012from erpnext.controllers.stock_controller import StockController
13from erpnext.stock.doctype.item.item import set_item_default
14from erpnext.stock.get_item_details import get_bin_details, get_conversion_factor
15from erpnext.stock.utils import get_incoming_rate
16
Nabin Haitbf495c92013-01-30 12:49:08 +053017
Nabin Haitc3afb252013-03-19 12:01:24 +053018class SellingController(StockController):
Nabin Hait993c6c02022-04-12 12:24:47 +053019 def __setup__(self):
20 self.flags.ignore_permlevel_for_fields = ["selling_price_list", "price_list_currency"]
21
Rushabh Mehtab5e76892014-07-29 16:07:43 +053022 def onload(self):
Rohit Waghchaure7d529892016-10-06 14:35:04 +053023 super(SellingController, self).onload()
Rushabh Mehtab5e76892014-07-29 16:07:43 +053024 if self.doctype in ("Sales Order", "Delivery Note", "Sales Invoice"):
Rohit Waghchaure02566a02023-01-20 22:38:56 +053025 for item in self.get("items") + (self.get("packed_items") or []):
s-aga-rc716dcc2022-12-29 12:34:18 +053026 item.update(get_bin_details(item.item_code, item.warehouse, include_child_warehouses=True))
Rushabh Mehtab5e76892014-07-29 16:07:43 +053027
Nabin Haitd1fd1e22013-10-18 12:29:11 +053028 def validate(self):
29 super(SellingController, self).validate()
Zarrarfc03a042018-06-04 12:52:52 +053030 self.validate_items()
Nabin Haitd1fd1e22013-10-18 12:29:11 +053031 self.validate_max_discount()
shreyas1cfe2d72016-10-19 18:36:12 +053032 self.validate_selling_price()
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +053033 self.set_qty_as_per_stock_uom()
Afshan01eca122020-12-08 09:27:56 +053034 self.set_po_nos(for_validate=True)
Saif Ur Rehman5fdbc682018-11-26 19:32:16 +050035 self.set_gross_profit()
Rushabh Mehta708e47a2018-08-08 16:37:31 +053036 set_default_income_account_for_item(self)
Rohit Waghchauref4dc7162018-11-15 17:04:02 +053037 self.set_customer_address()
Deepesh Gargf3d78dd2019-08-23 11:42:35 +053038 self.validate_for_duplicate_items()
rohitwaghchaure6fa6caf2020-04-23 09:46:29 +053039 self.validate_target_warehouse()
Deepesh Gargfa152212022-11-28 19:22:35 +053040 self.validate_auto_repeat_subscription_dates()
Anand Doshid2946502014-04-08 20:10:03 +053041
Anand Doshif3096132013-05-21 19:35:06 +053042 def set_missing_values(self, for_validate=False):
Shreya Shah5615cb42018-10-07 11:42:07 +053043
Anand Doshiabc10032013-06-14 17:44:03 +053044 super(SellingController, self).set_missing_values(for_validate)
Anand Doshid2946502014-04-08 20:10:03 +053045
Anand Doshif3096132013-05-21 19:35:06 +053046 # set contact and address details for customer, if they are not mentioned
Deepesh Garg6f3d93e2020-09-18 11:23:35 +053047 self.set_missing_lead_customer_details(for_validate=for_validate)
mbauskar9e9d2422017-04-10 19:16:07 +053048 self.set_price_list_and_item_details(for_validate=for_validate)
Anand Doshid2946502014-04-08 20:10:03 +053049
Deepesh Garg6f3d93e2020-09-18 11:23:35 +053050 def set_missing_lead_customer_details(self, for_validate=False):
Nabin Hait34c551d2019-07-03 10:34:31 +053051 customer, lead = None, None
Rushabh Mehtaf14b8092014-04-03 14:30:42 +053052 if getattr(self, "customer", None):
Nabin Hait34c551d2019-07-03 10:34:31 +053053 customer = self.customer
54 elif self.doctype == "Opportunity" and self.party_name:
55 if self.opportunity_from == "Customer":
56 customer = self.party_name
57 else:
58 lead = self.party_name
59 elif self.doctype == "Quotation" and self.party_name:
60 if self.quotation_to == "Customer":
61 customer = self.party_name
62 else:
63 lead = self.party_name
64
65 if customer:
Anand Doshi43624432014-02-25 15:42:16 +053066 from erpnext.accounts.party import _get_party_details
Ankush Menat494bd9e2022-03-28 18:52:46 +053067
rohitwaghchaure3ffe8962018-07-13 17:40:48 +053068 fetch_payment_terms_template = False
Ankush Menat494bd9e2022-03-28 18:52:46 +053069 if self.get("__islocal") or self.company != frappe.db.get_value(
70 self.doctype, self.name, "company"
71 ):
rohitwaghchaure3ffe8962018-07-13 17:40:48 +053072 fetch_payment_terms_template = True
73
Ankush Menat494bd9e2022-03-28 18:52:46 +053074 party_details = _get_party_details(
75 customer,
Nabin Hait7eba1a32017-10-02 15:59:27 +053076 ignore_permissions=self.flags.ignore_permissions,
Ankush Menat494bd9e2022-03-28 18:52:46 +053077 doctype=self.doctype,
78 company=self.company,
79 posting_date=self.get("posting_date"),
Shreya Shah5615cb42018-10-07 11:42:07 +053080 fetch_payment_terms_template=fetch_payment_terms_template,
Ankush Menat494bd9e2022-03-28 18:52:46 +053081 party_address=self.customer_address,
82 shipping_address=self.shipping_address_name,
83 company_address=self.get("company_address"),
84 )
Nabin Hait6b039142014-05-02 15:45:10 +053085 if not self.meta.get_field("sales_team"):
86 party_details.pop("sales_team")
Nabin Hait6b039142014-05-02 15:45:10 +053087 self.update_if_missing(party_details)
Anand Doshid2946502014-04-08 20:10:03 +053088
Nabin Hait34c551d2019-07-03 10:34:31 +053089 elif lead:
Rushabh Mehta60cfccb2015-02-17 10:36:54 +053090 from erpnext.crm.doctype.lead.lead import get_lead_details
Anand Doshid2946502014-04-08 20:10:03 +053091
Ankush Menat494bd9e2022-03-28 18:52:46 +053092 self.update_if_missing(
93 get_lead_details(
94 lead,
95 posting_date=self.get("transaction_date") or self.get("posting_date"),
96 company=self.company,
97 )
98 )
99
100 if self.get("taxes_and_charges") and not self.get("taxes") and not for_validate:
101 taxes = get_taxes_and_charges("Sales Taxes and Charges Template", self.taxes_and_charges)
Deepesh Garg6f3d93e2020-09-18 11:23:35 +0530102 for tax in taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530103 self.append("taxes", tax)
Deepesh Garg6f3d93e2020-09-18 11:23:35 +0530104
mbauskar9e9d2422017-04-10 19:16:07 +0530105 def set_price_list_and_item_details(self, for_validate=False):
Nabin Hait096d3632013-10-17 17:01:14 +0530106 self.set_price_list_currency("Selling")
mbauskar287fe812017-04-10 19:15:57 +0530107 self.set_missing_item_details(for_validate=for_validate)
Anand Doshid2946502014-04-08 20:10:03 +0530108
Anand Doshiac32bad2014-04-18 01:30:14 +0530109 def remove_shipping_charge(self):
110 if self.shipping_rule:
111 shipping_rule = frappe.get_doc("Shipping Rule", self.shipping_rule)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530112 existing_shipping_charge = self.get(
113 "taxes",
114 {
115 "doctype": "Sales Taxes and Charges",
116 "charge_type": "Actual",
117 "account_head": shipping_rule.account,
118 "cost_center": shipping_rule.cost_center,
119 },
120 )
Anand Doshiac32bad2014-04-18 01:30:14 +0530121 if existing_shipping_charge:
Nabin Haite7d15362014-12-25 16:01:55 +0530122 self.get("taxes").remove(existing_shipping_charge[-1])
Anand Doshiac32bad2014-04-18 01:30:14 +0530123 self.calculate_taxes_and_totals()
Anand Doshid2946502014-04-08 20:10:03 +0530124
Nabin Haitec52db82013-01-22 11:53:14 +0530125 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530126 from frappe.utils import money_in_words
Anand Doshid2946502014-04-08 20:10:03 +0530127
Nabin Hait5690be12015-02-12 16:09:11 +0530128 if self.meta.get_field("base_in_words"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530129 base_amount = abs(
130 self.base_grand_total if self.is_rounded_total_disabled() else self.base_rounded_total
131 )
Nabin Hait877e1bb2017-11-17 12:27:43 +0530132 self.base_in_words = money_in_words(base_amount, self.company_currency)
133
Nabin Haitec52db82013-01-22 11:53:14 +0530134 if self.meta.get_field("in_words"):
Nabin Hait877e1bb2017-11-17 12:27:43 +0530135 amount = abs(self.grand_total if self.is_rounded_total_disabled() else self.rounded_total)
136 self.in_words = money_in_words(amount, self.currency)
Anand Doshid2946502014-04-08 20:10:03 +0530137
Anand Doshi923d41d2013-05-28 17:23:36 +0530138 def calculate_commission(self):
Raffael Meyere10ab162021-11-30 13:24:18 +0100139 if not self.meta.get_field("commission_rate"):
140 return
Anand Doshid2946502014-04-08 20:10:03 +0530141
Ankush Menat494bd9e2022-03-28 18:52:46 +0530142 self.round_floats_in(self, ("amount_eligible_for_commission", "commission_rate"))
Raffael Meyere10ab162021-11-30 13:24:18 +0100143
144 if not (0 <= self.commission_rate <= 100.0):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530145 throw(
146 "{} {}".format(
147 _(self.meta.get_label("commission_rate")),
148 _("must be between 0 and 100"),
149 )
150 )
Raffael Meyere10ab162021-11-30 13:24:18 +0100151
152 self.amount_eligible_for_commission = sum(
153 item.base_net_amount for item in self.items if item.grant_commission
154 )
155
156 self.total_commission = flt(
157 self.amount_eligible_for_commission * self.commission_rate / 100.0,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530158 self.precision("total_commission"),
Raffael Meyere10ab162021-11-30 13:24:18 +0100159 )
Anand Doshif3096132013-05-21 19:35:06 +0530160
161 def calculate_contribution(self):
Anand Doshiac32bad2014-04-18 01:30:14 +0530162 if not self.meta.get_field("sales_team"):
163 return
164
Anand Doshif3096132013-05-21 19:35:06 +0530165 total = 0.0
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530166 sales_team = self.get("sales_team")
Anand Doshif3096132013-05-21 19:35:06 +0530167 for sales_person in sales_team:
168 self.round_floats_in(sales_person)
169
170 sales_person.allocated_amount = flt(
Raffael Meyere10ab162021-11-30 13:24:18 +0100171 self.amount_eligible_for_commission * sales_person.allocated_percentage / 100.0,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530172 self.precision("allocated_amount", sales_person),
173 )
Anand Doshid2946502014-04-08 20:10:03 +0530174
Anuja Pawar87553392021-03-01 10:44:13 +0530175 if sales_person.commission_rate:
176 sales_person.incentives = flt(
Sagar Voraf4a6c782021-03-17 19:57:53 +0530177 sales_person.allocated_amount * flt(sales_person.commission_rate) / 100.0,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530178 self.precision("incentives", sales_person),
179 )
Anuja Pawar87553392021-03-01 10:44:13 +0530180
Anand Doshif3096132013-05-21 19:35:06 +0530181 total += sales_person.allocated_percentage
Anand Doshid2946502014-04-08 20:10:03 +0530182
Anand Doshif3096132013-05-21 19:35:06 +0530183 if sales_team and total != 100.0:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530184 throw(_("Total allocated percentage for sales team should be 100"))
Anand Doshid2946502014-04-08 20:10:03 +0530185
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530186 def validate_max_discount(self):
Nabin Haitdd38a262014-12-26 13:15:21 +0530187 for d in self.get("items"):
Nabin Haitc35271a2018-08-10 19:01:04 +0530188 if d.item_code:
189 discount = flt(frappe.get_cached_value("Item", d.item_code, "max_discount"))
Anand Doshid2946502014-04-08 20:10:03 +0530190
Nabin Haitc35271a2018-08-10 19:01:04 +0530191 if discount and flt(d.discount_percentage) > discount:
192 frappe.throw(_("Maximum discount for Item {0} is {1}%").format(d.item_code, discount))
Anand Doshid2946502014-04-08 20:10:03 +0530193
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530194 def set_qty_as_per_stock_uom(self):
195 for d in self.get("items"):
196 if d.meta.get_field("stock_qty"):
197 if not d.conversion_factor:
198 frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530199 d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530200
shreyas1cfe2d72016-10-19 18:36:12 +0530201 def validate_selling_price(self):
Saqibfff00ce2020-05-05 16:14:17 +0530202 def throw_message(idx, item_name, rate, ref_rate_field):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530203 throw(
204 _(
205 """Row #{0}: Selling rate for item {1} is lower than its {2}.
Pruthvi Patel7c957d72021-08-24 21:24:25 +0530206 Selling {3} should be atleast {4}.<br><br>Alternatively,
207 you can disable selling price validation in {5} to bypass
Ankush Menat494bd9e2022-03-28 18:52:46 +0530208 this validation."""
209 ).format(
210 idx,
211 bold(item_name),
212 bold(ref_rate_field),
213 bold("net rate"),
214 bold(rate),
215 get_link_to_form("Selling Settings", "Selling Settings"),
216 ),
217 title=_("Invalid Selling Price"),
218 )
mbauskare9747a82016-11-16 17:19:47 +0530219
Ankush Menat494bd9e2022-03-28 18:52:46 +0530220 if self.get("is_return") or not frappe.db.get_single_value(
221 "Selling Settings", "validate_selling_price"
Pruthvi Patel7c957d72021-08-24 21:24:25 +0530222 ):
rohitwaghchaure45ac31a2018-02-12 11:27:37 +0530223 return
224
Ankush Menat494bd9e2022-03-28 18:52:46 +0530225 is_internal_customer = self.get("is_internal_customer")
Pruthvi Patel7c957d72021-08-24 21:24:25 +0530226 valuation_rate_map = {}
227
228 for item in self.items:
Krithi Ramani8c536ff2022-01-19 15:27:09 +0530229 if not item.item_code or item.is_free_item:
Saurabhd7e18692017-09-18 15:43:35 +0530230 continue
prssannab57b3c92020-10-22 15:37:47 +0530231
Pruthvi Patel7c957d72021-08-24 21:24:25 +0530232 last_purchase_rate, is_stock_item = frappe.get_cached_value(
233 "Item", item.item_code, ("last_purchase_rate", "is_stock_item")
234 )
shreyase8aaa922016-10-20 14:03:59 +0530235
Ankush Menat494bd9e2022-03-28 18:52:46 +0530236 last_purchase_rate_in_sales_uom = last_purchase_rate * (item.conversion_factor or 1)
shreyase8aaa922016-10-20 14:03:59 +0530237
Pruthvi Patel7c957d72021-08-24 21:24:25 +0530238 if flt(item.base_net_rate) < flt(last_purchase_rate_in_sales_uom):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530239 throw_message(item.idx, item.item_name, last_purchase_rate_in_sales_uom, "last purchase rate")
Pruthvi Patel7c957d72021-08-24 21:24:25 +0530240
241 if is_internal_customer or not is_stock_item:
242 continue
243
244 valuation_rate_map[(item.item_code, item.warehouse)] = None
245
246 if not valuation_rate_map:
247 return
248
249 or_conditions = (
250 f"""(item_code = {frappe.db.escape(valuation_rate[0])}
251 and warehouse = {frappe.db.escape(valuation_rate[1])})"""
252 for valuation_rate in valuation_rate_map
253 )
254
Ankush Menat494bd9e2022-03-28 18:52:46 +0530255 valuation_rates = frappe.db.sql(
256 f"""
Pruthvi Patel7c957d72021-08-24 21:24:25 +0530257 select
258 item_code, warehouse, valuation_rate
259 from
260 `tabBin`
261 where
262 ({" or ".join(or_conditions)})
263 and valuation_rate > 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530264 """,
265 as_dict=True,
266 )
Pruthvi Patel7c957d72021-08-24 21:24:25 +0530267
268 for rate in valuation_rates:
269 valuation_rate_map[(rate.item_code, rate.warehouse)] = rate.valuation_rate
270
271 for item in self.items:
Krithi Ramani8c536ff2022-01-19 15:27:09 +0530272 if not item.item_code or item.is_free_item:
Pruthvi Patel7c957d72021-08-24 21:24:25 +0530273 continue
274
Ankush Menat494bd9e2022-03-28 18:52:46 +0530275 last_valuation_rate = valuation_rate_map.get((item.item_code, item.warehouse))
Pruthvi Patel7c957d72021-08-24 21:24:25 +0530276
277 if not last_valuation_rate:
278 continue
279
Ankush Menat494bd9e2022-03-28 18:52:46 +0530280 last_valuation_rate_in_sales_uom = last_valuation_rate * (item.conversion_factor or 1)
Pruthvi Patel7c957d72021-08-24 21:24:25 +0530281
282 if flt(item.base_net_rate) < flt(last_valuation_rate_in_sales_uom):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530283 throw_message(item.idx, item.item_name, last_valuation_rate_in_sales_uom, "valuation rate")
shreyas1cfe2d72016-10-19 18:36:12 +0530284
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530285 def get_item_list(self):
286 il = []
Nabin Haitdd38a262014-12-26 13:15:21 +0530287 for d in self.get("items"):
nathando247e9ff2014-09-03 15:03:31 +0800288 if d.qty is None:
Nabin Haitc41a9482014-08-18 15:40:15 +0530289 frappe.throw(_("Row {0}: Qty is mandatory").format(d.idx))
Anand Doshi01de9452016-01-26 16:22:50 +0530290
Neil Trini Lasradoed8cecb2015-07-07 13:59:23 +0530291 if self.has_product_bundle(d.item_code):
Nabin Haite7d15362014-12-25 16:01:55 +0530292 for p in self.get("packed_items"):
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530293 if p.parent_detail_docname == d.name and p.parent_item == d.item_code:
294 # the packing details table's qty is already multiplied with parent's qty
Ankush Menat494bd9e2022-03-28 18:52:46 +0530295 il.append(
296 frappe._dict(
297 {
298 "warehouse": p.warehouse or d.warehouse,
299 "item_code": p.item_code,
300 "qty": flt(p.qty),
301 "uom": p.uom,
302 "batch_no": cstr(p.batch_no).strip(),
303 "serial_no": cstr(p.serial_no).strip(),
304 "name": d.name,
305 "target_warehouse": p.target_warehouse,
306 "company": self.company,
307 "voucher_type": self.doctype,
308 "allow_zero_valuation": d.allow_zero_valuation_rate,
309 "sales_invoice_item": d.get("sales_invoice_item"),
310 "dn_detail": d.get("dn_detail"),
311 "incoming_rate": p.get("incoming_rate"),
Rohit Waghchaure23729992022-09-02 18:43:55 +0530312 "item_row": p,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530313 }
314 )
315 )
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530316 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530317 il.append(
318 frappe._dict(
319 {
320 "warehouse": d.warehouse,
321 "item_code": d.item_code,
322 "qty": d.stock_qty,
323 "uom": d.uom,
324 "stock_uom": d.stock_uom,
325 "conversion_factor": d.conversion_factor,
326 "batch_no": cstr(d.get("batch_no")).strip(),
327 "serial_no": cstr(d.get("serial_no")).strip(),
328 "name": d.name,
329 "target_warehouse": d.target_warehouse,
330 "company": self.company,
331 "voucher_type": self.doctype,
332 "allow_zero_valuation": d.allow_zero_valuation_rate,
333 "sales_invoice_item": d.get("sales_invoice_item"),
334 "dn_detail": d.get("dn_detail"),
335 "incoming_rate": d.get("incoming_rate"),
Rohit Waghchaure23729992022-09-02 18:43:55 +0530336 "item_row": d,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530337 }
338 )
339 )
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530340 return il
Anand Doshid2946502014-04-08 20:10:03 +0530341
Neil Trini Lasradoed8cecb2015-07-07 13:59:23 +0530342 def has_product_bundle(self, item_code):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530343 return frappe.db.sql(
344 """select name from `tabProduct Bundle`
345 where new_item_code=%s and docstatus != 2""",
346 item_code,
347 )
Anand Doshid2946502014-04-08 20:10:03 +0530348
Nabin Hait453cc372015-07-29 12:21:03 +0530349 def get_already_delivered_qty(self, current_docname, so, so_detail):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530350 delivered_via_dn = frappe.db.sql(
351 """select sum(qty) from `tabDelivery Note Item`
ankitjavalkarworke69a6112014-10-08 12:46:02 +0530352 where so_detail = %s and docstatus = 1
Anand Doshid2946502014-04-08 20:10:03 +0530353 and against_sales_order = %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530354 and parent != %s""",
355 (so_detail, so, current_docname),
356 )
Anand Doshi01de9452016-01-26 16:22:50 +0530357
Ankush Menat494bd9e2022-03-28 18:52:46 +0530358 delivered_via_si = frappe.db.sql(
359 """select sum(si_item.qty)
Nabin Hait18267912015-08-17 15:36:23 +0530360 from `tabSales Invoice Item` si_item, `tabSales Invoice` si
Anand Doshi602e8252015-11-16 19:05:46 +0530361 where si_item.parent = si.name and si.update_stock = 1
Anand Doshi01de9452016-01-26 16:22:50 +0530362 and si_item.so_detail = %s and si.docstatus = 1
Nabin Hait18267912015-08-17 15:36:23 +0530363 and si_item.sales_order = %s
Ankush Menat494bd9e2022-03-28 18:52:46 +0530364 and si.name != %s""",
365 (so_detail, so, current_docname),
366 )
Anand Doshi01de9452016-01-26 16:22:50 +0530367
Ankush Menat494bd9e2022-03-28 18:52:46 +0530368 total_delivered_qty = (flt(delivered_via_dn[0][0]) if delivered_via_dn else 0) + (
369 flt(delivered_via_si[0][0]) if delivered_via_si else 0
370 )
Anand Doshi01de9452016-01-26 16:22:50 +0530371
Nabin Hait453cc372015-07-29 12:21:03 +0530372 return total_delivered_qty
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530373
374 def get_so_qty_and_warehouse(self, so_detail):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530375 so_item = frappe.db.sql(
376 """select qty, warehouse from `tabSales Order Item`
377 where name = %s and docstatus = 1""",
378 so_detail,
379 as_dict=1,
380 )
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530381 so_qty = so_item and flt(so_item[0]["qty"]) or 0.0
Nabin Haita7f757a2014-02-10 17:54:04 +0530382 so_warehouse = so_item and so_item[0]["warehouse"] or ""
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530383 return so_qty, so_warehouse
Anand Doshid2946502014-04-08 20:10:03 +0530384
Mangesh-Khairnare17b7092019-03-01 15:52:23 +0530385 def check_sales_order_on_hold_or_close(self, ref_fieldname):
Nabin Haitdd38a262014-12-26 13:15:21 +0530386 for d in self.get("items"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530387 if d.get(ref_fieldname):
Rushabh Mehtaf2227d02014-03-31 23:37:40 +0530388 status = frappe.db.get_value("Sales Order", d.get(ref_fieldname), "status")
Mangesh-Khairnar86e650c2019-03-02 20:30:21 +0530389 if status in ("Closed", "On Hold"):
Saurabh8a8ef852015-10-21 19:28:53 +0530390 frappe.throw(_("Sales Order {0} is {1}").format(d.get(ref_fieldname), status))
shreyas1cfe2d72016-10-19 18:36:12 +0530391
Nabin Hait14aa9c52016-04-18 15:54:01 +0530392 def update_reserved_qty(self):
393 so_map = {}
394 for d in self.get("items"):
395 if d.so_detail:
396 if self.doctype == "Delivery Note" and d.against_sales_order:
397 so_map.setdefault(d.against_sales_order, []).append(d.so_detail)
398 elif self.doctype == "Sales Invoice" and d.sales_order and self.update_stock:
399 so_map.setdefault(d.sales_order, []).append(d.so_detail)
400
401 for so, so_item_rows in so_map.items():
402 if so and so_item_rows:
403 sales_order = frappe.get_doc("Sales Order", so)
404
405 if sales_order.status in ["Closed", "Cancelled"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530406 frappe.throw(
407 _("{0} {1} is cancelled or closed").format(_("Sales Order"), so), frappe.InvalidStatusError
408 )
Nabin Hait14aa9c52016-04-18 15:54:01 +0530409
410 sales_order.update_reserved_qty(so_item_rows)
411
Nabin Haita77b8c92020-12-21 14:45:50 +0530412 def set_incoming_rate(self):
rohitwaghchaurefe4540d2021-08-26 12:52:36 +0530413 if self.doctype not in ("Delivery Note", "Sales Invoice"):
Nabin Haita77b8c92020-12-21 14:45:50 +0530414 return
415
416 items = self.get("items") + (self.get("packed_items") or [])
417 for d in items:
rohitwaghchaurece6c3b52021-04-13 20:55:52 +0530418 if not self.get("return_against"):
Nabin Haita77b8c92020-12-21 14:45:50 +0530419 # Get incoming rate based on original item cost based on valuation method
Ankush Menat494bd9e2022-03-28 18:52:46 +0530420 qty = flt(d.get("stock_qty") or d.get("actual_qty"))
rohitwaghchaurece6c3b52021-04-13 20:55:52 +0530421
Ankush Menatfcc885b2021-12-22 12:38:51 +0530422 if not (self.get("is_return") and d.incoming_rate):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530423 d.incoming_rate = get_incoming_rate(
424 {
425 "item_code": d.item_code,
426 "warehouse": d.warehouse,
427 "posting_date": self.get("posting_date") or self.get("transaction_date"),
428 "posting_time": self.get("posting_time") or nowtime(),
429 "qty": qty if cint(self.get("is_return")) else (-1 * qty),
430 "serial_no": d.get("serial_no"),
431 "batch_no": d.get("batch_no"),
432 "company": self.company,
433 "voucher_type": self.doctype,
434 "voucher_no": self.name,
435 "allow_zero_valuation": d.get("allow_zero_valuation"),
436 },
437 raise_error_if_no_rate=False,
438 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530439
440 # For internal transfers use incoming rate as the valuation rate
441 if self.is_internal_transfer():
Deepesh Gargef9d1262022-12-05 10:17:19 +0530442 if self.doctype == "Delivery Note" or self.get("update_stock"):
443 if d.doctype == "Packed Item":
444 incoming_rate = flt(
445 flt(d.incoming_rate, d.precision("incoming_rate")) * d.conversion_factor,
446 d.precision("incoming_rate"),
Ankush Menatee0a2772022-05-12 18:17:09 +0530447 )
Deepesh Gargef9d1262022-12-05 10:17:19 +0530448 if d.incoming_rate != incoming_rate:
449 d.incoming_rate = incoming_rate
450 else:
451 rate = flt(
452 flt(d.incoming_rate, d.precision("incoming_rate")) * d.conversion_factor,
453 d.precision("rate"),
454 )
455 if d.rate != rate:
456 d.rate = rate
457 frappe.msgprint(
458 _(
459 "Row {0}: Item rate has been updated as per valuation rate since its an internal stock transfer"
460 ).format(d.idx),
461 alert=1,
462 )
Noah Jacobac0bc1f2021-06-24 19:36:17 +0530463
Deepesh Gargef9d1262022-12-05 10:17:19 +0530464 d.discount_percentage = 0.0
465 d.discount_amount = 0.0
466 d.margin_rate_or_amount = 0.0
Deepesh Gargb4be2922021-01-28 13:09:56 +0530467
Nabin Haita77b8c92020-12-21 14:45:50 +0530468 elif self.get("return_against"):
469 # Get incoming rate of return entry from reference document
470 # based on original item cost as per valuation method
Ankush Menat494bd9e2022-03-28 18:52:46 +0530471 d.incoming_rate = get_rate_for_return(
472 self.doctype, self.name, d.item_code, self.return_against, item_row=d
473 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530474
Nabin Hait14aa9c52016-04-18 15:54:01 +0530475 def update_stock_ledger(self):
476 self.update_reserved_qty()
477
478 sl_entries = []
Nabin Haita77b8c92020-12-21 14:45:50 +0530479 # Loop over items and packed items table
Nabin Hait14aa9c52016-04-18 15:54:01 +0530480 for d in self.get_item_list():
Himanshu Mishra859d9422018-08-08 18:33:50 +0530481 if frappe.get_cached_value("Item", d.item_code, "is_stock_item") == 1 and flt(d.qty):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530482 if flt(d.conversion_factor) == 0.0:
483 d.conversion_factor = (
484 get_conversion_factor(d.item_code, d.uom).get("conversion_factor") or 1.0
485 )
rohitwaghchaure019d4de2020-08-20 15:53:58 +0530486
Nabin Haita77b8c92020-12-21 14:45:50 +0530487 # On cancellation or return entry submission, make stock ledger entry for
Nabin Hait14aa9c52016-04-18 15:54:01 +0530488 # target warehouse first, to update serial no values properly
489
Ankush Menat494bd9e2022-03-28 18:52:46 +0530490 if d.warehouse and (
491 (not cint(self.is_return) and self.docstatus == 1)
492 or (cint(self.is_return) and self.docstatus == 2)
493 ):
494 sl_entries.append(self.get_sle_for_source_warehouse(d))
Nabin Hait14aa9c52016-04-18 15:54:01 +0530495
mergify[bot]233bf5d2021-10-05 16:16:21 +0530496 if d.target_warehouse:
Nabin Haita77b8c92020-12-21 14:45:50 +0530497 sl_entries.append(self.get_sle_for_target_warehouse(d))
Nabin Hait14aa9c52016-04-18 15:54:01 +0530498
Ankush Menat494bd9e2022-03-28 18:52:46 +0530499 if d.warehouse and (
500 (not cint(self.is_return) and self.docstatus == 2)
501 or (cint(self.is_return) and self.docstatus == 1)
502 ):
503 sl_entries.append(self.get_sle_for_source_warehouse(d))
Nabin Haita77b8c92020-12-21 14:45:50 +0530504
Nabin Hait14aa9c52016-04-18 15:54:01 +0530505 self.make_sl_entries(sl_entries)
Anand Doshid2946502014-04-08 20:10:03 +0530506
Nabin Haita77b8c92020-12-21 14:45:50 +0530507 def get_sle_for_source_warehouse(self, item_row):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530508 sle = self.get_sl_entries(
509 item_row,
510 {
511 "actual_qty": -1 * flt(item_row.qty),
512 "incoming_rate": item_row.incoming_rate,
513 "recalculate_rate": cint(self.is_return),
514 },
515 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530516 if item_row.target_warehouse and not cint(self.is_return):
517 sle.dependant_sle_voucher_detail_no = item_row.name
518
519 return sle
520
521 def get_sle_for_target_warehouse(self, item_row):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530522 sle = self.get_sl_entries(
523 item_row, {"actual_qty": flt(item_row.qty), "warehouse": item_row.target_warehouse}
524 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530525
526 if self.docstatus == 1:
527 if not cint(self.is_return):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530528 sle.update({"incoming_rate": item_row.incoming_rate, "recalculate_rate": 1})
Nabin Haita77b8c92020-12-21 14:45:50 +0530529 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530530 sle.update({"outgoing_rate": item_row.incoming_rate})
Nabin Haita77b8c92020-12-21 14:45:50 +0530531 if item_row.warehouse:
532 sle.dependant_sle_voucher_detail_no = item_row.name
Deepesh Gargb4be2922021-01-28 13:09:56 +0530533
Nabin Haita77b8c92020-12-21 14:45:50 +0530534 return sle
535
Afshan01eca122020-12-08 09:27:56 +0530536 def set_po_nos(self, for_validate=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530537 if self.doctype == "Sales Invoice" and hasattr(self, "items"):
Afshan01eca122020-12-08 09:27:56 +0530538 if for_validate and self.po_no:
539 return
Afshan3f971b22020-10-26 16:59:57 +0530540 self.set_pos_for_sales_invoice()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530541 if self.doctype == "Delivery Note" and hasattr(self, "items"):
Afshan01eca122020-12-08 09:27:56 +0530542 if for_validate and self.po_no:
543 return
Afshan3f971b22020-10-26 16:59:57 +0530544 self.set_pos_for_delivery_note()
545
546 def set_pos_for_sales_invoice(self):
Afshan0a6e1b32020-10-26 21:23:31 +0530547 po_nos = []
Afshan01eca122020-12-08 09:27:56 +0530548 if self.po_no:
549 po_nos.append(self.po_no)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530550 self.get_po_nos("Sales Order", "sales_order", po_nos)
551 self.get_po_nos("Delivery Note", "delivery_note", po_nos)
552 self.po_no = ", ".join(list(set(x.strip() for x in ",".join(po_nos).split(","))))
Afshan3f971b22020-10-26 16:59:57 +0530553
554 def set_pos_for_delivery_note(self):
Afshan0a6e1b32020-10-26 21:23:31 +0530555 po_nos = []
Afshan01eca122020-12-08 09:27:56 +0530556 if self.po_no:
557 po_nos.append(self.po_no)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530558 self.get_po_nos("Sales Order", "against_sales_order", po_nos)
559 self.get_po_nos("Sales Invoice", "against_sales_invoice", po_nos)
560 self.po_no = ", ".join(list(set(x.strip() for x in ",".join(po_nos).split(","))))
Afshan0a6e1b32020-10-26 21:23:31 +0530561
562 def get_po_nos(self, ref_doctype, ref_fieldname, po_nos):
Ankush Menat98917802021-06-11 18:40:22 +0530563 doc_list = list(set(d.get(ref_fieldname) for d in self.items if d.get(ref_fieldname)))
Afshan0a6e1b32020-10-26 21:23:31 +0530564 if doc_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530565 po_nos += [
566 d.po_no
567 for d in frappe.get_all(ref_doctype, "po_no", filters={"name": ("in", doc_list)})
568 if d.get("po_no")
569 ]
Nabin Hait96f4b222018-03-13 15:46:59 +0530570
Saif Ur Rehman5fdbc682018-11-26 19:32:16 +0500571 def set_gross_profit(self):
Abhishek Balam18e7b602020-05-26 18:37:02 +0530572 if self.doctype in ["Sales Order", "Quotation"]:
Saif Ur Rehman5fdbc682018-11-26 19:32:16 +0500573 for item in self.items:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530574 item.gross_profit = flt(
575 ((item.base_rate - item.valuation_rate) * item.stock_qty), self.precision("amount", item)
576 )
Saif Ur Rehman5fdbc682018-11-26 19:32:16 +0500577
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530578 def set_customer_address(self):
579 address_dict = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530580 "customer_address": "address_display",
581 "shipping_address_name": "shipping_address",
582 "company_address": "company_address_display",
Deepesh Garg104fdcb2022-11-24 16:41:40 +0530583 "dispatch_address_name": "dispatch_address",
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530584 }
585
586 for address_field, address_display_field in address_dict.items():
587 if self.get(address_field):
588 self.set(address_display_field, get_address_display(self.get(address_field)))
589
Deepesh Gargf3d78dd2019-08-23 11:42:35 +0530590 def validate_for_duplicate_items(self):
591 check_list, chk_dupl_itm = [], []
592 if cint(frappe.db.get_single_value("Selling Settings", "allow_multiple_items")):
593 return
Saqib0681a482021-02-11 14:06:15 +0530594 if self.doctype == "Sales Invoice" and self.is_consolidated:
595 return
596 if self.doctype == "POS Invoice":
597 return
Deepesh Gargf3d78dd2019-08-23 11:42:35 +0530598
Ankush Menat494bd9e2022-03-28 18:52:46 +0530599 for d in self.get("items"):
Saqib0681a482021-02-11 14:06:15 +0530600 if self.doctype == "Sales Invoice":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530601 stock_items = [
602 d.item_code,
603 d.description,
604 d.warehouse,
605 d.sales_order or d.delivery_note,
606 d.batch_no or "",
607 ]
Jannat Patelc1187bc2020-11-19 13:10:24 +0530608 non_stock_items = [d.item_code, d.description, d.sales_order or d.delivery_note]
Deepesh Gargf3d78dd2019-08-23 11:42:35 +0530609 elif self.doctype == "Delivery Note":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530610 stock_items = [
611 d.item_code,
612 d.description,
613 d.warehouse,
614 d.against_sales_order or d.against_sales_invoice,
615 d.batch_no or "",
616 ]
617 non_stock_items = [
618 d.item_code,
619 d.description,
620 d.against_sales_order or d.against_sales_invoice,
621 ]
Rohit Waghchaure13c7e182019-08-29 19:45:19 +0530622 elif self.doctype in ["Sales Order", "Quotation"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530623 stock_items = [d.item_code, d.description, d.warehouse, ""]
Jannat Patelc1187bc2020-11-19 13:10:24 +0530624 non_stock_items = [d.item_code, d.description]
Deepesh Gargf3d78dd2019-08-23 11:42:35 +0530625
mergify[bot]89f516c2022-07-21 13:57:03 +0530626 duplicate_items_msg = _("Item {0} entered multiple times.").format(frappe.bold(d.item_code))
627 duplicate_items_msg += "<br><br>"
628 duplicate_items_msg += _("Please enable {} in {} to allow same item in multiple rows").format(
629 frappe.bold("Allow Item to Be Added Multiple Times in a Transaction"),
630 get_link_to_form("Selling Settings", "Selling Settings"),
631 )
Deepesh Gargf3d78dd2019-08-23 11:42:35 +0530632 if frappe.db.get_value("Item", d.item_code, "is_stock_item") == 1:
Jannat Patelc1187bc2020-11-19 13:10:24 +0530633 if stock_items in check_list:
Saqibac9e6ff2021-01-28 17:58:55 +0530634 frappe.throw(duplicate_items_msg)
Deepesh Gargf3d78dd2019-08-23 11:42:35 +0530635 else:
Jannat Patelc1187bc2020-11-19 13:10:24 +0530636 check_list.append(stock_items)
Deepesh Gargf3d78dd2019-08-23 11:42:35 +0530637 else:
Jannat Patelc1187bc2020-11-19 13:10:24 +0530638 if non_stock_items in chk_dupl_itm:
Saqibac9e6ff2021-01-28 17:58:55 +0530639 frappe.throw(duplicate_items_msg)
Deepesh Gargf3d78dd2019-08-23 11:42:35 +0530640 else:
Jannat Patelc1187bc2020-11-19 13:10:24 +0530641 chk_dupl_itm.append(non_stock_items)
Deepesh Gargf3d78dd2019-08-23 11:42:35 +0530642
rohitwaghchaure6fa6caf2020-04-23 09:46:29 +0530643 def validate_target_warehouse(self):
644 items = self.get("items") + (self.get("packed_items") or [])
645
646 for d in items:
647 if d.get("target_warehouse") and d.get("warehouse") == d.get("target_warehouse"):
648 warehouse = frappe.bold(d.get("target_warehouse"))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530649 frappe.throw(
650 _("Row {0}: Delivery Warehouse ({1}) and Customer Warehouse ({2}) can not be same").format(
651 d.idx, warehouse, warehouse
652 )
653 )
Deepesh Gargf3d78dd2019-08-23 11:42:35 +0530654
mergify[bot]233bf5d2021-10-05 16:16:21 +0530655 if not self.get("is_internal_customer") and any(d.get("target_warehouse") for d in items):
656 msg = _("Target Warehouse is set for some items but the customer is not an internal customer.")
657 msg += " " + _("This {} will be treated as material transfer.").format(_(self.doctype))
658 frappe.msgprint(msg, title="Internal Transfer", alert=True)
659
Zarrarfc03a042018-06-04 12:52:52 +0530660 def validate_items(self):
661 # validate items to see if they have is_sales_item enabled
662 from erpnext.controllers.buying_controller import validate_item_type
Ankush Menat494bd9e2022-03-28 18:52:46 +0530663
Zarrarfc03a042018-06-04 12:52:52 +0530664 validate_item_type(self, "is_sales_item", "sales")
665
Ankush Menat494bd9e2022-03-28 18:52:46 +0530666
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530667def set_default_income_account_for_item(obj):
Nabin Haitdd38a262014-12-26 13:15:21 +0530668 for d in obj.get("items"):
Nabin Haitd1fd1e22013-10-18 12:29:11 +0530669 if d.item_code:
Manas Solanki5b935622018-05-16 17:44:51 +0530670 if getattr(d, "income_account", None):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530671 set_item_default(d.item_code, obj.company, "income_account", d.income_account)