blob: 974ade35849301ef7d4539d6b466d91a170c3376 [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
Anand Doshi756dca72013-01-15 18:39:21 +05303
4from __future__ import unicode_literals
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
6from frappe import _, msgprint
Nabin Hait5a834202017-10-05 19:51:10 +05307from frappe.utils import flt,cint, cstr, getdate
rohitwaghchaure4c688b72020-09-15 19:40:37 +05308from six import iteritems
Rohit Waghchaure8b829712021-04-03 14:20:30 +05309from collections import OrderedDict
Rushabh Mehtacc008cc2014-02-03 16:14:56 +053010from erpnext.accounts.party import get_party_details
Rushabh Mehta724f9e52014-10-07 15:29:58 +053011from erpnext.stock.get_item_details import get_conversion_factor
rohitwaghchaurefe226862017-12-28 16:11:27 +053012from erpnext.buying.utils import validate_for_items, update_last_purchase_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053013from erpnext.stock.stock_ledger import get_valuation_rate
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +053014from erpnext.stock.doctype.serial_no.serial_no import get_auto_serial_nos, auto_make_serial_nos, get_serial_nos
Rohit Waghchauref4dc7162018-11-15 17:04:02 +053015from frappe.contacts.doctype.address.address import get_address_display
Anand Doshi756dca72013-01-15 18:39:21 +053016
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +053017from erpnext.accounts.doctype.budget.budget import validate_expense_against_budget
Nabin Haita77b8c92020-12-21 14:45:50 +053018from erpnext.controllers.sales_and_purchase_return import get_rate_for_return
19from erpnext.stock.utils import get_incoming_rate
Nabin Haitbf495c92013-01-30 12:49:08 +053020
Rohit Waghchaure7b7ceaa2021-05-24 20:11:15 +053021from erpnext.controllers.stock_controller import StockController
22from erpnext.controllers.subcontracting import Subcontracting
23
24class BuyingController(StockController, Subcontracting):
Faris Ansaribc6a2b22020-10-27 19:42:58 +053025
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053026 def get_feed(self):
rohitwaghchaurea1064a62016-03-03 14:00:35 +053027 if self.get("supplier_name"):
28 return _("From {0} | {1} {2}").format(self.supplier_name, self.currency,
29 self.grand_total)
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053030
Saurabh6f753182013-03-20 12:55:28 +053031 def validate(self):
32 super(BuyingController, self).validate()
Nabin Hait365ae272014-04-03 17:38:54 +053033 if getattr(self, "supplier", None) and not self.supplier_name:
Nabin Hait1d218422015-07-17 15:19:02 +053034 self.supplier_name = frappe.db.get_value("Supplier", self.supplier, "supplier_name")
Rushabh Mehtaea0ff232016-07-07 14:02:26 +053035
Zarrarfc03a042018-06-04 12:52:52 +053036 self.validate_items()
nabinhait614fb752014-07-14 10:47:50 +053037 self.set_qty_as_per_stock_uom()
Nabin Hait205f7ce2013-04-26 13:35:06 +053038 self.validate_stock_or_nonstock_items()
Anand Doshi373680b2013-10-10 16:04:40 +053039 self.validate_warehouse()
Deepesh Garg15ff6a52020-02-18 12:28:41 +053040 self.validate_from_warehouse()
Rohit Waghchauref4dc7162018-11-15 17:04:02 +053041 self.set_supplier_address()
Saqib562fd0e2020-04-08 12:11:40 +053042 self.validate_asset_return()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053043
Nabin Hait14aa9c52016-04-18 15:54:01 +053044 if self.doctype=="Purchase Invoice":
45 self.validate_purchase_receipt_if_update_stock()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053046
Nabin Hait14aa9c52016-04-18 15:54:01 +053047 if self.doctype=="Purchase Receipt" or (self.doctype=="Purchase Invoice" and self.update_stock):
Rohit Waghchaure560ba392016-08-29 18:19:32 +053048 # self.validate_purchase_return()
Saurabhfbb342c2016-04-07 16:41:31 +053049 self.validate_rejected_warehouse()
50 self.validate_accepted_rejected_qty()
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053051 validate_for_items(self)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053052
Saurabhfbb342c2016-04-07 16:41:31 +053053 #sub-contracting
54 self.validate_for_subcontracting()
55 self.create_raw_materials_supplied("supplied_items")
56 self.set_landed_cost_voucher_amount()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053057
Nabin Hait14aa9c52016-04-18 15:54:01 +053058 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Nabin Haita77b8c92020-12-21 14:45:50 +053059 self.update_valuation_rate()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053060
Rohit Waghchaure110e1522021-06-15 17:29:52 +053061 def onload(self):
62 super(BuyingController, self).onload()
63 self.set_onload("backflush_based_on", frappe.db.get_single_value('Buying Settings',
64 'backflush_raw_materials_of_subcontract_based_on'))
65
Anand Doshi3543f302013-05-24 19:25:01 +053066 def set_missing_values(self, for_validate=False):
Anand Doshiabc10032013-06-14 17:44:03 +053067 super(BuyingController, self).set_missing_values(for_validate)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053068
Rushabh Mehta0b995402013-08-09 15:29:59 +053069 self.set_supplier_from_item_default()
Nabin Hait096d3632013-10-17 17:01:14 +053070 self.set_price_list_currency("Buying")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053071
Anand Doshi3543f302013-05-24 19:25:01 +053072 # set contact and address details for supplier, if they are not mentioned
Nabin Hait365ae272014-04-03 17:38:54 +053073 if getattr(self, "supplier", None):
Shreya Shah5615cb42018-10-07 11:42:07 +053074 self.update_if_missing(get_party_details(self.supplier, party_type="Supplier", ignore_permissions=self.flags.ignore_permissions,
Deepesh Gargbcf56e62021-08-06 23:53:16 +053075 doctype=self.doctype, company=self.company, party_address=self.supplier_address, shipping_address=self.get('shipping_address'),
76 fetch_payment_terms_template= not self.get('ignore_default_payment_terms_template')))
Rushabh Mehta886c9ef2013-07-08 12:08:06 +053077
Nabin Haitcccc45e2016-10-05 17:15:43 +053078 self.set_missing_item_details(for_validate)
Rushabh Mehta436467a2013-07-08 12:37:59 +053079
Rushabh Mehta0b995402013-08-09 15:29:59 +053080 def set_supplier_from_item_default(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +053081 if self.meta.get_field("supplier") and not self.supplier:
Nabin Haitdd38a262014-12-26 13:15:21 +053082 for d in self.get("items"):
Nabin Hait33df0b42018-05-26 09:09:02 +053083 supplier = frappe.db.get_value("Item Default",
84 {"parent": d.item_code, "company": self.company}, "default_supplier")
Rushabh Mehta0b995402013-08-09 15:29:59 +053085 if supplier:
Anand Doshif78d1ae2014-03-28 13:55:00 +053086 self.supplier = supplier
Shreya Shah3c9839f2018-07-17 18:01:44 +053087 else:
88 item_group = frappe.db.get_value("Item", d.item_code, "item_group")
89 supplier = frappe.db.get_value("Item Default",
90 {"parent": item_group, "company": self.company}, "default_supplier")
91 if supplier:
92 self.supplier = supplier
Rushabh Mehta0b995402013-08-09 15:29:59 +053093 break
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053094
Nabin Hait205f7ce2013-04-26 13:35:06 +053095 def validate_stock_or_nonstock_items(self):
Rohit Waghchaureaf059952018-05-07 18:46:53 +053096 if self.meta.get_field("taxes") and not self.get_stock_items() and not self.get_asset_items():
Deepesh Gargf17ea2c2020-12-11 21:30:39 +053097 msg = _('Tax Category has been changed to "Total" because all the Items are non-stock items')
98 self.update_tax_category(msg)
99
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530100 def update_tax_category(self, msg):
101 tax_for_valuation = [d for d in self.get("taxes")
Nabin Hait205f7ce2013-04-26 13:35:06 +0530102 if d.category in ["Valuation", "Valuation and Total"]]
tundebabzy9a346202017-06-16 11:00:14 +0100103
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530104 if tax_for_valuation:
105 for d in tax_for_valuation:
106 d.category = 'Total'
107
108 msgprint(msg)
Marica1c8cbd02020-05-02 17:55:15 +0530109
Saqib562fd0e2020-04-08 12:11:40 +0530110 def validate_asset_return(self):
111 if self.doctype not in ['Purchase Receipt', 'Purchase Invoice'] or not self.is_return:
112 return
113
114 purchase_doc_field = 'purchase_receipt' if self.doctype == 'Purchase Receipt' else 'purchase_invoice'
115 not_cancelled_asset = [d.name for d in frappe.db.get_all("Asset", {
116 purchase_doc_field: self.return_against,
117 "docstatus": 1
118 })]
119 if self.is_return and len(not_cancelled_asset):
Rohit Waghchaure103ecec2020-10-26 11:55:08 +0530120 frappe.throw(_("{} has submitted assets linked to it. You need to cancel the assets to create purchase return.")
121 .format(self.return_against), title=_("Not Allowed"))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530122
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530123 def get_asset_items(self):
Saqibd9956092019-11-18 11:46:55 +0530124 if self.doctype not in ['Purchase Order', 'Purchase Invoice', 'Purchase Receipt']:
Rohit Waghchaured644e6d2018-05-12 15:27:18 +0530125 return []
126
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530127 return [d.item_code for d in self.items if d.is_fixed_asset]
128
Saurabhfbb342c2016-04-07 16:41:31 +0530129 def set_landed_cost_voucher_amount(self):
130 for d in self.get("items"):
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530131 lc_voucher_data = frappe.db.sql("""select sum(applicable_charges), cost_center
Saurabhfbb342c2016-04-07 16:41:31 +0530132 from `tabLanded Cost Item`
133 where docstatus = 1 and purchase_receipt_item = %s""", d.name)
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530134 d.landed_cost_voucher_amount = lc_voucher_data[0][0] if lc_voucher_data else 0.0
135 if not d.cost_center and lc_voucher_data and lc_voucher_data[0][1]:
136 d.db_set('cost_center', lc_voucher_data[0][1])
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530137
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530138 def validate_from_warehouse(self):
139 for item in self.get('items'):
140 if item.get('from_warehouse') and (item.get('from_warehouse') == item.get('warehouse')):
141 frappe.throw(_("Row #{0}: Accepted Warehouse and Supplier Warehouse cannot be same").format(item.idx))
142
143 if item.get('from_warehouse') and self.get('is_subcontracted') == 'Yes':
144 frappe.throw(_("Row #{0}: Cannot select Supplier Warehouse while suppling raw materials to subcontractor").format(item.idx))
145
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530146 def set_supplier_address(self):
147 address_dict = {
148 'supplier_address': 'address_display',
149 'shipping_address': 'shipping_address_display'
150 }
151
152 for address_field, address_display_field in address_dict.items():
153 if self.get(address_field):
154 self.set(address_display_field, get_address_display(self.get(address_field)))
155
Nabin Haitd3b62502013-01-21 17:24:31 +0530156 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530157 from frappe.utils import money_in_words
Nabin Hait5690be12015-02-12 16:09:11 +0530158 if self.meta.get_field("base_in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530159 if self.meta.get_field("base_rounded_total") and not self.is_rounded_total_disabled():
160 amount = self.base_rounded_total
161 else:
162 amount = self.base_grand_total
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530163 self.base_in_words = money_in_words(amount, self.company_currency)
164
Nabin Hait5b4c2942013-01-22 11:12:02 +0530165 if self.meta.get_field("in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530166 if self.meta.get_field("rounded_total") and not self.is_rounded_total_disabled():
167 amount = self.rounded_total
168 else:
169 amount = self.grand_total
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530170
171 self.in_words = money_in_words(amount, self.currency)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530172
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530173 # update valuation rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530174 def update_valuation_rate(self, reset_outgoing_rate=True):
Anand Doshi8595fcf2013-02-08 19:28:14 +0530175 """
176 item_tax_amount is the total tax amount applied on that item
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530177 stored for valuation
178
Anand Doshi8595fcf2013-02-08 19:28:14 +0530179 TODO: rename item_tax_amount to valuation_tax_amount
180 """
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530181 stock_and_asset_items = []
Saqibd9956092019-11-18 11:46:55 +0530182 stock_and_asset_items = self.get_stock_items() + self.get_asset_items()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530183
Saqibd9956092019-11-18 11:46:55 +0530184 stock_and_asset_items_qty, stock_and_asset_items_amount = 0, 0
185 last_item_idx = 1
Nabin Haita77b8c92020-12-21 14:45:50 +0530186 for d in self.get("items"):
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530187 if (d.item_code and d.item_code in stock_and_asset_items):
Saqibd9956092019-11-18 11:46:55 +0530188 stock_and_asset_items_qty += flt(d.qty)
189 stock_and_asset_items_amount += flt(d.base_net_amount)
190 last_item_idx = d.idx
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530191
Ankush Menat98917802021-06-11 18:40:22 +0530192 total_valuation_amount = sum(flt(d.base_tax_amount_after_discount_amount) for d in self.get("taxes")
193 if d.category in ["Valuation", "Valuation and Total"])
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530194
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530195 valuation_amount_adjustment = total_valuation_amount
Nabin Haita77b8c92020-12-21 14:45:50 +0530196 for i, item in enumerate(self.get("items")):
Saqibd9956092019-11-18 11:46:55 +0530197 if item.item_code and item.qty and item.item_code in stock_and_asset_items:
198 item_proportion = flt(item.base_net_amount) / stock_and_asset_items_amount if stock_and_asset_items_amount \
199 else flt(item.qty) / stock_and_asset_items_qty
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530200
Saqibd9956092019-11-18 11:46:55 +0530201 if i == (last_item_idx - 1):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530202 item.item_tax_amount = flt(valuation_amount_adjustment,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530203 self.precision("item_tax_amount", item))
204 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530205 item.item_tax_amount = flt(item_proportion * total_valuation_amount,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530206 self.precision("item_tax_amount", item))
207 valuation_amount_adjustment -= item.item_tax_amount
208
Anand Doshi39384d32013-05-11 19:39:53 +0530209 self.round_floats_in(item)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530210 if flt(item.conversion_factor)==0.0:
bobzz-zoneb4c7bad2015-08-05 11:30:12 +0700211 item.conversion_factor = get_conversion_factor(item.item_code, item.uom).get("conversion_factor") or 1.0
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530212
Rushabh Mehta54047782013-12-26 11:07:46 +0530213 qty_in_stock_uom = flt(item.qty * item.conversion_factor)
Nabin Haita77b8c92020-12-21 14:45:50 +0530214 item.rm_supp_cost = self.get_supplied_items_cost(item.name, reset_outgoing_rate)
215 item.valuation_rate = ((item.base_net_amount + item.item_tax_amount + item.rm_supp_cost
216 + flt(item.landed_cost_voucher_amount)) / qty_in_stock_uom)
Anand Doshi4a7248e2013-02-27 18:10:30 +0530217 else:
Anand Doshi5af812a2013-05-10 19:23:02 +0530218 item.valuation_rate = 0.0
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530219
Deepesh Gargb4be2922021-01-28 13:09:56 +0530220 def set_incoming_rate(self):
221 if self.doctype not in ("Purchase Receipt", "Purchase Invoice", "Purchase Order"):
222 return
223
224 ref_doctype_map = {
225 "Purchase Order": "Sales Order Item",
226 "Purchase Receipt": "Delivery Note Item",
227 "Purchase Invoice": "Sales Invoice Item",
228 }
229
230 ref_doctype = ref_doctype_map.get(self.doctype)
231 items = self.get("items")
232 for d in items:
233 if not cint(self.get("is_return")):
234 # Get outgoing rate based on original item cost based on valuation method
235
236 if not d.get(frappe.scrub(ref_doctype)):
237 outgoing_rate = get_incoming_rate({
238 "item_code": d.item_code,
239 "warehouse": d.get('from_warehouse'),
240 "posting_date": self.get('posting_date') or self.get('transation_date'),
241 "posting_time": self.get('posting_time'),
242 "qty": -1 * flt(d.get('stock_qty')),
243 "serial_no": d.get('serial_no'),
244 "company": self.company,
245 "voucher_type": self.doctype,
246 "voucher_no": self.name,
247 "allow_zero_valuation": d.get("allow_zero_valuation")
248 }, raise_error_if_no_rate=False)
249
250 rate = flt(outgoing_rate * d.conversion_factor, d.precision('rate'))
251 else:
252 rate = frappe.db.get_value(ref_doctype, d.get(frappe.scrub(ref_doctype)), 'rate')
253
254 if self.is_internal_transfer():
255 if rate != d.rate:
256 d.rate = rate
257 d.discount_percentage = 0
258 d.discount_amount = 0
259 frappe.msgprint(_("Row {0}: Item rate has been updated as per valuation rate since its an internal stock transfer")
260 .format(d.idx), alert=1)
261
Nabin Haita77b8c92020-12-21 14:45:50 +0530262 def get_supplied_items_cost(self, item_row_id, reset_outgoing_rate=True):
263 supplied_items_cost = 0.0
264 for d in self.get("supplied_items"):
265 if d.reference_name == item_row_id:
Rohit Waghchaure7b7ceaa2021-05-24 20:11:15 +0530266 if reset_outgoing_rate and frappe.get_cached_value('Item', d.rm_item_code, 'is_stock_item'):
Nabin Haita77b8c92020-12-21 14:45:50 +0530267 rate = get_incoming_rate({
268 "item_code": d.rm_item_code,
269 "warehouse": self.supplier_warehouse,
270 "posting_date": self.posting_date,
271 "posting_time": self.posting_time,
272 "qty": -1 * d.consumed_qty,
273 "serial_no": d.serial_no
274 })
275
276 if rate > 0:
277 d.rate = rate
278
Nabin Haitb99c77b2020-12-25 18:12:35 +0530279 d.amount = flt(flt(d.consumed_qty) * flt(d.rate), d.precision("amount"))
Nabin Haita77b8c92020-12-21 14:45:50 +0530280 supplied_items_cost += flt(d.amount)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530281
Nabin Haita77b8c92020-12-21 14:45:50 +0530282 return supplied_items_cost
283
Nabin Hait54d209f2013-03-01 18:51:10 +0530284 def validate_for_subcontracting(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530285 if not self.is_subcontracted and self.sub_contracted_items:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530286 frappe.throw(_("Please enter 'Is Subcontracted' as Yes or No"))
287
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530288 if self.is_subcontracted == "Yes":
Saurabhfbb342c2016-04-07 16:41:31 +0530289 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] and not self.supplier_warehouse:
Afshan27bcb2a2021-03-09 22:25:48 +0530290 frappe.throw(_("Supplier Warehouse mandatory for sub-contracted {0}").format(self.doctype))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530291
Nabin Haitdd38a262014-12-26 13:15:21 +0530292 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530293 if item in self.sub_contracted_items and not item.bom:
294 frappe.throw(_("Please select BOM in BOM field for Item {0}").format(item.item_code))
295
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530296 if self.doctype != "Purchase Order":
297 return
pawan54465f52017-11-29 10:18:38 +0530298
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530299 for row in self.get("supplied_items"):
300 if not row.reserve_warehouse:
301 msg = f"Reserved Warehouse is mandatory for the Item {frappe.bold(row.rm_item_code)} in Raw Materials supplied"
302 frappe.throw(_(msg))
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530303 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530304 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530305 if item.bom:
306 item.bom = None
307
Nabin Hait344f4432014-05-08 19:08:20 +0530308 def create_raw_materials_supplied(self, raw_material_table):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530309 if self.is_subcontracted=="Yes":
Rohit Waghchaure7b7ceaa2021-05-24 20:11:15 +0530310 self.set_materials_for_subcontracted_items(raw_material_table)
Nabin Hait54d209f2013-03-01 18:51:10 +0530311
Saurabhfbb342c2016-04-07 16:41:31 +0530312 elif self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Haitdd38a262014-12-26 13:15:21 +0530313 for item in self.get("items"):
Nabin Haita0c239d2014-04-01 18:54:38 +0530314 item.rm_supp_cost = 0.0
315
Rohit Waghchaure4b9d2f22017-02-16 15:53:40 +0530316 if self.is_subcontracted == "No" and self.get("supplied_items"):
317 self.set('supplied_items', [])
318
Nabin Hait5418d712013-02-27 18:11:17 +0530319 @property
320 def sub_contracted_items(self):
321 if not hasattr(self, "_sub_contracted_items"):
Nabin Haitebd51442013-04-23 15:36:26 +0530322 self._sub_contracted_items = []
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530323 item_codes = list(set(item.item_code for item in
Nabin Haitdd38a262014-12-26 13:15:21 +0530324 self.get("items")))
Nabin Haitebd51442013-04-23 15:36:26 +0530325 if item_codes:
Suraj Shetty9d6d95c2019-11-29 13:26:52 +0530326 items = frappe.get_all('Item', filters={
327 'name': ['in', item_codes],
328 'is_sub_contracted_item': 1
329 })
330 self._sub_contracted_items = [item.name for item in items]
Nabin Hait5418d712013-02-27 18:11:17 +0530331
332 return self._sub_contracted_items
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530333
nabinhait614fb752014-07-14 10:47:50 +0530334 def set_qty_as_per_stock_uom(self):
Nabin Haitdd38a262014-12-26 13:15:21 +0530335 for d in self.get("items"):
Nabin Haitfd4bcd82015-05-22 16:55:40 +0530336 if d.meta.get_field("stock_qty"):
Deepesh Garg8b0302b2019-08-05 10:14:19 +0530337 # Check if item code is present
338 # Conversion factor should not be mandatory for non itemized items
339 if not d.conversion_factor and d.item_code:
Nabin Haite6e456b2015-05-13 17:21:44 +0530340 frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
Rushabh Mehta5b51cc82014-07-21 18:25:45 +0530341 d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530342
marinationd6596a12020-11-02 15:07:48 +0530343 if self.doctype=="Purchase Receipt" and d.meta.get_field("received_stock_qty"):
344 # Set Received Qty in Stock UOM
345 d.received_stock_qty = flt(d.received_qty) * flt(d.conversion_factor, d.precision("conversion_factor"))
346
Saurabh130c57b2016-04-04 15:49:36 +0530347 def validate_purchase_return(self):
348 for d in self.get("items"):
349 if self.is_return and flt(d.rejected_qty) != 0:
350 frappe.throw(_("Row #{0}: Rejected Qty can not be entered in Purchase Return").format(d.idx))
351
352 # validate rate with ref PR
353
354 def validate_rejected_warehouse(self):
355 for d in self.get("items"):
356 if flt(d.rejected_qty) and not d.rejected_warehouse:
Saurabhfbb342c2016-04-07 16:41:31 +0530357 if self.rejected_warehouse:
358 d.rejected_warehouse = self.rejected_warehouse
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530359
Saurabh130c57b2016-04-04 15:49:36 +0530360 if not d.rejected_warehouse:
361 frappe.throw(_("Row #{0}: Rejected Warehouse is mandatory against rejected Item {1}").format(d.idx, d.item_code))
362
363 # validate accepted and rejected qty
364 def validate_accepted_rejected_qty(self):
365 for d in self.get("items"):
Saurabh4f4d0a82017-03-13 14:31:48 +0530366 self.validate_negative_quantity(d, ["received_qty","qty", "rejected_qty"])
Saurabh130c57b2016-04-04 15:49:36 +0530367 if not flt(d.received_qty) and flt(d.qty):
368 d.received_qty = flt(d.qty) - flt(d.rejected_qty)
369
370 elif not flt(d.qty) and flt(d.rejected_qty):
371 d.qty = flt(d.received_qty) - flt(d.rejected_qty)
372
373 elif not flt(d.rejected_qty):
374 d.rejected_qty = flt(d.received_qty) - flt(d.qty)
375
Mangesh-Khairnar8c621ab2019-06-26 11:10:17 +0530376 val = flt(d.qty) + flt(d.rejected_qty)
Saurabh130c57b2016-04-04 15:49:36 +0530377 # Check Received Qty = Accepted Qty + Rejected Qty
Mangesh-Khairnar8c621ab2019-06-26 11:10:17 +0530378 if (flt(val, d.precision("received_qty")) != flt(d.received_qty, d.precision("received_qty"))):
Saurabh130c57b2016-04-04 15:49:36 +0530379 frappe.throw(_("Accepted + Rejected Qty must be equal to Received quantity for Item {0}").format(d.item_code))
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530380
Saurabh4f4d0a82017-03-13 14:31:48 +0530381 def validate_negative_quantity(self, item_row, field_list):
382 if self.is_return:
383 return
384
385 item_row = item_row.as_dict()
386 for fieldname in field_list:
387 if flt(item_row[fieldname]) < 0:
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530388 frappe.throw(_("Row #{0}: {1} can not be negative for item {2}").format(item_row['idx'],
389 frappe.get_meta(item_row.doctype).get_label(fieldname), item_row['item_code']))
Saurabh4f4d0a82017-03-13 14:31:48 +0530390
Mangesh-Khairnar5e474f42019-03-06 14:46:38 +0530391 def check_for_on_hold_or_closed_status(self, ref_doctype, ref_fieldname):
392 for d in self.get("items"):
393 if d.get(ref_fieldname):
394 status = frappe.db.get_value(ref_doctype, d.get(ref_fieldname), "status")
395 if status in ("Closed", "On Hold"):
396 frappe.throw(_("{0} {1} is {2}").format(ref_doctype,d.get(ref_fieldname), status))
397
Saurabhe29248b2016-04-04 11:55:52 +0530398 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait07e53762018-01-05 18:19:59 +0530399 self.update_ordered_and_reserved_qty()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530400
Saurabhe29248b2016-04-04 11:55:52 +0530401 sl_entries = []
402 stock_items = self.get_stock_items()
403
404 for d in self.get('items'):
405 if d.item_code in stock_items and d.warehouse:
406 pr_qty = flt(d.qty) * flt(d.conversion_factor)
407
408 if pr_qty:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530409
410 if d.from_warehouse and ((not cint(self.is_return) and self.docstatus==1)
411 or (cint(self.is_return) and self.docstatus==2)):
412 from_warehouse_sle = self.get_sl_entries(d, {
413 "actual_qty": -1 * pr_qty,
Nabin Haita77b8c92020-12-21 14:45:50 +0530414 "warehouse": d.from_warehouse,
Deepesh Gargb4be2922021-01-28 13:09:56 +0530415 "outgoing_rate": d.rate,
416 "recalculate_rate": 1,
Nabin Haita77b8c92020-12-21 14:45:50 +0530417 "dependant_sle_voucher_detail_no": d.name
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530418 })
419
420 sl_entries.append(from_warehouse_sle)
421
Saurabhe29248b2016-04-04 11:55:52 +0530422 sle = self.get_sl_entries(d, {
423 "actual_qty": flt(pr_qty),
424 "serial_no": cstr(d.serial_no).strip()
425 })
426 if self.is_return:
Nabin Haita77b8c92020-12-21 14:45:50 +0530427 outgoing_rate = get_rate_for_return(self.doctype, self.name, d.item_code, self.return_against, item_row=d)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530428
Saurabhe29248b2016-04-04 11:55:52 +0530429 sle.update({
Nabin Haita77b8c92020-12-21 14:45:50 +0530430 "outgoing_rate": outgoing_rate,
431 "recalculate_rate": 1
Saurabhe29248b2016-04-04 11:55:52 +0530432 })
Nabin Haita77b8c92020-12-21 14:45:50 +0530433 if d.from_warehouse:
434 sle.dependant_sle_voucher_detail_no = d.name
Saurabhe29248b2016-04-04 11:55:52 +0530435 else:
Nabin Haitb81ed452016-05-11 12:52:31 +0530436 val_rate_db_precision = 6 if cint(self.precision("valuation_rate", d)) <= 6 else 9
437 incoming_rate = flt(d.valuation_rate, val_rate_db_precision)
Saurabhe29248b2016-04-04 11:55:52 +0530438 sle.update({
Nabin Haita77b8c92020-12-21 14:45:50 +0530439 "incoming_rate": incoming_rate,
440 "recalculate_rate": 1 if (self.is_subcontracted and d.bom) or d.from_warehouse else 0
Saurabhe29248b2016-04-04 11:55:52 +0530441 })
442 sl_entries.append(sle)
443
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530444 if d.from_warehouse and ((not cint(self.is_return) and self.docstatus==2)
445 or (cint(self.is_return) and self.docstatus==1)):
446 from_warehouse_sle = self.get_sl_entries(d, {
447 "actual_qty": -1 * pr_qty,
Nabin Haita77b8c92020-12-21 14:45:50 +0530448 "warehouse": d.from_warehouse,
449 "recalculate_rate": 1
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530450 })
451
452 sl_entries.append(from_warehouse_sle)
453
Rohit Waghchaure560ba392016-08-29 18:19:32 +0530454 if flt(d.rejected_qty) != 0:
Saurabhe29248b2016-04-04 11:55:52 +0530455 sl_entries.append(self.get_sl_entries(d, {
456 "warehouse": d.rejected_warehouse,
457 "actual_qty": flt(d.rejected_qty) * flt(d.conversion_factor),
458 "serial_no": cstr(d.rejected_serial_no).strip(),
459 "incoming_rate": 0.0
460 }))
461
462 self.make_sl_entries_for_supplier_warehouse(sl_entries)
463 self.make_sl_entries(sl_entries, allow_negative_stock=allow_negative_stock,
464 via_landed_cost_voucher=via_landed_cost_voucher)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530465
Nabin Hait07e53762018-01-05 18:19:59 +0530466 def update_ordered_and_reserved_qty(self):
Nabin Hait14aa9c52016-04-18 15:54:01 +0530467 po_map = {}
468 for d in self.get("items"):
469 if self.doctype=="Purchase Receipt" \
Rohit Waghchaurea71d9d32016-07-05 00:34:00 +0530470 and d.purchase_order:
471 po_map.setdefault(d.purchase_order, []).append(d.purchase_order_item)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530472
Nabin Hait14aa9c52016-04-18 15:54:01 +0530473 elif self.doctype=="Purchase Invoice" and d.purchase_order and d.po_detail:
474 po_map.setdefault(d.purchase_order, []).append(d.po_detail)
475
476 for po, po_item_rows in po_map.items():
477 if po and po_item_rows:
478 po_obj = frappe.get_doc("Purchase Order", po)
479
480 if po_obj.status in ["Closed", "Cancelled"]:
481 frappe.throw(_("{0} {1} is cancelled or closed").format(_("Purchase Order"), po),
482 frappe.InvalidStatusError)
483
484 po_obj.update_ordered_qty(po_item_rows)
Nabin Hait07e53762018-01-05 18:19:59 +0530485 if self.is_subcontracted:
486 po_obj.update_reserved_qty_for_subcontract()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530487
Saurabhe29248b2016-04-04 11:55:52 +0530488 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
489 if hasattr(self, 'supplied_items'):
490 for d in self.get('supplied_items'):
491 # negative quantity is passed, as raw material qty has to be decreased
492 # when PR is submitted and it has to be increased when PR is cancelled
493 sl_entries.append(self.get_sl_entries(d, {
494 "item_code": d.rm_item_code,
495 "warehouse": self.supplier_warehouse,
496 "actual_qty": -1*flt(d.consumed_qty),
Nabin Haita77b8c92020-12-21 14:45:50 +0530497 "dependant_sle_voucher_detail_no": d.reference_name
Saurabhe29248b2016-04-04 11:55:52 +0530498 }))
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530499
rohitwaghchaurefe226862017-12-28 16:11:27 +0530500 def on_submit(self):
501 if self.get('is_return'):
502 return
503
Rohit Waghchaureab842542018-04-26 19:18:29 +0530504 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530505 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
506
507 self.process_fixed_asset()
508 self.update_fixed_asset(field)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530509
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530510 if self.doctype in ['Purchase Order', 'Purchase Receipt']:
511 update_last_purchase_rate(self, is_submit = 1)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530512
513 def on_cancel(self):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +0530514 super(BuyingController, self).on_cancel()
515
rohitwaghchaurefe226862017-12-28 16:11:27 +0530516 if self.get('is_return'):
517 return
518
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530519 if self.doctype in ['Purchase Order', 'Purchase Receipt']:
520 update_last_purchase_rate(self, is_submit = 0)
521
Rohit Waghchaureab842542018-04-26 19:18:29 +0530522 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530523 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
524
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530525 self.delete_linked_asset()
526 self.update_fixed_asset(field, delete_asset=True)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530527
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530528 def validate_budget(self):
529 if self.docstatus == 1:
530 for data in self.get('items'):
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530531 args = data.as_dict()
532 args.update({
533 'doctype': self.doctype,
rohitwaghchaure34c18772018-06-25 10:31:08 +0530534 'company': self.company,
535 'posting_date': (self.schedule_date
536 if self.doctype == 'Material Request' else self.transaction_date)
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530537 })
538
539 validate_expense_against_budget(args)
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530540
Rohit Waghchaureab842542018-04-26 19:18:29 +0530541 def process_fixed_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530542 if self.doctype == 'Purchase Invoice' and not self.update_stock:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530543 return
544
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530545 asset_items = self.get_asset_items()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530546 if asset_items:
Saqibd9956092019-11-18 11:46:55 +0530547 self.auto_make_assets(asset_items)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530548
Saqibd9956092019-11-18 11:46:55 +0530549 def auto_make_assets(self, asset_items):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530550 items_data = get_asset_item_details(asset_items)
Saqibf37a46e2019-11-22 16:32:50 +0530551 messages = []
Rohit Waghchaureab842542018-04-26 19:18:29 +0530552
553 for d in self.items:
554 if d.is_fixed_asset:
555 item_data = items_data.get(d.item_code)
556
Saqibd9956092019-11-18 11:46:55 +0530557 if item_data.get('auto_create_assets'):
558 # If asset has to be auto created
559 # Check for asset naming series
560 if item_data.get('asset_naming_series'):
Saqibbba78f02020-03-31 10:49:44 +0530561 created_assets = []
562
Saqibd9956092019-11-18 11:46:55 +0530563 for qty in range(cint(d.qty)):
Saqibbba78f02020-03-31 10:49:44 +0530564 asset = self.make_asset(d)
565 created_assets.append(asset)
Marica1c8cbd02020-05-02 17:55:15 +0530566
Saqibbba78f02020-03-31 10:49:44 +0530567 if len(created_assets) > 5:
568 # dont show asset form links if more than 5 assets are created
Marica1c8cbd02020-05-02 17:55:15 +0530569 messages.append(_('{} Assets created for {}').format(len(created_assets), frappe.bold(d.item_code)))
Saqibbba78f02020-03-31 10:49:44 +0530570 else:
571 assets_link = list(map(lambda d: frappe.utils.get_link_to_form('Asset', d), created_assets))
572 assets_link = frappe.bold(','.join(assets_link))
573
574 is_plural = 's' if len(created_assets) != 1 else ''
575 messages.append(
576 _('Asset{} {assets_link} created for {}').format(is_plural, frappe.bold(d.item_code), assets_link=assets_link)
577 )
Saqibd9956092019-11-18 11:46:55 +0530578 else:
Saqibbba78f02020-03-31 10:49:44 +0530579 frappe.throw(_("Row {}: Asset Naming Series is mandatory for the auto creation for item {}")
580 .format(d.idx, frappe.bold(d.item_code)))
Saqibd9956092019-11-18 11:46:55 +0530581 else:
Saqibbba78f02020-03-31 10:49:44 +0530582 messages.append(_("Assets not created for {0}. You will have to create asset manually.")
583 .format(frappe.bold(d.item_code)))
Saqibf37a46e2019-11-22 16:32:50 +0530584
585 for message in messages:
Saqibbba78f02020-03-31 10:49:44 +0530586 frappe.msgprint(message, title="Success", indicator="green")
Rohit Waghchaureab842542018-04-26 19:18:29 +0530587
588 def make_asset(self, row):
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530589 if not row.asset_location:
590 frappe.throw(_("Row {0}: Enter location for the asset item {1}").format(row.idx, row.item_code))
591
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530592 item_data = frappe.db.get_value('Item',
593 row.item_code, ['asset_naming_series', 'asset_category'], as_dict=1)
594
Saqibd9956092019-11-18 11:46:55 +0530595 purchase_amount = flt(row.base_rate + row.item_tax_amount)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530596 asset = frappe.get_doc({
597 'doctype': 'Asset',
598 'item_code': row.item_code,
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530599 'asset_name': row.item_name,
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530600 'naming_series': item_data.get('asset_naming_series') or 'AST',
601 'asset_category': item_data.get('asset_category'),
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530602 'location': row.asset_location,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530603 'company': self.company,
thefalconx33c15cc8f2019-09-24 18:49:16 +0530604 'supplier': self.supplier,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530605 'purchase_date': self.posting_date,
Rohit Waghchaure0ea6fe42018-05-08 23:31:58 +0530606 'calculate_depreciation': 1,
Rohit Waghchaure16bc8532018-05-12 12:06:00 +0530607 'purchase_receipt_amount': purchase_amount,
608 'gross_purchase_amount': purchase_amount,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530609 'purchase_receipt': self.name if self.doctype == 'Purchase Receipt' else None,
610 'purchase_invoice': self.name if self.doctype == 'Purchase Invoice' else None
611 })
612
613 asset.flags.ignore_validate = True
614 asset.flags.ignore_mandatory = True
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530615 asset.set_missing_values()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530616 asset.insert()
617
Saqibbba78f02020-03-31 10:49:44 +0530618 return asset.name
619
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530620 def update_fixed_asset(self, field, delete_asset = False):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530621 for d in self.get("items"):
Saqibd9956092019-11-18 11:46:55 +0530622 if d.is_fixed_asset:
623 is_auto_create_enabled = frappe.db.get_value('Item', d.item_code, 'auto_create_assets')
624 assets = frappe.db.get_all('Asset', filters={ field : self.name, 'item_code' : d.item_code })
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530625
Saqibd9956092019-11-18 11:46:55 +0530626 for asset in assets:
627 asset = frappe.get_doc('Asset', asset.name)
628 if delete_asset and is_auto_create_enabled:
629 # need to delete movements to delete assets otherwise throws link exists error
Saqibcd3976f2019-11-25 12:24:34 +0530630 movements = frappe.db.sql(
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530631 """SELECT asm.name
Saqibcd3976f2019-11-25 12:24:34 +0530632 FROM `tabAsset Movement` asm, `tabAsset Movement Item` asm_item
633 WHERE asm_item.parent=asm.name and asm_item.asset=%s""", asset.name, as_dict=1)
Saqibd9956092019-11-18 11:46:55 +0530634 for movement in movements:
635 frappe.delete_doc('Asset Movement', movement.name, force=1)
636 frappe.delete_doc("Asset", asset.name, force=1)
637 continue
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530638
Saqibd9956092019-11-18 11:46:55 +0530639 if self.docstatus in [0, 1] and not asset.get(field):
640 asset.set(field, self.name)
641 asset.purchase_date = self.posting_date
642 asset.supplier = self.supplier
643 elif self.docstatus == 2:
Saqibcd3976f2019-11-25 12:24:34 +0530644 if asset.docstatus == 0:
645 asset.set(field, None)
646 asset.supplier = None
647 if asset.docstatus == 1 and delete_asset:
Rohit Waghchaure103ecec2020-10-26 11:55:08 +0530648 frappe.throw(_('Cannot cancel this document as it is linked with submitted asset {0}. Please cancel it to continue.')
649 .format(frappe.utils.get_link_to_form('Asset', asset.name)))
Rohit Waghchaureab842542018-04-26 19:18:29 +0530650
Saqibd9956092019-11-18 11:46:55 +0530651 asset.flags.ignore_validate_update_after_submit = True
652 asset.flags.ignore_mandatory = True
653 if asset.docstatus == 0:
654 asset.flags.ignore_validate = True
Rohit Waghchaureab842542018-04-26 19:18:29 +0530655
Saqibd9956092019-11-18 11:46:55 +0530656 asset.save()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530657
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530658 def delete_linked_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530659 if self.doctype == 'Purchase Invoice' and not self.get('update_stock'):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530660 return
661
Nabin Hait1e7c32b2018-09-26 18:01:00 +0530662 frappe.db.sql("delete from `tabAsset Movement` where reference_name=%s", self.name)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530663
Nabin Hait5a834202017-10-05 19:51:10 +0530664 def validate_schedule_date(self):
Sahil Khan34766c02018-12-20 18:50:24 +0530665 if not self.get("items"):
666 return
Nabin Haita1138612019-10-15 12:43:27 +0530667
18alantom2a20a032021-05-05 11:59:15 +0530668 if any(d.schedule_date for d in self.get("items")):
669 # Select earliest schedule_date.
670 self.schedule_date = min(d.schedule_date for d in self.get("items")
671 if d.schedule_date is not None)
Nabin Hait5a834202017-10-05 19:51:10 +0530672
673 if self.schedule_date:
674 for d in self.get('items'):
675 if not d.schedule_date:
676 d.schedule_date = self.schedule_date
677
Prateeksha Singhcbd06fd2018-01-05 21:28:01 +0530678 if (d.schedule_date and self.transaction_date and
679 getdate(d.schedule_date) < getdate(self.transaction_date)):
Nabin Hait96b264b2018-01-02 11:50:29 +0530680 frappe.throw(_("Row #{0}: Reqd by Date cannot be before Transaction Date").format(d.idx))
Nabin Hait5a834202017-10-05 19:51:10 +0530681 else:
Nabin Hait96b264b2018-01-02 11:50:29 +0530682 frappe.throw(_("Please enter Reqd by Date"))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530683
Zarrarfc03a042018-06-04 12:52:52 +0530684 def validate_items(self):
685 # validate items to see if they have is_purchase_item or is_subcontracted_item enabled
Nabin Hait0bef91c2018-06-18 16:33:48 +0530686 if self.doctype=="Material Request": return
Zarrarfc03a042018-06-04 12:52:52 +0530687
rohitwaghchaure50d8c4a2018-06-05 13:08:10 +0530688 if hasattr(self, "is_subcontracted") and self.is_subcontracted == 'Yes':
Zarrarfc03a042018-06-04 12:52:52 +0530689 validate_item_type(self, "is_sub_contracted_item", "subcontracted")
690 else:
691 validate_item_type(self, "is_purchase_item", "purchase")
692
Rohit Waghchaureab842542018-04-26 19:18:29 +0530693def get_asset_item_details(asset_items):
694 asset_items_data = {}
Saqibd9956092019-11-18 11:46:55 +0530695 for d in frappe.get_all('Item', fields = ["name", "auto_create_assets", "asset_naming_series"],
Rohit Waghchaureab842542018-04-26 19:18:29 +0530696 filters = {'name': ('in', asset_items)}):
697 asset_items_data.setdefault(d.name, d)
698
699 return asset_items_data
Ameya Shenoy873e28d2018-06-06 05:53:19 +0000700
Zarrarfc03a042018-06-04 12:52:52 +0530701def validate_item_type(doc, fieldname, message):
702 # iterate through items and check if they are valid sales or purchase items
Zarrar7c088ff2018-06-05 10:32:09 +0530703 items = [d.item_code for d in doc.items if d.item_code]
704
705 # No validation check inase of creating transaction using 'Opening Invoice Creation Tool'
706 if not items:
707 return
708
Suraj Shettybfc195d2018-09-21 10:20:52 +0530709 item_list = ", ".join(["%s" % frappe.db.escape(d) for d in items])
Zarrarfc03a042018-06-04 12:52:52 +0530710
711 invalid_items = [d[0] for d in frappe.db.sql("""
712 select item_code from tabItem where name in ({0}) and {1}=0
713 """.format(item_list, fieldname), as_list=True)]
714
715 if invalid_items:
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530716 items = ", ".join([d for d in invalid_items])
717
718 if len(invalid_items) > 1:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530719 error_message = _("Following items {0} are not marked as {1} item. You can enable them as {1} item from its Item master").format(items, message)
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530720 else:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530721 error_message = _("Following item {0} is not marked as {1} item. You can enable them as {1} item from its Item master").format(items, message)
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530722
723 frappe.throw(error_message)