blob: e0b3ad801ec41eb00a83f69207ddab6c080354e6 [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
Chillar Anand915b3432021-09-02 16:44:59 +05305
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05306import frappe
7from frappe import _, msgprint
Rohit Waghchauref4dc7162018-11-15 17:04:02 +05308from frappe.contacts.doctype.address.address import get_address_display
Chillar Anand915b3432021-09-02 16:44:59 +05309from frappe.utils import cint, cstr, flt, getdate
Anand Doshi756dca72013-01-15 18:39:21 +053010
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +053011from erpnext.accounts.doctype.budget.budget import validate_expense_against_budget
Chillar Anand915b3432021-09-02 16:44:59 +053012from erpnext.accounts.party import get_party_details
13from erpnext.buying.utils import update_last_purchase_rate, validate_for_items
Nabin Haita77b8c92020-12-21 14:45:50 +053014from erpnext.controllers.sales_and_purchase_return import get_rate_for_return
Rohit Waghchaure7b7ceaa2021-05-24 20:11:15 +053015from erpnext.controllers.stock_controller import StockController
16from erpnext.controllers.subcontracting import Subcontracting
Chillar Anand915b3432021-09-02 16:44:59 +053017from erpnext.stock.get_item_details import get_conversion_factor
18from erpnext.stock.utils import get_incoming_rate
19
Rohit Waghchaure7b7ceaa2021-05-24 20:11:15 +053020
21class BuyingController(StockController, Subcontracting):
Faris Ansaribc6a2b22020-10-27 19:42:58 +053022
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053023 def get_feed(self):
rohitwaghchaurea1064a62016-03-03 14:00:35 +053024 if self.get("supplier_name"):
25 return _("From {0} | {1} {2}").format(self.supplier_name, self.currency,
26 self.grand_total)
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053027
Saurabh6f753182013-03-20 12:55:28 +053028 def validate(self):
29 super(BuyingController, self).validate()
Nabin Hait365ae272014-04-03 17:38:54 +053030 if getattr(self, "supplier", None) and not self.supplier_name:
Nabin Hait1d218422015-07-17 15:19:02 +053031 self.supplier_name = frappe.db.get_value("Supplier", self.supplier, "supplier_name")
Rushabh Mehtaea0ff232016-07-07 14:02:26 +053032
Zarrarfc03a042018-06-04 12:52:52 +053033 self.validate_items()
nabinhait614fb752014-07-14 10:47:50 +053034 self.set_qty_as_per_stock_uom()
Nabin Hait205f7ce2013-04-26 13:35:06 +053035 self.validate_stock_or_nonstock_items()
Anand Doshi373680b2013-10-10 16:04:40 +053036 self.validate_warehouse()
Deepesh Garg15ff6a52020-02-18 12:28:41 +053037 self.validate_from_warehouse()
Rohit Waghchauref4dc7162018-11-15 17:04:02 +053038 self.set_supplier_address()
Saqib562fd0e2020-04-08 12:11:40 +053039 self.validate_asset_return()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053040
Nabin Hait14aa9c52016-04-18 15:54:01 +053041 if self.doctype=="Purchase Invoice":
42 self.validate_purchase_receipt_if_update_stock()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053043
Nabin Hait14aa9c52016-04-18 15:54:01 +053044 if self.doctype=="Purchase Receipt" or (self.doctype=="Purchase Invoice" and self.update_stock):
Rohit Waghchaure560ba392016-08-29 18:19:32 +053045 # self.validate_purchase_return()
Saurabhfbb342c2016-04-07 16:41:31 +053046 self.validate_rejected_warehouse()
47 self.validate_accepted_rejected_qty()
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053048 validate_for_items(self)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053049
Saurabhfbb342c2016-04-07 16:41:31 +053050 #sub-contracting
51 self.validate_for_subcontracting()
52 self.create_raw_materials_supplied("supplied_items")
53 self.set_landed_cost_voucher_amount()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053054
Nabin Hait14aa9c52016-04-18 15:54:01 +053055 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Nabin Haita77b8c92020-12-21 14:45:50 +053056 self.update_valuation_rate()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053057
Rohit Waghchaure110e1522021-06-15 17:29:52 +053058 def onload(self):
59 super(BuyingController, self).onload()
60 self.set_onload("backflush_based_on", frappe.db.get_single_value('Buying Settings',
61 'backflush_raw_materials_of_subcontract_based_on'))
62
Anand Doshi3543f302013-05-24 19:25:01 +053063 def set_missing_values(self, for_validate=False):
Anand Doshiabc10032013-06-14 17:44:03 +053064 super(BuyingController, self).set_missing_values(for_validate)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053065
Rushabh Mehta0b995402013-08-09 15:29:59 +053066 self.set_supplier_from_item_default()
Nabin Hait096d3632013-10-17 17:01:14 +053067 self.set_price_list_currency("Buying")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053068
Anand Doshi3543f302013-05-24 19:25:01 +053069 # set contact and address details for supplier, if they are not mentioned
Nabin Hait365ae272014-04-03 17:38:54 +053070 if getattr(self, "supplier", None):
Shreya Shah5615cb42018-10-07 11:42:07 +053071 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 +053072 doctype=self.doctype, company=self.company, party_address=self.supplier_address, shipping_address=self.get('shipping_address'),
73 fetch_payment_terms_template= not self.get('ignore_default_payment_terms_template')))
Rushabh Mehta886c9ef2013-07-08 12:08:06 +053074
Nabin Haitcccc45e2016-10-05 17:15:43 +053075 self.set_missing_item_details(for_validate)
Rushabh Mehta436467a2013-07-08 12:37:59 +053076
Rushabh Mehta0b995402013-08-09 15:29:59 +053077 def set_supplier_from_item_default(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +053078 if self.meta.get_field("supplier") and not self.supplier:
Nabin Haitdd38a262014-12-26 13:15:21 +053079 for d in self.get("items"):
Nabin Hait33df0b42018-05-26 09:09:02 +053080 supplier = frappe.db.get_value("Item Default",
81 {"parent": d.item_code, "company": self.company}, "default_supplier")
Rushabh Mehta0b995402013-08-09 15:29:59 +053082 if supplier:
Anand Doshif78d1ae2014-03-28 13:55:00 +053083 self.supplier = supplier
Shreya Shah3c9839f2018-07-17 18:01:44 +053084 else:
85 item_group = frappe.db.get_value("Item", d.item_code, "item_group")
86 supplier = frappe.db.get_value("Item Default",
87 {"parent": item_group, "company": self.company}, "default_supplier")
88 if supplier:
89 self.supplier = supplier
Rushabh Mehta0b995402013-08-09 15:29:59 +053090 break
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053091
Nabin Hait205f7ce2013-04-26 13:35:06 +053092 def validate_stock_or_nonstock_items(self):
Rohit Waghchaureaf059952018-05-07 18:46:53 +053093 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 +053094 msg = _('Tax Category has been changed to "Total" because all the Items are non-stock items')
95 self.update_tax_category(msg)
96
Deepesh Gargf17ea2c2020-12-11 21:30:39 +053097 def update_tax_category(self, msg):
98 tax_for_valuation = [d for d in self.get("taxes")
Nabin Hait205f7ce2013-04-26 13:35:06 +053099 if d.category in ["Valuation", "Valuation and Total"]]
tundebabzy9a346202017-06-16 11:00:14 +0100100
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530101 if tax_for_valuation:
102 for d in tax_for_valuation:
103 d.category = 'Total'
104
105 msgprint(msg)
Marica1c8cbd02020-05-02 17:55:15 +0530106
Saqib562fd0e2020-04-08 12:11:40 +0530107 def validate_asset_return(self):
108 if self.doctype not in ['Purchase Receipt', 'Purchase Invoice'] or not self.is_return:
109 return
110
111 purchase_doc_field = 'purchase_receipt' if self.doctype == 'Purchase Receipt' else 'purchase_invoice'
112 not_cancelled_asset = [d.name for d in frappe.db.get_all("Asset", {
113 purchase_doc_field: self.return_against,
114 "docstatus": 1
115 })]
116 if self.is_return and len(not_cancelled_asset):
Rohit Waghchaure103ecec2020-10-26 11:55:08 +0530117 frappe.throw(_("{} has submitted assets linked to it. You need to cancel the assets to create purchase return.")
118 .format(self.return_against), title=_("Not Allowed"))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530119
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530120 def get_asset_items(self):
Saqibd9956092019-11-18 11:46:55 +0530121 if self.doctype not in ['Purchase Order', 'Purchase Invoice', 'Purchase Receipt']:
Rohit Waghchaured644e6d2018-05-12 15:27:18 +0530122 return []
123
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530124 return [d.item_code for d in self.items if d.is_fixed_asset]
125
Saurabhfbb342c2016-04-07 16:41:31 +0530126 def set_landed_cost_voucher_amount(self):
127 for d in self.get("items"):
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530128 lc_voucher_data = frappe.db.sql("""select sum(applicable_charges), cost_center
Saurabhfbb342c2016-04-07 16:41:31 +0530129 from `tabLanded Cost Item`
130 where docstatus = 1 and purchase_receipt_item = %s""", d.name)
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530131 d.landed_cost_voucher_amount = lc_voucher_data[0][0] if lc_voucher_data else 0.0
132 if not d.cost_center and lc_voucher_data and lc_voucher_data[0][1]:
133 d.db_set('cost_center', lc_voucher_data[0][1])
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530134
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530135 def validate_from_warehouse(self):
136 for item in self.get('items'):
137 if item.get('from_warehouse') and (item.get('from_warehouse') == item.get('warehouse')):
138 frappe.throw(_("Row #{0}: Accepted Warehouse and Supplier Warehouse cannot be same").format(item.idx))
139
140 if item.get('from_warehouse') and self.get('is_subcontracted') == 'Yes':
141 frappe.throw(_("Row #{0}: Cannot select Supplier Warehouse while suppling raw materials to subcontractor").format(item.idx))
142
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530143 def set_supplier_address(self):
144 address_dict = {
145 'supplier_address': 'address_display',
146 'shipping_address': 'shipping_address_display'
147 }
148
149 for address_field, address_display_field in address_dict.items():
150 if self.get(address_field):
151 self.set(address_display_field, get_address_display(self.get(address_field)))
152
Nabin Haitd3b62502013-01-21 17:24:31 +0530153 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530154 from frappe.utils import money_in_words
Nabin Hait5690be12015-02-12 16:09:11 +0530155 if self.meta.get_field("base_in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530156 if self.meta.get_field("base_rounded_total") and not self.is_rounded_total_disabled():
157 amount = self.base_rounded_total
158 else:
159 amount = self.base_grand_total
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530160 self.base_in_words = money_in_words(amount, self.company_currency)
161
Nabin Hait5b4c2942013-01-22 11:12:02 +0530162 if self.meta.get_field("in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530163 if self.meta.get_field("rounded_total") and not self.is_rounded_total_disabled():
164 amount = self.rounded_total
165 else:
166 amount = self.grand_total
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530167
168 self.in_words = money_in_words(amount, self.currency)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530169
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530170 # update valuation rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530171 def update_valuation_rate(self, reset_outgoing_rate=True):
Anand Doshi8595fcf2013-02-08 19:28:14 +0530172 """
173 item_tax_amount is the total tax amount applied on that item
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530174 stored for valuation
175
Anand Doshi8595fcf2013-02-08 19:28:14 +0530176 TODO: rename item_tax_amount to valuation_tax_amount
177 """
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530178 stock_and_asset_items = []
Saqibd9956092019-11-18 11:46:55 +0530179 stock_and_asset_items = self.get_stock_items() + self.get_asset_items()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530180
Saqibd9956092019-11-18 11:46:55 +0530181 stock_and_asset_items_qty, stock_and_asset_items_amount = 0, 0
182 last_item_idx = 1
Nabin Haita77b8c92020-12-21 14:45:50 +0530183 for d in self.get("items"):
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530184 if (d.item_code and d.item_code in stock_and_asset_items):
Saqibd9956092019-11-18 11:46:55 +0530185 stock_and_asset_items_qty += flt(d.qty)
186 stock_and_asset_items_amount += flt(d.base_net_amount)
187 last_item_idx = d.idx
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530188
Ankush Menat98917802021-06-11 18:40:22 +0530189 total_valuation_amount = sum(flt(d.base_tax_amount_after_discount_amount) for d in self.get("taxes")
190 if d.category in ["Valuation", "Valuation and Total"])
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530191
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530192 valuation_amount_adjustment = total_valuation_amount
Nabin Haita77b8c92020-12-21 14:45:50 +0530193 for i, item in enumerate(self.get("items")):
Saqibd9956092019-11-18 11:46:55 +0530194 if item.item_code and item.qty and item.item_code in stock_and_asset_items:
195 item_proportion = flt(item.base_net_amount) / stock_and_asset_items_amount if stock_and_asset_items_amount \
196 else flt(item.qty) / stock_and_asset_items_qty
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530197
Saqibd9956092019-11-18 11:46:55 +0530198 if i == (last_item_idx - 1):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530199 item.item_tax_amount = flt(valuation_amount_adjustment,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530200 self.precision("item_tax_amount", item))
201 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530202 item.item_tax_amount = flt(item_proportion * total_valuation_amount,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530203 self.precision("item_tax_amount", item))
204 valuation_amount_adjustment -= item.item_tax_amount
205
Anand Doshi39384d32013-05-11 19:39:53 +0530206 self.round_floats_in(item)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530207 if flt(item.conversion_factor)==0.0:
bobzz-zoneb4c7bad2015-08-05 11:30:12 +0700208 item.conversion_factor = get_conversion_factor(item.item_code, item.uom).get("conversion_factor") or 1.0
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530209
Rushabh Mehta54047782013-12-26 11:07:46 +0530210 qty_in_stock_uom = flt(item.qty * item.conversion_factor)
Nabin Haita77b8c92020-12-21 14:45:50 +0530211 item.rm_supp_cost = self.get_supplied_items_cost(item.name, reset_outgoing_rate)
212 item.valuation_rate = ((item.base_net_amount + item.item_tax_amount + item.rm_supp_cost
213 + flt(item.landed_cost_voucher_amount)) / qty_in_stock_uom)
Anand Doshi4a7248e2013-02-27 18:10:30 +0530214 else:
Anand Doshi5af812a2013-05-10 19:23:02 +0530215 item.valuation_rate = 0.0
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530216
Deepesh Gargb4be2922021-01-28 13:09:56 +0530217 def set_incoming_rate(self):
218 if self.doctype not in ("Purchase Receipt", "Purchase Invoice", "Purchase Order"):
219 return
220
221 ref_doctype_map = {
222 "Purchase Order": "Sales Order Item",
223 "Purchase Receipt": "Delivery Note Item",
224 "Purchase Invoice": "Sales Invoice Item",
225 }
226
227 ref_doctype = ref_doctype_map.get(self.doctype)
228 items = self.get("items")
229 for d in items:
230 if not cint(self.get("is_return")):
231 # Get outgoing rate based on original item cost based on valuation method
232
233 if not d.get(frappe.scrub(ref_doctype)):
234 outgoing_rate = get_incoming_rate({
235 "item_code": d.item_code,
236 "warehouse": d.get('from_warehouse'),
237 "posting_date": self.get('posting_date') or self.get('transation_date'),
238 "posting_time": self.get('posting_time'),
239 "qty": -1 * flt(d.get('stock_qty')),
240 "serial_no": d.get('serial_no'),
241 "company": self.company,
242 "voucher_type": self.doctype,
243 "voucher_no": self.name,
244 "allow_zero_valuation": d.get("allow_zero_valuation")
245 }, raise_error_if_no_rate=False)
246
247 rate = flt(outgoing_rate * d.conversion_factor, d.precision('rate'))
248 else:
249 rate = frappe.db.get_value(ref_doctype, d.get(frappe.scrub(ref_doctype)), 'rate')
250
251 if self.is_internal_transfer():
252 if rate != d.rate:
253 d.rate = rate
254 d.discount_percentage = 0
255 d.discount_amount = 0
256 frappe.msgprint(_("Row {0}: Item rate has been updated as per valuation rate since its an internal stock transfer")
257 .format(d.idx), alert=1)
258
Nabin Haita77b8c92020-12-21 14:45:50 +0530259 def get_supplied_items_cost(self, item_row_id, reset_outgoing_rate=True):
260 supplied_items_cost = 0.0
261 for d in self.get("supplied_items"):
262 if d.reference_name == item_row_id:
Rohit Waghchaure7b7ceaa2021-05-24 20:11:15 +0530263 if reset_outgoing_rate and frappe.get_cached_value('Item', d.rm_item_code, 'is_stock_item'):
Nabin Haita77b8c92020-12-21 14:45:50 +0530264 rate = get_incoming_rate({
265 "item_code": d.rm_item_code,
266 "warehouse": self.supplier_warehouse,
267 "posting_date": self.posting_date,
268 "posting_time": self.posting_time,
269 "qty": -1 * d.consumed_qty,
270 "serial_no": d.serial_no
271 })
272
273 if rate > 0:
274 d.rate = rate
275
Nabin Haitb99c77b2020-12-25 18:12:35 +0530276 d.amount = flt(flt(d.consumed_qty) * flt(d.rate), d.precision("amount"))
Nabin Haita77b8c92020-12-21 14:45:50 +0530277 supplied_items_cost += flt(d.amount)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530278
Nabin Haita77b8c92020-12-21 14:45:50 +0530279 return supplied_items_cost
280
Nabin Hait54d209f2013-03-01 18:51:10 +0530281 def validate_for_subcontracting(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530282 if not self.is_subcontracted and self.sub_contracted_items:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530283 frappe.throw(_("Please enter 'Is Subcontracted' as Yes or No"))
284
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530285 if self.is_subcontracted == "Yes":
Saurabhfbb342c2016-04-07 16:41:31 +0530286 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] and not self.supplier_warehouse:
Afshan27bcb2a2021-03-09 22:25:48 +0530287 frappe.throw(_("Supplier Warehouse mandatory for sub-contracted {0}").format(self.doctype))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530288
Nabin Haitdd38a262014-12-26 13:15:21 +0530289 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530290 if item in self.sub_contracted_items and not item.bom:
291 frappe.throw(_("Please select BOM in BOM field for Item {0}").format(item.item_code))
292
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530293 if self.doctype != "Purchase Order":
294 return
pawan54465f52017-11-29 10:18:38 +0530295
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530296 for row in self.get("supplied_items"):
297 if not row.reserve_warehouse:
298 msg = f"Reserved Warehouse is mandatory for the Item {frappe.bold(row.rm_item_code)} in Raw Materials supplied"
299 frappe.throw(_(msg))
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530300 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530301 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530302 if item.bom:
303 item.bom = None
304
Nabin Hait344f4432014-05-08 19:08:20 +0530305 def create_raw_materials_supplied(self, raw_material_table):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530306 if self.is_subcontracted=="Yes":
Rohit Waghchaure7b7ceaa2021-05-24 20:11:15 +0530307 self.set_materials_for_subcontracted_items(raw_material_table)
Nabin Hait54d209f2013-03-01 18:51:10 +0530308
Saurabhfbb342c2016-04-07 16:41:31 +0530309 elif self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Haitdd38a262014-12-26 13:15:21 +0530310 for item in self.get("items"):
Nabin Haita0c239d2014-04-01 18:54:38 +0530311 item.rm_supp_cost = 0.0
312
Rohit Waghchaure4b9d2f22017-02-16 15:53:40 +0530313 if self.is_subcontracted == "No" and self.get("supplied_items"):
314 self.set('supplied_items', [])
315
Nabin Hait5418d712013-02-27 18:11:17 +0530316 @property
317 def sub_contracted_items(self):
318 if not hasattr(self, "_sub_contracted_items"):
Nabin Haitebd51442013-04-23 15:36:26 +0530319 self._sub_contracted_items = []
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530320 item_codes = list(set(item.item_code for item in
Nabin Haitdd38a262014-12-26 13:15:21 +0530321 self.get("items")))
Nabin Haitebd51442013-04-23 15:36:26 +0530322 if item_codes:
Suraj Shetty9d6d95c2019-11-29 13:26:52 +0530323 items = frappe.get_all('Item', filters={
324 'name': ['in', item_codes],
325 'is_sub_contracted_item': 1
326 })
327 self._sub_contracted_items = [item.name for item in items]
Nabin Hait5418d712013-02-27 18:11:17 +0530328
329 return self._sub_contracted_items
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530330
nabinhait614fb752014-07-14 10:47:50 +0530331 def set_qty_as_per_stock_uom(self):
Nabin Haitdd38a262014-12-26 13:15:21 +0530332 for d in self.get("items"):
Nabin Haitfd4bcd82015-05-22 16:55:40 +0530333 if d.meta.get_field("stock_qty"):
Deepesh Garg8b0302b2019-08-05 10:14:19 +0530334 # Check if item code is present
335 # Conversion factor should not be mandatory for non itemized items
336 if not d.conversion_factor and d.item_code:
Nabin Haite6e456b2015-05-13 17:21:44 +0530337 frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
Rushabh Mehta5b51cc82014-07-21 18:25:45 +0530338 d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530339
marinationd6596a12020-11-02 15:07:48 +0530340 if self.doctype=="Purchase Receipt" and d.meta.get_field("received_stock_qty"):
341 # Set Received Qty in Stock UOM
342 d.received_stock_qty = flt(d.received_qty) * flt(d.conversion_factor, d.precision("conversion_factor"))
343
Saurabh130c57b2016-04-04 15:49:36 +0530344 def validate_purchase_return(self):
345 for d in self.get("items"):
346 if self.is_return and flt(d.rejected_qty) != 0:
347 frappe.throw(_("Row #{0}: Rejected Qty can not be entered in Purchase Return").format(d.idx))
348
349 # validate rate with ref PR
350
351 def validate_rejected_warehouse(self):
352 for d in self.get("items"):
353 if flt(d.rejected_qty) and not d.rejected_warehouse:
Saurabhfbb342c2016-04-07 16:41:31 +0530354 if self.rejected_warehouse:
355 d.rejected_warehouse = self.rejected_warehouse
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530356
Saurabh130c57b2016-04-04 15:49:36 +0530357 if not d.rejected_warehouse:
358 frappe.throw(_("Row #{0}: Rejected Warehouse is mandatory against rejected Item {1}").format(d.idx, d.item_code))
359
360 # validate accepted and rejected qty
361 def validate_accepted_rejected_qty(self):
362 for d in self.get("items"):
Saurabh4f4d0a82017-03-13 14:31:48 +0530363 self.validate_negative_quantity(d, ["received_qty","qty", "rejected_qty"])
Saurabh130c57b2016-04-04 15:49:36 +0530364 if not flt(d.received_qty) and flt(d.qty):
365 d.received_qty = flt(d.qty) - flt(d.rejected_qty)
366
367 elif not flt(d.qty) and flt(d.rejected_qty):
368 d.qty = flt(d.received_qty) - flt(d.rejected_qty)
369
370 elif not flt(d.rejected_qty):
371 d.rejected_qty = flt(d.received_qty) - flt(d.qty)
372
Mangesh-Khairnar8c621ab2019-06-26 11:10:17 +0530373 val = flt(d.qty) + flt(d.rejected_qty)
Saurabh130c57b2016-04-04 15:49:36 +0530374 # Check Received Qty = Accepted Qty + Rejected Qty
Mangesh-Khairnar8c621ab2019-06-26 11:10:17 +0530375 if (flt(val, d.precision("received_qty")) != flt(d.received_qty, d.precision("received_qty"))):
Saurabh130c57b2016-04-04 15:49:36 +0530376 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 +0530377
Saurabh4f4d0a82017-03-13 14:31:48 +0530378 def validate_negative_quantity(self, item_row, field_list):
379 if self.is_return:
380 return
381
382 item_row = item_row.as_dict()
383 for fieldname in field_list:
384 if flt(item_row[fieldname]) < 0:
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530385 frappe.throw(_("Row #{0}: {1} can not be negative for item {2}").format(item_row['idx'],
386 frappe.get_meta(item_row.doctype).get_label(fieldname), item_row['item_code']))
Saurabh4f4d0a82017-03-13 14:31:48 +0530387
Mangesh-Khairnar5e474f42019-03-06 14:46:38 +0530388 def check_for_on_hold_or_closed_status(self, ref_doctype, ref_fieldname):
389 for d in self.get("items"):
390 if d.get(ref_fieldname):
391 status = frappe.db.get_value(ref_doctype, d.get(ref_fieldname), "status")
392 if status in ("Closed", "On Hold"):
393 frappe.throw(_("{0} {1} is {2}").format(ref_doctype,d.get(ref_fieldname), status))
394
Saurabhe29248b2016-04-04 11:55:52 +0530395 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait07e53762018-01-05 18:19:59 +0530396 self.update_ordered_and_reserved_qty()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530397
Saurabhe29248b2016-04-04 11:55:52 +0530398 sl_entries = []
399 stock_items = self.get_stock_items()
400
401 for d in self.get('items'):
402 if d.item_code in stock_items and d.warehouse:
403 pr_qty = flt(d.qty) * flt(d.conversion_factor)
404
405 if pr_qty:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530406
407 if d.from_warehouse and ((not cint(self.is_return) and self.docstatus==1)
408 or (cint(self.is_return) and self.docstatus==2)):
409 from_warehouse_sle = self.get_sl_entries(d, {
410 "actual_qty": -1 * pr_qty,
Nabin Haita77b8c92020-12-21 14:45:50 +0530411 "warehouse": d.from_warehouse,
Deepesh Gargb4be2922021-01-28 13:09:56 +0530412 "outgoing_rate": d.rate,
413 "recalculate_rate": 1,
Nabin Haita77b8c92020-12-21 14:45:50 +0530414 "dependant_sle_voucher_detail_no": d.name
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530415 })
416
417 sl_entries.append(from_warehouse_sle)
418
Saurabhe29248b2016-04-04 11:55:52 +0530419 sle = self.get_sl_entries(d, {
420 "actual_qty": flt(pr_qty),
421 "serial_no": cstr(d.serial_no).strip()
422 })
423 if self.is_return:
Nabin Haita77b8c92020-12-21 14:45:50 +0530424 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 +0530425
Saurabhe29248b2016-04-04 11:55:52 +0530426 sle.update({
Nabin Haita77b8c92020-12-21 14:45:50 +0530427 "outgoing_rate": outgoing_rate,
428 "recalculate_rate": 1
Saurabhe29248b2016-04-04 11:55:52 +0530429 })
Nabin Haita77b8c92020-12-21 14:45:50 +0530430 if d.from_warehouse:
431 sle.dependant_sle_voucher_detail_no = d.name
Saurabhe29248b2016-04-04 11:55:52 +0530432 else:
Nabin Haitb81ed452016-05-11 12:52:31 +0530433 val_rate_db_precision = 6 if cint(self.precision("valuation_rate", d)) <= 6 else 9
434 incoming_rate = flt(d.valuation_rate, val_rate_db_precision)
Saurabhe29248b2016-04-04 11:55:52 +0530435 sle.update({
Nabin Haita77b8c92020-12-21 14:45:50 +0530436 "incoming_rate": incoming_rate,
437 "recalculate_rate": 1 if (self.is_subcontracted and d.bom) or d.from_warehouse else 0
Saurabhe29248b2016-04-04 11:55:52 +0530438 })
439 sl_entries.append(sle)
440
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530441 if d.from_warehouse and ((not cint(self.is_return) and self.docstatus==2)
442 or (cint(self.is_return) and self.docstatus==1)):
443 from_warehouse_sle = self.get_sl_entries(d, {
444 "actual_qty": -1 * pr_qty,
Nabin Haita77b8c92020-12-21 14:45:50 +0530445 "warehouse": d.from_warehouse,
446 "recalculate_rate": 1
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530447 })
448
449 sl_entries.append(from_warehouse_sle)
450
Rohit Waghchaure560ba392016-08-29 18:19:32 +0530451 if flt(d.rejected_qty) != 0:
Saurabhe29248b2016-04-04 11:55:52 +0530452 sl_entries.append(self.get_sl_entries(d, {
453 "warehouse": d.rejected_warehouse,
454 "actual_qty": flt(d.rejected_qty) * flt(d.conversion_factor),
455 "serial_no": cstr(d.rejected_serial_no).strip(),
456 "incoming_rate": 0.0
457 }))
458
459 self.make_sl_entries_for_supplier_warehouse(sl_entries)
460 self.make_sl_entries(sl_entries, allow_negative_stock=allow_negative_stock,
461 via_landed_cost_voucher=via_landed_cost_voucher)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530462
Nabin Hait07e53762018-01-05 18:19:59 +0530463 def update_ordered_and_reserved_qty(self):
Nabin Hait14aa9c52016-04-18 15:54:01 +0530464 po_map = {}
465 for d in self.get("items"):
466 if self.doctype=="Purchase Receipt" \
Rohit Waghchaurea71d9d32016-07-05 00:34:00 +0530467 and d.purchase_order:
468 po_map.setdefault(d.purchase_order, []).append(d.purchase_order_item)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530469
Nabin Hait14aa9c52016-04-18 15:54:01 +0530470 elif self.doctype=="Purchase Invoice" and d.purchase_order and d.po_detail:
471 po_map.setdefault(d.purchase_order, []).append(d.po_detail)
472
473 for po, po_item_rows in po_map.items():
474 if po and po_item_rows:
475 po_obj = frappe.get_doc("Purchase Order", po)
476
477 if po_obj.status in ["Closed", "Cancelled"]:
478 frappe.throw(_("{0} {1} is cancelled or closed").format(_("Purchase Order"), po),
479 frappe.InvalidStatusError)
480
481 po_obj.update_ordered_qty(po_item_rows)
Nabin Hait07e53762018-01-05 18:19:59 +0530482 if self.is_subcontracted:
483 po_obj.update_reserved_qty_for_subcontract()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530484
Saurabhe29248b2016-04-04 11:55:52 +0530485 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
486 if hasattr(self, 'supplied_items'):
487 for d in self.get('supplied_items'):
488 # negative quantity is passed, as raw material qty has to be decreased
489 # when PR is submitted and it has to be increased when PR is cancelled
490 sl_entries.append(self.get_sl_entries(d, {
491 "item_code": d.rm_item_code,
492 "warehouse": self.supplier_warehouse,
493 "actual_qty": -1*flt(d.consumed_qty),
Nabin Haita77b8c92020-12-21 14:45:50 +0530494 "dependant_sle_voucher_detail_no": d.reference_name
Saurabhe29248b2016-04-04 11:55:52 +0530495 }))
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530496
rohitwaghchaurefe226862017-12-28 16:11:27 +0530497 def on_submit(self):
498 if self.get('is_return'):
499 return
500
Rohit Waghchaureab842542018-04-26 19:18:29 +0530501 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530502 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
503
504 self.process_fixed_asset()
505 self.update_fixed_asset(field)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530506
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530507 if self.doctype in ['Purchase Order', 'Purchase Receipt']:
508 update_last_purchase_rate(self, is_submit = 1)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530509
510 def on_cancel(self):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +0530511 super(BuyingController, self).on_cancel()
512
rohitwaghchaurefe226862017-12-28 16:11:27 +0530513 if self.get('is_return'):
514 return
515
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530516 if self.doctype in ['Purchase Order', 'Purchase Receipt']:
517 update_last_purchase_rate(self, is_submit = 0)
518
Rohit Waghchaureab842542018-04-26 19:18:29 +0530519 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530520 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
521
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530522 self.delete_linked_asset()
523 self.update_fixed_asset(field, delete_asset=True)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530524
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530525 def validate_budget(self):
526 if self.docstatus == 1:
527 for data in self.get('items'):
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530528 args = data.as_dict()
529 args.update({
530 'doctype': self.doctype,
rohitwaghchaure34c18772018-06-25 10:31:08 +0530531 'company': self.company,
532 'posting_date': (self.schedule_date
533 if self.doctype == 'Material Request' else self.transaction_date)
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530534 })
535
536 validate_expense_against_budget(args)
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530537
Rohit Waghchaureab842542018-04-26 19:18:29 +0530538 def process_fixed_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530539 if self.doctype == 'Purchase Invoice' and not self.update_stock:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530540 return
541
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530542 asset_items = self.get_asset_items()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530543 if asset_items:
Saqibd9956092019-11-18 11:46:55 +0530544 self.auto_make_assets(asset_items)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530545
Saqibd9956092019-11-18 11:46:55 +0530546 def auto_make_assets(self, asset_items):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530547 items_data = get_asset_item_details(asset_items)
Saqibf37a46e2019-11-22 16:32:50 +0530548 messages = []
Rohit Waghchaureab842542018-04-26 19:18:29 +0530549
550 for d in self.items:
551 if d.is_fixed_asset:
552 item_data = items_data.get(d.item_code)
553
Saqibd9956092019-11-18 11:46:55 +0530554 if item_data.get('auto_create_assets'):
555 # If asset has to be auto created
556 # Check for asset naming series
557 if item_data.get('asset_naming_series'):
Saqibbba78f02020-03-31 10:49:44 +0530558 created_assets = []
559
Saqibd9956092019-11-18 11:46:55 +0530560 for qty in range(cint(d.qty)):
Saqibbba78f02020-03-31 10:49:44 +0530561 asset = self.make_asset(d)
562 created_assets.append(asset)
Marica1c8cbd02020-05-02 17:55:15 +0530563
Saqibbba78f02020-03-31 10:49:44 +0530564 if len(created_assets) > 5:
565 # dont show asset form links if more than 5 assets are created
Marica1c8cbd02020-05-02 17:55:15 +0530566 messages.append(_('{} Assets created for {}').format(len(created_assets), frappe.bold(d.item_code)))
Saqibbba78f02020-03-31 10:49:44 +0530567 else:
568 assets_link = list(map(lambda d: frappe.utils.get_link_to_form('Asset', d), created_assets))
569 assets_link = frappe.bold(','.join(assets_link))
570
571 is_plural = 's' if len(created_assets) != 1 else ''
572 messages.append(
573 _('Asset{} {assets_link} created for {}').format(is_plural, frappe.bold(d.item_code), assets_link=assets_link)
574 )
Saqibd9956092019-11-18 11:46:55 +0530575 else:
Saqibbba78f02020-03-31 10:49:44 +0530576 frappe.throw(_("Row {}: Asset Naming Series is mandatory for the auto creation for item {}")
577 .format(d.idx, frappe.bold(d.item_code)))
Saqibd9956092019-11-18 11:46:55 +0530578 else:
Saqibbba78f02020-03-31 10:49:44 +0530579 messages.append(_("Assets not created for {0}. You will have to create asset manually.")
580 .format(frappe.bold(d.item_code)))
Saqibf37a46e2019-11-22 16:32:50 +0530581
582 for message in messages:
Saqibbba78f02020-03-31 10:49:44 +0530583 frappe.msgprint(message, title="Success", indicator="green")
Rohit Waghchaureab842542018-04-26 19:18:29 +0530584
585 def make_asset(self, row):
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530586 if not row.asset_location:
587 frappe.throw(_("Row {0}: Enter location for the asset item {1}").format(row.idx, row.item_code))
588
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530589 item_data = frappe.db.get_value('Item',
590 row.item_code, ['asset_naming_series', 'asset_category'], as_dict=1)
591
Saqibd9956092019-11-18 11:46:55 +0530592 purchase_amount = flt(row.base_rate + row.item_tax_amount)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530593 asset = frappe.get_doc({
594 'doctype': 'Asset',
595 'item_code': row.item_code,
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530596 'asset_name': row.item_name,
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530597 'naming_series': item_data.get('asset_naming_series') or 'AST',
598 'asset_category': item_data.get('asset_category'),
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530599 'location': row.asset_location,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530600 'company': self.company,
thefalconx33c15cc8f2019-09-24 18:49:16 +0530601 'supplier': self.supplier,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530602 'purchase_date': self.posting_date,
Rohit Waghchaure0ea6fe42018-05-08 23:31:58 +0530603 'calculate_depreciation': 1,
Rohit Waghchaure16bc8532018-05-12 12:06:00 +0530604 'purchase_receipt_amount': purchase_amount,
605 'gross_purchase_amount': purchase_amount,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530606 'purchase_receipt': self.name if self.doctype == 'Purchase Receipt' else None,
607 'purchase_invoice': self.name if self.doctype == 'Purchase Invoice' else None
608 })
609
610 asset.flags.ignore_validate = True
611 asset.flags.ignore_mandatory = True
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530612 asset.set_missing_values()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530613 asset.insert()
614
Saqibbba78f02020-03-31 10:49:44 +0530615 return asset.name
616
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530617 def update_fixed_asset(self, field, delete_asset = False):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530618 for d in self.get("items"):
Saqibd9956092019-11-18 11:46:55 +0530619 if d.is_fixed_asset:
620 is_auto_create_enabled = frappe.db.get_value('Item', d.item_code, 'auto_create_assets')
621 assets = frappe.db.get_all('Asset', filters={ field : self.name, 'item_code' : d.item_code })
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530622
Saqibd9956092019-11-18 11:46:55 +0530623 for asset in assets:
624 asset = frappe.get_doc('Asset', asset.name)
625 if delete_asset and is_auto_create_enabled:
626 # need to delete movements to delete assets otherwise throws link exists error
Saqibcd3976f2019-11-25 12:24:34 +0530627 movements = frappe.db.sql(
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530628 """SELECT asm.name
Saqibcd3976f2019-11-25 12:24:34 +0530629 FROM `tabAsset Movement` asm, `tabAsset Movement Item` asm_item
630 WHERE asm_item.parent=asm.name and asm_item.asset=%s""", asset.name, as_dict=1)
Saqibd9956092019-11-18 11:46:55 +0530631 for movement in movements:
632 frappe.delete_doc('Asset Movement', movement.name, force=1)
633 frappe.delete_doc("Asset", asset.name, force=1)
634 continue
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530635
Saqibd9956092019-11-18 11:46:55 +0530636 if self.docstatus in [0, 1] and not asset.get(field):
637 asset.set(field, self.name)
638 asset.purchase_date = self.posting_date
639 asset.supplier = self.supplier
640 elif self.docstatus == 2:
Saqibcd3976f2019-11-25 12:24:34 +0530641 if asset.docstatus == 0:
642 asset.set(field, None)
643 asset.supplier = None
644 if asset.docstatus == 1 and delete_asset:
Rohit Waghchaure103ecec2020-10-26 11:55:08 +0530645 frappe.throw(_('Cannot cancel this document as it is linked with submitted asset {0}. Please cancel it to continue.')
646 .format(frappe.utils.get_link_to_form('Asset', asset.name)))
Rohit Waghchaureab842542018-04-26 19:18:29 +0530647
Saqibd9956092019-11-18 11:46:55 +0530648 asset.flags.ignore_validate_update_after_submit = True
649 asset.flags.ignore_mandatory = True
650 if asset.docstatus == 0:
651 asset.flags.ignore_validate = True
Rohit Waghchaureab842542018-04-26 19:18:29 +0530652
Saqibd9956092019-11-18 11:46:55 +0530653 asset.save()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530654
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530655 def delete_linked_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530656 if self.doctype == 'Purchase Invoice' and not self.get('update_stock'):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530657 return
658
Nabin Hait1e7c32b2018-09-26 18:01:00 +0530659 frappe.db.sql("delete from `tabAsset Movement` where reference_name=%s", self.name)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530660
Nabin Hait5a834202017-10-05 19:51:10 +0530661 def validate_schedule_date(self):
Sahil Khan34766c02018-12-20 18:50:24 +0530662 if not self.get("items"):
663 return
Nabin Haita1138612019-10-15 12:43:27 +0530664
18alantom2a20a032021-05-05 11:59:15 +0530665 if any(d.schedule_date for d in self.get("items")):
666 # Select earliest schedule_date.
667 self.schedule_date = min(d.schedule_date for d in self.get("items")
668 if d.schedule_date is not None)
Nabin Hait5a834202017-10-05 19:51:10 +0530669
670 if self.schedule_date:
671 for d in self.get('items'):
672 if not d.schedule_date:
673 d.schedule_date = self.schedule_date
674
Prateeksha Singhcbd06fd2018-01-05 21:28:01 +0530675 if (d.schedule_date and self.transaction_date and
676 getdate(d.schedule_date) < getdate(self.transaction_date)):
Nabin Hait96b264b2018-01-02 11:50:29 +0530677 frappe.throw(_("Row #{0}: Reqd by Date cannot be before Transaction Date").format(d.idx))
Nabin Hait5a834202017-10-05 19:51:10 +0530678 else:
Nabin Hait96b264b2018-01-02 11:50:29 +0530679 frappe.throw(_("Please enter Reqd by Date"))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530680
Zarrarfc03a042018-06-04 12:52:52 +0530681 def validate_items(self):
682 # validate items to see if they have is_purchase_item or is_subcontracted_item enabled
Nabin Hait0bef91c2018-06-18 16:33:48 +0530683 if self.doctype=="Material Request": return
Zarrarfc03a042018-06-04 12:52:52 +0530684
rohitwaghchaure50d8c4a2018-06-05 13:08:10 +0530685 if hasattr(self, "is_subcontracted") and self.is_subcontracted == 'Yes':
Zarrarfc03a042018-06-04 12:52:52 +0530686 validate_item_type(self, "is_sub_contracted_item", "subcontracted")
687 else:
688 validate_item_type(self, "is_purchase_item", "purchase")
689
Rohit Waghchaureab842542018-04-26 19:18:29 +0530690def get_asset_item_details(asset_items):
691 asset_items_data = {}
Saqibd9956092019-11-18 11:46:55 +0530692 for d in frappe.get_all('Item', fields = ["name", "auto_create_assets", "asset_naming_series"],
Rohit Waghchaureab842542018-04-26 19:18:29 +0530693 filters = {'name': ('in', asset_items)}):
694 asset_items_data.setdefault(d.name, d)
695
696 return asset_items_data
Ameya Shenoy873e28d2018-06-06 05:53:19 +0000697
Zarrarfc03a042018-06-04 12:52:52 +0530698def validate_item_type(doc, fieldname, message):
699 # iterate through items and check if they are valid sales or purchase items
Zarrar7c088ff2018-06-05 10:32:09 +0530700 items = [d.item_code for d in doc.items if d.item_code]
701
702 # No validation check inase of creating transaction using 'Opening Invoice Creation Tool'
703 if not items:
704 return
705
Suraj Shettybfc195d2018-09-21 10:20:52 +0530706 item_list = ", ".join(["%s" % frappe.db.escape(d) for d in items])
Zarrarfc03a042018-06-04 12:52:52 +0530707
708 invalid_items = [d[0] for d in frappe.db.sql("""
709 select item_code from tabItem where name in ({0}) and {1}=0
710 """.format(item_list, fieldname), as_list=True)]
711
712 if invalid_items:
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530713 items = ", ".join([d for d in invalid_items])
714
715 if len(invalid_items) > 1:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530716 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 +0530717 else:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530718 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 +0530719
720 frappe.throw(error_message)