You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

675 lines
22 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # License: GNU General Public License v3. See license.txt
  3. import frappe
  4. from frappe import _, bold, throw
  5. from frappe.contacts.doctype.address.address import get_address_display
  6. from frappe.utils import cint, cstr, flt, get_link_to_form, nowtime
  7. from erpnext.controllers.accounts_controller import get_taxes_and_charges
  8. from erpnext.controllers.sales_and_purchase_return import get_rate_for_return
  9. from erpnext.controllers.stock_controller import StockController
  10. from erpnext.stock.doctype.item.item import set_item_default
  11. from erpnext.stock.get_item_details import get_bin_details, get_conversion_factor
  12. from erpnext.stock.utils import get_incoming_rate
  13. class SellingController(StockController):
  14. def __setup__(self):
  15. self.flags.ignore_permlevel_for_fields = ["selling_price_list", "price_list_currency"]
  16. def get_feed(self):
  17. return _("To {0} | {1} {2}").format(self.customer_name, self.currency, self.grand_total)
  18. def onload(self):
  19. super(SellingController, self).onload()
  20. if self.doctype in ("Sales Order", "Delivery Note", "Sales Invoice"):
  21. for item in self.get("items") + (self.get("packed_items") or []):
  22. item.update(get_bin_details(item.item_code, item.warehouse, include_child_warehouses=True))
  23. def validate(self):
  24. super(SellingController, self).validate()
  25. self.validate_items()
  26. self.validate_max_discount()
  27. self.validate_selling_price()
  28. self.set_qty_as_per_stock_uom()
  29. self.set_po_nos(for_validate=True)
  30. self.set_gross_profit()
  31. set_default_income_account_for_item(self)
  32. self.set_customer_address()
  33. self.validate_for_duplicate_items()
  34. self.validate_target_warehouse()
  35. self.validate_auto_repeat_subscription_dates()
  36. def set_missing_values(self, for_validate=False):
  37. super(SellingController, self).set_missing_values(for_validate)
  38. # set contact and address details for customer, if they are not mentioned
  39. self.set_missing_lead_customer_details(for_validate=for_validate)
  40. self.set_price_list_and_item_details(for_validate=for_validate)
  41. def set_missing_lead_customer_details(self, for_validate=False):
  42. customer, lead = None, None
  43. if getattr(self, "customer", None):
  44. customer = self.customer
  45. elif self.doctype == "Opportunity" and self.party_name:
  46. if self.opportunity_from == "Customer":
  47. customer = self.party_name
  48. else:
  49. lead = self.party_name
  50. elif self.doctype == "Quotation" and self.party_name:
  51. if self.quotation_to == "Customer":
  52. customer = self.party_name
  53. else:
  54. lead = self.party_name
  55. if customer:
  56. from erpnext.accounts.party import _get_party_details
  57. fetch_payment_terms_template = False
  58. if self.get("__islocal") or self.company != frappe.db.get_value(
  59. self.doctype, self.name, "company"
  60. ):
  61. fetch_payment_terms_template = True
  62. party_details = _get_party_details(
  63. customer,
  64. ignore_permissions=self.flags.ignore_permissions,
  65. doctype=self.doctype,
  66. company=self.company,
  67. posting_date=self.get("posting_date"),
  68. fetch_payment_terms_template=fetch_payment_terms_template,
  69. party_address=self.customer_address,
  70. shipping_address=self.shipping_address_name,
  71. company_address=self.get("company_address"),
  72. )
  73. if not self.meta.get_field("sales_team"):
  74. party_details.pop("sales_team")
  75. self.update_if_missing(party_details)
  76. elif lead:
  77. from erpnext.crm.doctype.lead.lead import get_lead_details
  78. self.update_if_missing(
  79. get_lead_details(
  80. lead,
  81. posting_date=self.get("transaction_date") or self.get("posting_date"),
  82. company=self.company,
  83. )
  84. )
  85. if self.get("taxes_and_charges") and not self.get("taxes") and not for_validate:
  86. taxes = get_taxes_and_charges("Sales Taxes and Charges Template", self.taxes_and_charges)
  87. for tax in taxes:
  88. self.append("taxes", tax)
  89. def set_price_list_and_item_details(self, for_validate=False):
  90. self.set_price_list_currency("Selling")
  91. self.set_missing_item_details(for_validate=for_validate)
  92. def remove_shipping_charge(self):
  93. if self.shipping_rule:
  94. shipping_rule = frappe.get_doc("Shipping Rule", self.shipping_rule)
  95. existing_shipping_charge = self.get(
  96. "taxes",
  97. {
  98. "doctype": "Sales Taxes and Charges",
  99. "charge_type": "Actual",
  100. "account_head": shipping_rule.account,
  101. "cost_center": shipping_rule.cost_center,
  102. },
  103. )
  104. if existing_shipping_charge:
  105. self.get("taxes").remove(existing_shipping_charge[-1])
  106. self.calculate_taxes_and_totals()
  107. def set_total_in_words(self):
  108. from frappe.utils import money_in_words
  109. if self.meta.get_field("base_in_words"):
  110. base_amount = abs(
  111. self.base_grand_total if self.is_rounded_total_disabled() else self.base_rounded_total
  112. )
  113. self.base_in_words = money_in_words(base_amount, self.company_currency)
  114. if self.meta.get_field("in_words"):
  115. amount = abs(self.grand_total if self.is_rounded_total_disabled() else self.rounded_total)
  116. self.in_words = money_in_words(amount, self.currency)
  117. def calculate_commission(self):
  118. if not self.meta.get_field("commission_rate") or self.docstatus.is_submitted():
  119. return
  120. self.round_floats_in(self, ("amount_eligible_for_commission", "commission_rate"))
  121. if not (0 <= self.commission_rate <= 100.0):
  122. throw(
  123. "{} {}".format(
  124. _(self.meta.get_label("commission_rate")),
  125. _("must be between 0 and 100"),
  126. )
  127. )
  128. self.amount_eligible_for_commission = sum(
  129. item.base_net_amount for item in self.items if item.grant_commission
  130. )
  131. self.total_commission = flt(
  132. self.amount_eligible_for_commission * self.commission_rate / 100.0,
  133. self.precision("total_commission"),
  134. )
  135. def calculate_contribution(self):
  136. if not self.meta.get_field("sales_team"):
  137. return
  138. total = 0.0
  139. sales_team = self.get("sales_team")
  140. for sales_person in sales_team:
  141. self.round_floats_in(sales_person)
  142. sales_person.allocated_amount = flt(
  143. self.amount_eligible_for_commission * sales_person.allocated_percentage / 100.0,
  144. self.precision("allocated_amount", sales_person),
  145. )
  146. if sales_person.commission_rate:
  147. sales_person.incentives = flt(
  148. sales_person.allocated_amount * flt(sales_person.commission_rate) / 100.0,
  149. self.precision("incentives", sales_person),
  150. )
  151. total += sales_person.allocated_percentage
  152. if sales_team and total != 100.0:
  153. throw(_("Total allocated percentage for sales team should be 100"))
  154. def validate_max_discount(self):
  155. for d in self.get("items"):
  156. if d.item_code:
  157. discount = flt(frappe.get_cached_value("Item", d.item_code, "max_discount"))
  158. if discount and flt(d.discount_percentage) > discount:
  159. frappe.throw(_("Maximum discount for Item {0} is {1}%").format(d.item_code, discount))
  160. def set_qty_as_per_stock_uom(self):
  161. for d in self.get("items"):
  162. if d.meta.get_field("stock_qty"):
  163. if not d.conversion_factor:
  164. frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
  165. d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
  166. def validate_selling_price(self):
  167. def throw_message(idx, item_name, rate, ref_rate_field):
  168. throw(
  169. _(
  170. """Row #{0}: Selling rate for item {1} is lower than its {2}.
  171. Selling {3} should be atleast {4}.<br><br>Alternatively,
  172. you can disable selling price validation in {5} to bypass
  173. this validation."""
  174. ).format(
  175. idx,
  176. bold(item_name),
  177. bold(ref_rate_field),
  178. bold("net rate"),
  179. bold(rate),
  180. get_link_to_form("Selling Settings", "Selling Settings"),
  181. ),
  182. title=_("Invalid Selling Price"),
  183. )
  184. if self.get("is_return") or not frappe.db.get_single_value(
  185. "Selling Settings", "validate_selling_price"
  186. ):
  187. return
  188. is_internal_customer = self.get("is_internal_customer")
  189. valuation_rate_map = {}
  190. for item in self.items:
  191. if not item.item_code or item.is_free_item:
  192. continue
  193. last_purchase_rate, is_stock_item = frappe.get_cached_value(
  194. "Item", item.item_code, ("last_purchase_rate", "is_stock_item")
  195. )
  196. last_purchase_rate_in_sales_uom = last_purchase_rate * (item.conversion_factor or 1)
  197. if flt(item.base_net_rate) < flt(last_purchase_rate_in_sales_uom):
  198. throw_message(item.idx, item.item_name, last_purchase_rate_in_sales_uom, "last purchase rate")
  199. if is_internal_customer or not is_stock_item:
  200. continue
  201. valuation_rate_map[(item.item_code, item.warehouse)] = None
  202. if not valuation_rate_map:
  203. return
  204. or_conditions = (
  205. f"""(item_code = {frappe.db.escape(valuation_rate[0])}
  206. and warehouse = {frappe.db.escape(valuation_rate[1])})"""
  207. for valuation_rate in valuation_rate_map
  208. )
  209. valuation_rates = frappe.db.sql(
  210. f"""
  211. select
  212. item_code, warehouse, valuation_rate
  213. from
  214. `tabBin`
  215. where
  216. ({" or ".join(or_conditions)})
  217. and valuation_rate > 0
  218. """,
  219. as_dict=True,
  220. )
  221. for rate in valuation_rates:
  222. valuation_rate_map[(rate.item_code, rate.warehouse)] = rate.valuation_rate
  223. for item in self.items:
  224. if not item.item_code or item.is_free_item:
  225. continue
  226. last_valuation_rate = valuation_rate_map.get((item.item_code, item.warehouse))
  227. if not last_valuation_rate:
  228. continue
  229. last_valuation_rate_in_sales_uom = last_valuation_rate * (item.conversion_factor or 1)
  230. if flt(item.base_net_rate) < flt(last_valuation_rate_in_sales_uom):
  231. throw_message(item.idx, item.item_name, last_valuation_rate_in_sales_uom, "valuation rate")
  232. def get_item_list(self):
  233. il = []
  234. for d in self.get("items"):
  235. if d.qty is None:
  236. frappe.throw(_("Row {0}: Qty is mandatory").format(d.idx))
  237. if self.has_product_bundle(d.item_code):
  238. for p in self.get("packed_items"):
  239. if p.parent_detail_docname == d.name and p.parent_item == d.item_code:
  240. # the packing details table's qty is already multiplied with parent's qty
  241. il.append(
  242. frappe._dict(
  243. {
  244. "warehouse": p.warehouse or d.warehouse,
  245. "item_code": p.item_code,
  246. "qty": flt(p.qty),
  247. "uom": p.uom,
  248. "batch_no": cstr(p.batch_no).strip(),
  249. "serial_no": cstr(p.serial_no).strip(),
  250. "name": d.name,
  251. "target_warehouse": p.target_warehouse,
  252. "company": self.company,
  253. "voucher_type": self.doctype,
  254. "allow_zero_valuation": d.allow_zero_valuation_rate,
  255. "sales_invoice_item": d.get("sales_invoice_item"),
  256. "dn_detail": d.get("dn_detail"),
  257. "incoming_rate": p.get("incoming_rate"),
  258. "item_row": p,
  259. }
  260. )
  261. )
  262. else:
  263. il.append(
  264. frappe._dict(
  265. {
  266. "warehouse": d.warehouse,
  267. "item_code": d.item_code,
  268. "qty": d.stock_qty,
  269. "uom": d.uom,
  270. "stock_uom": d.stock_uom,
  271. "conversion_factor": d.conversion_factor,
  272. "batch_no": cstr(d.get("batch_no")).strip(),
  273. "serial_no": cstr(d.get("serial_no")).strip(),
  274. "name": d.name,
  275. "target_warehouse": d.target_warehouse,
  276. "company": self.company,
  277. "voucher_type": self.doctype,
  278. "allow_zero_valuation": d.allow_zero_valuation_rate,
  279. "sales_invoice_item": d.get("sales_invoice_item"),
  280. "dn_detail": d.get("dn_detail"),
  281. "incoming_rate": d.get("incoming_rate"),
  282. "item_row": d,
  283. }
  284. )
  285. )
  286. return il
  287. def has_product_bundle(self, item_code):
  288. return frappe.db.sql(
  289. """select name from `tabProduct Bundle`
  290. where new_item_code=%s and docstatus != 2""",
  291. item_code,
  292. )
  293. def get_already_delivered_qty(self, current_docname, so, so_detail):
  294. delivered_via_dn = frappe.db.sql(
  295. """select sum(qty) from `tabDelivery Note Item`
  296. where so_detail = %s and docstatus = 1
  297. and against_sales_order = %s
  298. and parent != %s""",
  299. (so_detail, so, current_docname),
  300. )
  301. delivered_via_si = frappe.db.sql(
  302. """select sum(si_item.qty)
  303. from `tabSales Invoice Item` si_item, `tabSales Invoice` si
  304. where si_item.parent = si.name and si.update_stock = 1
  305. and si_item.so_detail = %s and si.docstatus = 1
  306. and si_item.sales_order = %s
  307. and si.name != %s""",
  308. (so_detail, so, current_docname),
  309. )
  310. total_delivered_qty = (flt(delivered_via_dn[0][0]) if delivered_via_dn else 0) + (
  311. flt(delivered_via_si[0][0]) if delivered_via_si else 0
  312. )
  313. return total_delivered_qty
  314. def get_so_qty_and_warehouse(self, so_detail):
  315. so_item = frappe.db.sql(
  316. """select qty, warehouse from `tabSales Order Item`
  317. where name = %s and docstatus = 1""",
  318. so_detail,
  319. as_dict=1,
  320. )
  321. so_qty = so_item and flt(so_item[0]["qty"]) or 0.0
  322. so_warehouse = so_item and so_item[0]["warehouse"] or ""
  323. return so_qty, so_warehouse
  324. def check_sales_order_on_hold_or_close(self, ref_fieldname):
  325. for d in self.get("items"):
  326. if d.get(ref_fieldname):
  327. status = frappe.db.get_value("Sales Order", d.get(ref_fieldname), "status")
  328. if status in ("Closed", "On Hold"):
  329. frappe.throw(_("Sales Order {0} is {1}").format(d.get(ref_fieldname), status))
  330. def update_reserved_qty(self):
  331. so_map = {}
  332. for d in self.get("items"):
  333. if d.so_detail:
  334. if self.doctype == "Delivery Note" and d.against_sales_order:
  335. so_map.setdefault(d.against_sales_order, []).append(d.so_detail)
  336. elif self.doctype == "Sales Invoice" and d.sales_order and self.update_stock:
  337. so_map.setdefault(d.sales_order, []).append(d.so_detail)
  338. for so, so_item_rows in so_map.items():
  339. if so and so_item_rows:
  340. sales_order = frappe.get_doc("Sales Order", so)
  341. if sales_order.status in ["Closed", "Cancelled"]:
  342. frappe.throw(
  343. _("{0} {1} is cancelled or closed").format(_("Sales Order"), so), frappe.InvalidStatusError
  344. )
  345. sales_order.update_reserved_qty(so_item_rows)
  346. def set_incoming_rate(self):
  347. if self.doctype not in ("Delivery Note", "Sales Invoice"):
  348. return
  349. items = self.get("items") + (self.get("packed_items") or [])
  350. for d in items:
  351. if not self.get("return_against"):
  352. # Get incoming rate based on original item cost based on valuation method
  353. qty = flt(d.get("stock_qty") or d.get("actual_qty"))
  354. if not (self.get("is_return") and d.incoming_rate):
  355. d.incoming_rate = get_incoming_rate(
  356. {
  357. "item_code": d.item_code,
  358. "warehouse": d.warehouse,
  359. "posting_date": self.get("posting_date") or self.get("transaction_date"),
  360. "posting_time": self.get("posting_time") or nowtime(),
  361. "qty": qty if cint(self.get("is_return")) else (-1 * qty),
  362. "serial_no": d.get("serial_no"),
  363. "batch_no": d.get("batch_no"),
  364. "company": self.company,
  365. "voucher_type": self.doctype,
  366. "voucher_no": self.name,
  367. "allow_zero_valuation": d.get("allow_zero_valuation"),
  368. },
  369. raise_error_if_no_rate=False,
  370. )
  371. # For internal transfers use incoming rate as the valuation rate
  372. if self.is_internal_transfer():
  373. if self.doctype == "Delivery Note" or self.get("update_stock"):
  374. if d.doctype == "Packed Item":
  375. incoming_rate = flt(
  376. flt(d.incoming_rate, d.precision("incoming_rate")) * d.conversion_factor,
  377. d.precision("incoming_rate"),
  378. )
  379. if d.incoming_rate != incoming_rate:
  380. d.incoming_rate = incoming_rate
  381. else:
  382. rate = flt(
  383. flt(d.incoming_rate, d.precision("incoming_rate")) * d.conversion_factor,
  384. d.precision("rate"),
  385. )
  386. if d.rate != rate:
  387. d.rate = rate
  388. frappe.msgprint(
  389. _(
  390. "Row {0}: Item rate has been updated as per valuation rate since its an internal stock transfer"
  391. ).format(d.idx),
  392. alert=1,
  393. )
  394. d.discount_percentage = 0.0
  395. d.discount_amount = 0.0
  396. d.margin_rate_or_amount = 0.0
  397. elif self.get("return_against"):
  398. # Get incoming rate of return entry from reference document
  399. # based on original item cost as per valuation method
  400. d.incoming_rate = get_rate_for_return(
  401. self.doctype, self.name, d.item_code, self.return_against, item_row=d
  402. )
  403. def update_stock_ledger(self):
  404. self.update_reserved_qty()
  405. sl_entries = []
  406. # Loop over items and packed items table
  407. for d in self.get_item_list():
  408. if frappe.get_cached_value("Item", d.item_code, "is_stock_item") == 1 and flt(d.qty):
  409. if flt(d.conversion_factor) == 0.0:
  410. d.conversion_factor = (
  411. get_conversion_factor(d.item_code, d.uom).get("conversion_factor") or 1.0
  412. )
  413. # On cancellation or return entry submission, make stock ledger entry for
  414. # target warehouse first, to update serial no values properly
  415. if d.warehouse and (
  416. (not cint(self.is_return) and self.docstatus == 1)
  417. or (cint(self.is_return) and self.docstatus == 2)
  418. ):
  419. sl_entries.append(self.get_sle_for_source_warehouse(d))
  420. if d.target_warehouse:
  421. sl_entries.append(self.get_sle_for_target_warehouse(d))
  422. if d.warehouse and (
  423. (not cint(self.is_return) and self.docstatus == 2)
  424. or (cint(self.is_return) and self.docstatus == 1)
  425. ):
  426. sl_entries.append(self.get_sle_for_source_warehouse(d))
  427. self.make_sl_entries(sl_entries)
  428. def get_sle_for_source_warehouse(self, item_row):
  429. sle = self.get_sl_entries(
  430. item_row,
  431. {
  432. "actual_qty": -1 * flt(item_row.qty),
  433. "incoming_rate": item_row.incoming_rate,
  434. "recalculate_rate": cint(self.is_return),
  435. },
  436. )
  437. if item_row.target_warehouse and not cint(self.is_return):
  438. sle.dependant_sle_voucher_detail_no = item_row.name
  439. return sle
  440. def get_sle_for_target_warehouse(self, item_row):
  441. sle = self.get_sl_entries(
  442. item_row, {"actual_qty": flt(item_row.qty), "warehouse": item_row.target_warehouse}
  443. )
  444. if self.docstatus == 1:
  445. if not cint(self.is_return):
  446. sle.update({"incoming_rate": item_row.incoming_rate, "recalculate_rate": 1})
  447. else:
  448. sle.update({"outgoing_rate": item_row.incoming_rate})
  449. if item_row.warehouse:
  450. sle.dependant_sle_voucher_detail_no = item_row.name
  451. return sle
  452. def set_po_nos(self, for_validate=False):
  453. if self.doctype == "Sales Invoice" and hasattr(self, "items"):
  454. if for_validate and self.po_no:
  455. return
  456. self.set_pos_for_sales_invoice()
  457. if self.doctype == "Delivery Note" and hasattr(self, "items"):
  458. if for_validate and self.po_no:
  459. return
  460. self.set_pos_for_delivery_note()
  461. def set_pos_for_sales_invoice(self):
  462. po_nos = []
  463. if self.po_no:
  464. po_nos.append(self.po_no)
  465. self.get_po_nos("Sales Order", "sales_order", po_nos)
  466. self.get_po_nos("Delivery Note", "delivery_note", po_nos)
  467. self.po_no = ", ".join(list(set(x.strip() for x in ",".join(po_nos).split(","))))
  468. def set_pos_for_delivery_note(self):
  469. po_nos = []
  470. if self.po_no:
  471. po_nos.append(self.po_no)
  472. self.get_po_nos("Sales Order", "against_sales_order", po_nos)
  473. self.get_po_nos("Sales Invoice", "against_sales_invoice", po_nos)
  474. self.po_no = ", ".join(list(set(x.strip() for x in ",".join(po_nos).split(","))))
  475. def get_po_nos(self, ref_doctype, ref_fieldname, po_nos):
  476. doc_list = list(set(d.get(ref_fieldname) for d in self.items if d.get(ref_fieldname)))
  477. if doc_list:
  478. po_nos += [
  479. d.po_no
  480. for d in frappe.get_all(ref_doctype, "po_no", filters={"name": ("in", doc_list)})
  481. if d.get("po_no")
  482. ]
  483. def set_gross_profit(self):
  484. if self.doctype in ["Sales Order", "Quotation"]:
  485. for item in self.items:
  486. item.gross_profit = flt(
  487. ((item.base_rate - item.valuation_rate) * item.stock_qty), self.precision("amount", item)
  488. )
  489. def set_customer_address(self):
  490. address_dict = {
  491. "customer_address": "address_display",
  492. "shipping_address_name": "shipping_address",
  493. "company_address": "company_address_display",
  494. "dispatch_address_name": "dispatch_address",
  495. }
  496. for address_field, address_display_field in address_dict.items():
  497. if self.get(address_field):
  498. self.set(address_display_field, get_address_display(self.get(address_field)))
  499. def validate_for_duplicate_items(self):
  500. check_list, chk_dupl_itm = [], []
  501. if cint(frappe.db.get_single_value("Selling Settings", "allow_multiple_items")):
  502. return
  503. if self.doctype == "Sales Invoice" and self.is_consolidated:
  504. return
  505. if self.doctype == "POS Invoice":
  506. return
  507. for d in self.get("items"):
  508. if self.doctype == "Sales Invoice":
  509. stock_items = [
  510. d.item_code,
  511. d.description,
  512. d.warehouse,
  513. d.sales_order or d.delivery_note,
  514. d.batch_no or "",
  515. ]
  516. non_stock_items = [d.item_code, d.description, d.sales_order or d.delivery_note]
  517. elif self.doctype == "Delivery Note":
  518. stock_items = [
  519. d.item_code,
  520. d.description,
  521. d.warehouse,
  522. d.against_sales_order or d.against_sales_invoice,
  523. d.batch_no or "",
  524. ]
  525. non_stock_items = [
  526. d.item_code,
  527. d.description,
  528. d.against_sales_order or d.against_sales_invoice,
  529. ]
  530. elif self.doctype in ["Sales Order", "Quotation"]:
  531. stock_items = [d.item_code, d.description, d.warehouse, ""]
  532. non_stock_items = [d.item_code, d.description]
  533. duplicate_items_msg = _("Item {0} entered multiple times.").format(frappe.bold(d.item_code))
  534. duplicate_items_msg += "<br><br>"
  535. duplicate_items_msg += _("Please enable {} in {} to allow same item in multiple rows").format(
  536. frappe.bold("Allow Item to Be Added Multiple Times in a Transaction"),
  537. get_link_to_form("Selling Settings", "Selling Settings"),
  538. )
  539. if frappe.db.get_value("Item", d.item_code, "is_stock_item") == 1:
  540. if stock_items in check_list:
  541. frappe.throw(duplicate_items_msg)
  542. else:
  543. check_list.append(stock_items)
  544. else:
  545. if non_stock_items in chk_dupl_itm:
  546. frappe.throw(duplicate_items_msg)
  547. else:
  548. chk_dupl_itm.append(non_stock_items)
  549. def validate_target_warehouse(self):
  550. items = self.get("items") + (self.get("packed_items") or [])
  551. for d in items:
  552. if d.get("target_warehouse") and d.get("warehouse") == d.get("target_warehouse"):
  553. warehouse = frappe.bold(d.get("target_warehouse"))
  554. frappe.throw(
  555. _("Row {0}: Delivery Warehouse ({1}) and Customer Warehouse ({2}) can not be same").format(
  556. d.idx, warehouse, warehouse
  557. )
  558. )
  559. if not self.get("is_internal_customer") and any(d.get("target_warehouse") for d in items):
  560. msg = _("Target Warehouse is set for some items but the customer is not an internal customer.")
  561. msg += " " + _("This {} will be treated as material transfer.").format(_(self.doctype))
  562. frappe.msgprint(msg, title="Internal Transfer", alert=True)
  563. def validate_items(self):
  564. # validate items to see if they have is_sales_item enabled
  565. from erpnext.controllers.buying_controller import validate_item_type
  566. validate_item_type(self, "is_sales_item", "sales")
  567. def set_default_income_account_for_item(obj):
  568. for d in obj.get("items"):
  569. if d.item_code:
  570. if getattr(d, "income_account", None):
  571. set_item_default(d.item_code, obj.company, "income_account", d.income_account)