blob: f088b9ffc2240ac0262d849824224ae3bbab7d19 [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
Chillar Anand915b3432021-09-02 16:44:59 +05304
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
marination293f6cb2021-11-16 14:22:26 +05306from frappe import ValidationError, _, msgprint
Rohit Waghchauref4dc7162018-11-15 17:04:02 +05307from frappe.contacts.doctype.address.address import get_address_display
Chillar Anand915b3432021-09-02 16:44:59 +05308from frappe.utils import cint, cstr, flt, getdate
Anand Doshi756dca72013-01-15 18:39:21 +05309
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +053010from erpnext.accounts.doctype.budget.budget import validate_expense_against_budget
Chillar Anand915b3432021-09-02 16:44:59 +053011from erpnext.accounts.party import get_party_details
12from erpnext.buying.utils import update_last_purchase_rate, validate_for_items
Nabin Haita77b8c92020-12-21 14:45:50 +053013from erpnext.controllers.sales_and_purchase_return import get_rate_for_return
Rohit Waghchaure7b7ceaa2021-05-24 20:11:15 +053014from erpnext.controllers.stock_controller import StockController
15from erpnext.controllers.subcontracting import Subcontracting
Chillar Anand915b3432021-09-02 16:44:59 +053016from erpnext.stock.get_item_details import get_conversion_factor
17from erpnext.stock.utils import get_incoming_rate
18
marination293f6cb2021-11-16 14:22:26 +053019
20class QtyMismatchError(ValidationError):
21 pass
Rohit Waghchaure7b7ceaa2021-05-24 20:11:15 +053022
23class BuyingController(StockController, Subcontracting):
Faris Ansaribc6a2b22020-10-27 19:42:58 +053024
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053025 def get_feed(self):
rohitwaghchaurea1064a62016-03-03 14:00:35 +053026 if self.get("supplier_name"):
27 return _("From {0} | {1} {2}").format(self.supplier_name, self.currency,
28 self.grand_total)
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053029
Saurabh6f753182013-03-20 12:55:28 +053030 def validate(self):
31 super(BuyingController, self).validate()
Nabin Hait365ae272014-04-03 17:38:54 +053032 if getattr(self, "supplier", None) and not self.supplier_name:
Nabin Hait1d218422015-07-17 15:19:02 +053033 self.supplier_name = frappe.db.get_value("Supplier", self.supplier, "supplier_name")
Rushabh Mehtaea0ff232016-07-07 14:02:26 +053034
Zarrarfc03a042018-06-04 12:52:52 +053035 self.validate_items()
nabinhait614fb752014-07-14 10:47:50 +053036 self.set_qty_as_per_stock_uom()
Nabin Hait205f7ce2013-04-26 13:35:06 +053037 self.validate_stock_or_nonstock_items()
Anand Doshi373680b2013-10-10 16:04:40 +053038 self.validate_warehouse()
Deepesh Garg15ff6a52020-02-18 12:28:41 +053039 self.validate_from_warehouse()
Rohit Waghchauref4dc7162018-11-15 17:04:02 +053040 self.set_supplier_address()
Saqib562fd0e2020-04-08 12:11:40 +053041 self.validate_asset_return()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053042
Nabin Hait14aa9c52016-04-18 15:54:01 +053043 if self.doctype=="Purchase Invoice":
44 self.validate_purchase_receipt_if_update_stock()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053045
Nabin Hait14aa9c52016-04-18 15:54:01 +053046 if self.doctype=="Purchase Receipt" or (self.doctype=="Purchase Invoice" and self.update_stock):
Rohit Waghchaure560ba392016-08-29 18:19:32 +053047 # self.validate_purchase_return()
Saurabhfbb342c2016-04-07 16:41:31 +053048 self.validate_rejected_warehouse()
49 self.validate_accepted_rejected_qty()
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053050 validate_for_items(self)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053051
Saurabhfbb342c2016-04-07 16:41:31 +053052 #sub-contracting
53 self.validate_for_subcontracting()
54 self.create_raw_materials_supplied("supplied_items")
55 self.set_landed_cost_voucher_amount()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053056
Nabin Hait14aa9c52016-04-18 15:54:01 +053057 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Nabin Haita77b8c92020-12-21 14:45:50 +053058 self.update_valuation_rate()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053059
Rohit Waghchaure110e1522021-06-15 17:29:52 +053060 def onload(self):
61 super(BuyingController, self).onload()
62 self.set_onload("backflush_based_on", frappe.db.get_single_value('Buying Settings',
63 'backflush_raw_materials_of_subcontract_based_on'))
64
Anand Doshi3543f302013-05-24 19:25:01 +053065 def set_missing_values(self, for_validate=False):
Anand Doshiabc10032013-06-14 17:44:03 +053066 super(BuyingController, self).set_missing_values(for_validate)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053067
Rushabh Mehta0b995402013-08-09 15:29:59 +053068 self.set_supplier_from_item_default()
Nabin Hait096d3632013-10-17 17:01:14 +053069 self.set_price_list_currency("Buying")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053070
Anand Doshi3543f302013-05-24 19:25:01 +053071 # set contact and address details for supplier, if they are not mentioned
Nabin Hait365ae272014-04-03 17:38:54 +053072 if getattr(self, "supplier", None):
Shreya Shah5615cb42018-10-07 11:42:07 +053073 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 +053074 doctype=self.doctype, company=self.company, party_address=self.supplier_address, shipping_address=self.get('shipping_address'),
75 fetch_payment_terms_template= not self.get('ignore_default_payment_terms_template')))
Rushabh Mehta886c9ef2013-07-08 12:08:06 +053076
Nabin Haitcccc45e2016-10-05 17:15:43 +053077 self.set_missing_item_details(for_validate)
Rushabh Mehta436467a2013-07-08 12:37:59 +053078
Rushabh Mehta0b995402013-08-09 15:29:59 +053079 def set_supplier_from_item_default(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +053080 if self.meta.get_field("supplier") and not self.supplier:
Nabin Haitdd38a262014-12-26 13:15:21 +053081 for d in self.get("items"):
Nabin Hait33df0b42018-05-26 09:09:02 +053082 supplier = frappe.db.get_value("Item Default",
83 {"parent": d.item_code, "company": self.company}, "default_supplier")
Rushabh Mehta0b995402013-08-09 15:29:59 +053084 if supplier:
Anand Doshif78d1ae2014-03-28 13:55:00 +053085 self.supplier = supplier
Shreya Shah3c9839f2018-07-17 18:01:44 +053086 else:
87 item_group = frappe.db.get_value("Item", d.item_code, "item_group")
88 supplier = frappe.db.get_value("Item Default",
89 {"parent": item_group, "company": self.company}, "default_supplier")
90 if supplier:
91 self.supplier = supplier
Rushabh Mehta0b995402013-08-09 15:29:59 +053092 break
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053093
Nabin Hait205f7ce2013-04-26 13:35:06 +053094 def validate_stock_or_nonstock_items(self):
Rohit Waghchaureaf059952018-05-07 18:46:53 +053095 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 +053096 msg = _('Tax Category has been changed to "Total" because all the Items are non-stock items')
97 self.update_tax_category(msg)
98
Deepesh Gargf17ea2c2020-12-11 21:30:39 +053099 def update_tax_category(self, msg):
100 tax_for_valuation = [d for d in self.get("taxes")
Nabin Hait205f7ce2013-04-26 13:35:06 +0530101 if d.category in ["Valuation", "Valuation and Total"]]
tundebabzy9a346202017-06-16 11:00:14 +0100102
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530103 if tax_for_valuation:
104 for d in tax_for_valuation:
105 d.category = 'Total'
106
107 msgprint(msg)
Marica1c8cbd02020-05-02 17:55:15 +0530108
Saqib562fd0e2020-04-08 12:11:40 +0530109 def validate_asset_return(self):
110 if self.doctype not in ['Purchase Receipt', 'Purchase Invoice'] or not self.is_return:
111 return
112
113 purchase_doc_field = 'purchase_receipt' if self.doctype == 'Purchase Receipt' else 'purchase_invoice'
114 not_cancelled_asset = [d.name for d in frappe.db.get_all("Asset", {
115 purchase_doc_field: self.return_against,
116 "docstatus": 1
117 })]
118 if self.is_return and len(not_cancelled_asset):
Rohit Waghchaure103ecec2020-10-26 11:55:08 +0530119 frappe.throw(_("{} has submitted assets linked to it. You need to cancel the assets to create purchase return.")
120 .format(self.return_against), title=_("Not Allowed"))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530121
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530122 def get_asset_items(self):
Saqibd9956092019-11-18 11:46:55 +0530123 if self.doctype not in ['Purchase Order', 'Purchase Invoice', 'Purchase Receipt']:
Rohit Waghchaured644e6d2018-05-12 15:27:18 +0530124 return []
125
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530126 return [d.item_code for d in self.items if d.is_fixed_asset]
127
Saurabhfbb342c2016-04-07 16:41:31 +0530128 def set_landed_cost_voucher_amount(self):
129 for d in self.get("items"):
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530130 lc_voucher_data = frappe.db.sql("""select sum(applicable_charges), cost_center
Saurabhfbb342c2016-04-07 16:41:31 +0530131 from `tabLanded Cost Item`
132 where docstatus = 1 and purchase_receipt_item = %s""", d.name)
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530133 d.landed_cost_voucher_amount = lc_voucher_data[0][0] if lc_voucher_data else 0.0
134 if not d.cost_center and lc_voucher_data and lc_voucher_data[0][1]:
135 d.db_set('cost_center', lc_voucher_data[0][1])
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530136
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530137 def validate_from_warehouse(self):
138 for item in self.get('items'):
139 if item.get('from_warehouse') and (item.get('from_warehouse') == item.get('warehouse')):
140 frappe.throw(_("Row #{0}: Accepted Warehouse and Supplier Warehouse cannot be same").format(item.idx))
141
142 if item.get('from_warehouse') and self.get('is_subcontracted') == 'Yes':
143 frappe.throw(_("Row #{0}: Cannot select Supplier Warehouse while suppling raw materials to subcontractor").format(item.idx))
144
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530145 def set_supplier_address(self):
146 address_dict = {
147 'supplier_address': 'address_display',
148 'shipping_address': 'shipping_address_display'
149 }
150
151 for address_field, address_display_field in address_dict.items():
152 if self.get(address_field):
153 self.set(address_display_field, get_address_display(self.get(address_field)))
154
Nabin Haitd3b62502013-01-21 17:24:31 +0530155 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530156 from frappe.utils import money_in_words
Nabin Hait5690be12015-02-12 16:09:11 +0530157 if self.meta.get_field("base_in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530158 if self.meta.get_field("base_rounded_total") and not self.is_rounded_total_disabled():
159 amount = self.base_rounded_total
160 else:
161 amount = self.base_grand_total
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530162 self.base_in_words = money_in_words(amount, self.company_currency)
163
Nabin Hait5b4c2942013-01-22 11:12:02 +0530164 if self.meta.get_field("in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530165 if self.meta.get_field("rounded_total") and not self.is_rounded_total_disabled():
166 amount = self.rounded_total
167 else:
168 amount = self.grand_total
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530169
170 self.in_words = money_in_words(amount, self.currency)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530171
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530172 # update valuation rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530173 def update_valuation_rate(self, reset_outgoing_rate=True):
Anand Doshi8595fcf2013-02-08 19:28:14 +0530174 """
175 item_tax_amount is the total tax amount applied on that item
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530176 stored for valuation
177
Anand Doshi8595fcf2013-02-08 19:28:14 +0530178 TODO: rename item_tax_amount to valuation_tax_amount
179 """
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530180 stock_and_asset_items = []
Saqibd9956092019-11-18 11:46:55 +0530181 stock_and_asset_items = self.get_stock_items() + self.get_asset_items()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530182
Saqibd9956092019-11-18 11:46:55 +0530183 stock_and_asset_items_qty, stock_and_asset_items_amount = 0, 0
184 last_item_idx = 1
Nabin Haita77b8c92020-12-21 14:45:50 +0530185 for d in self.get("items"):
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530186 if (d.item_code and d.item_code in stock_and_asset_items):
Saqibd9956092019-11-18 11:46:55 +0530187 stock_and_asset_items_qty += flt(d.qty)
188 stock_and_asset_items_amount += flt(d.base_net_amount)
189 last_item_idx = d.idx
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530190
Ankush Menat98917802021-06-11 18:40:22 +0530191 total_valuation_amount = sum(flt(d.base_tax_amount_after_discount_amount) for d in self.get("taxes")
192 if d.category in ["Valuation", "Valuation and Total"])
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530193
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530194 valuation_amount_adjustment = total_valuation_amount
Nabin Haita77b8c92020-12-21 14:45:50 +0530195 for i, item in enumerate(self.get("items")):
Saqibd9956092019-11-18 11:46:55 +0530196 if item.item_code and item.qty and item.item_code in stock_and_asset_items:
197 item_proportion = flt(item.base_net_amount) / stock_and_asset_items_amount if stock_and_asset_items_amount \
198 else flt(item.qty) / stock_and_asset_items_qty
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530199
Saqibd9956092019-11-18 11:46:55 +0530200 if i == (last_item_idx - 1):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530201 item.item_tax_amount = flt(valuation_amount_adjustment,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530202 self.precision("item_tax_amount", item))
203 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530204 item.item_tax_amount = flt(item_proportion * total_valuation_amount,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530205 self.precision("item_tax_amount", item))
206 valuation_amount_adjustment -= item.item_tax_amount
207
Anand Doshi39384d32013-05-11 19:39:53 +0530208 self.round_floats_in(item)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530209 if flt(item.conversion_factor)==0.0:
bobzz-zoneb4c7bad2015-08-05 11:30:12 +0700210 item.conversion_factor = get_conversion_factor(item.item_code, item.uom).get("conversion_factor") or 1.0
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530211
Rushabh Mehta54047782013-12-26 11:07:46 +0530212 qty_in_stock_uom = flt(item.qty * item.conversion_factor)
Nabin Haita77b8c92020-12-21 14:45:50 +0530213 item.rm_supp_cost = self.get_supplied_items_cost(item.name, reset_outgoing_rate)
214 item.valuation_rate = ((item.base_net_amount + item.item_tax_amount + item.rm_supp_cost
215 + flt(item.landed_cost_voucher_amount)) / qty_in_stock_uom)
Anand Doshi4a7248e2013-02-27 18:10:30 +0530216 else:
Anand Doshi5af812a2013-05-10 19:23:02 +0530217 item.valuation_rate = 0.0
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530218
Deepesh Gargb4be2922021-01-28 13:09:56 +0530219 def set_incoming_rate(self):
220 if self.doctype not in ("Purchase Receipt", "Purchase Invoice", "Purchase Order"):
221 return
222
223 ref_doctype_map = {
224 "Purchase Order": "Sales Order Item",
225 "Purchase Receipt": "Delivery Note Item",
226 "Purchase Invoice": "Sales Invoice Item",
227 }
228
229 ref_doctype = ref_doctype_map.get(self.doctype)
230 items = self.get("items")
231 for d in items:
232 if not cint(self.get("is_return")):
233 # Get outgoing rate based on original item cost based on valuation method
234
235 if not d.get(frappe.scrub(ref_doctype)):
236 outgoing_rate = get_incoming_rate({
237 "item_code": d.item_code,
238 "warehouse": d.get('from_warehouse'),
239 "posting_date": self.get('posting_date') or self.get('transation_date'),
240 "posting_time": self.get('posting_time'),
241 "qty": -1 * flt(d.get('stock_qty')),
242 "serial_no": d.get('serial_no'),
243 "company": self.company,
244 "voucher_type": self.doctype,
245 "voucher_no": self.name,
246 "allow_zero_valuation": d.get("allow_zero_valuation")
247 }, raise_error_if_no_rate=False)
248
249 rate = flt(outgoing_rate * d.conversion_factor, d.precision('rate'))
250 else:
251 rate = frappe.db.get_value(ref_doctype, d.get(frappe.scrub(ref_doctype)), 'rate')
252
253 if self.is_internal_transfer():
254 if rate != d.rate:
255 d.rate = rate
256 d.discount_percentage = 0
257 d.discount_amount = 0
258 frappe.msgprint(_("Row {0}: Item rate has been updated as per valuation rate since its an internal stock transfer")
259 .format(d.idx), alert=1)
260
Nabin Haita77b8c92020-12-21 14:45:50 +0530261 def get_supplied_items_cost(self, item_row_id, reset_outgoing_rate=True):
262 supplied_items_cost = 0.0
263 for d in self.get("supplied_items"):
264 if d.reference_name == item_row_id:
Rohit Waghchaure7b7ceaa2021-05-24 20:11:15 +0530265 if reset_outgoing_rate and frappe.get_cached_value('Item', d.rm_item_code, 'is_stock_item'):
Nabin Haita77b8c92020-12-21 14:45:50 +0530266 rate = get_incoming_rate({
267 "item_code": d.rm_item_code,
268 "warehouse": self.supplier_warehouse,
269 "posting_date": self.posting_date,
270 "posting_time": self.posting_time,
271 "qty": -1 * d.consumed_qty,
272 "serial_no": d.serial_no
273 })
274
275 if rate > 0:
276 d.rate = rate
277
Nabin Haitb99c77b2020-12-25 18:12:35 +0530278 d.amount = flt(flt(d.consumed_qty) * flt(d.rate), d.precision("amount"))
Nabin Haita77b8c92020-12-21 14:45:50 +0530279 supplied_items_cost += flt(d.amount)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530280
Nabin Haita77b8c92020-12-21 14:45:50 +0530281 return supplied_items_cost
282
Nabin Hait54d209f2013-03-01 18:51:10 +0530283 def validate_for_subcontracting(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530284 if not self.is_subcontracted and self.sub_contracted_items:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530285 frappe.throw(_("Please enter 'Is Subcontracted' as Yes or No"))
286
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530287 if self.is_subcontracted == "Yes":
Saurabhfbb342c2016-04-07 16:41:31 +0530288 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] and not self.supplier_warehouse:
Afshan27bcb2a2021-03-09 22:25:48 +0530289 frappe.throw(_("Supplier Warehouse mandatory for sub-contracted {0}").format(self.doctype))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530290
Nabin Haitdd38a262014-12-26 13:15:21 +0530291 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530292 if item in self.sub_contracted_items and not item.bom:
293 frappe.throw(_("Please select BOM in BOM field for Item {0}").format(item.item_code))
294
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530295 if self.doctype != "Purchase Order":
296 return
pawan54465f52017-11-29 10:18:38 +0530297
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530298 for row in self.get("supplied_items"):
299 if not row.reserve_warehouse:
300 msg = f"Reserved Warehouse is mandatory for the Item {frappe.bold(row.rm_item_code)} in Raw Materials supplied"
301 frappe.throw(_(msg))
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530302 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530303 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530304 if item.bom:
305 item.bom = None
306
Nabin Hait344f4432014-05-08 19:08:20 +0530307 def create_raw_materials_supplied(self, raw_material_table):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530308 if self.is_subcontracted=="Yes":
Rohit Waghchaure7b7ceaa2021-05-24 20:11:15 +0530309 self.set_materials_for_subcontracted_items(raw_material_table)
Nabin Hait54d209f2013-03-01 18:51:10 +0530310
Saurabhfbb342c2016-04-07 16:41:31 +0530311 elif self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Haitdd38a262014-12-26 13:15:21 +0530312 for item in self.get("items"):
Nabin Haita0c239d2014-04-01 18:54:38 +0530313 item.rm_supp_cost = 0.0
314
Rohit Waghchaure4b9d2f22017-02-16 15:53:40 +0530315 if self.is_subcontracted == "No" and self.get("supplied_items"):
316 self.set('supplied_items', [])
317
Nabin Hait5418d712013-02-27 18:11:17 +0530318 @property
319 def sub_contracted_items(self):
320 if not hasattr(self, "_sub_contracted_items"):
Nabin Haitebd51442013-04-23 15:36:26 +0530321 self._sub_contracted_items = []
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530322 item_codes = list(set(item.item_code for item in
Nabin Haitdd38a262014-12-26 13:15:21 +0530323 self.get("items")))
Nabin Haitebd51442013-04-23 15:36:26 +0530324 if item_codes:
Suraj Shetty9d6d95c2019-11-29 13:26:52 +0530325 items = frappe.get_all('Item', filters={
326 'name': ['in', item_codes],
327 'is_sub_contracted_item': 1
328 })
329 self._sub_contracted_items = [item.name for item in items]
Nabin Hait5418d712013-02-27 18:11:17 +0530330
331 return self._sub_contracted_items
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530332
nabinhait614fb752014-07-14 10:47:50 +0530333 def set_qty_as_per_stock_uom(self):
Nabin Haitdd38a262014-12-26 13:15:21 +0530334 for d in self.get("items"):
Nabin Haitfd4bcd82015-05-22 16:55:40 +0530335 if d.meta.get_field("stock_qty"):
Deepesh Garg8b0302b2019-08-05 10:14:19 +0530336 # Check if item code is present
337 # Conversion factor should not be mandatory for non itemized items
338 if not d.conversion_factor and d.item_code:
Nabin Haite6e456b2015-05-13 17:21:44 +0530339 frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
Rushabh Mehta5b51cc82014-07-21 18:25:45 +0530340 d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530341
marinationd6596a12020-11-02 15:07:48 +0530342 if self.doctype=="Purchase Receipt" and d.meta.get_field("received_stock_qty"):
343 # Set Received Qty in Stock UOM
344 d.received_stock_qty = flt(d.received_qty) * flt(d.conversion_factor, d.precision("conversion_factor"))
345
Saurabh130c57b2016-04-04 15:49:36 +0530346 def validate_purchase_return(self):
347 for d in self.get("items"):
348 if self.is_return and flt(d.rejected_qty) != 0:
349 frappe.throw(_("Row #{0}: Rejected Qty can not be entered in Purchase Return").format(d.idx))
350
351 # validate rate with ref PR
352
353 def validate_rejected_warehouse(self):
354 for d in self.get("items"):
355 if flt(d.rejected_qty) and not d.rejected_warehouse:
Saurabhfbb342c2016-04-07 16:41:31 +0530356 if self.rejected_warehouse:
357 d.rejected_warehouse = self.rejected_warehouse
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530358
Saurabh130c57b2016-04-04 15:49:36 +0530359 if not d.rejected_warehouse:
360 frappe.throw(_("Row #{0}: Rejected Warehouse is mandatory against rejected Item {1}").format(d.idx, d.item_code))
361
362 # validate accepted and rejected qty
363 def validate_accepted_rejected_qty(self):
364 for d in self.get("items"):
Saurabh4f4d0a82017-03-13 14:31:48 +0530365 self.validate_negative_quantity(d, ["received_qty","qty", "rejected_qty"])
Saurabh130c57b2016-04-04 15:49:36 +0530366
marination5fb5a752021-11-08 13:22:57 +0530367 if not flt(d.received_qty) and (flt(d.qty) or flt(d.rejected_qty)):
368 d.received_qty = flt(d.qty) + flt(d.rejected_qty)
Saurabh130c57b2016-04-04 15:49:36 +0530369
Saurabh130c57b2016-04-04 15:49:36 +0530370 # Check Received Qty = Accepted Qty + Rejected Qty
marinationafe1c452021-11-15 17:17:29 +0530371 val = flt(d.qty) + flt(d.rejected_qty)
Mangesh-Khairnar8c621ab2019-06-26 11:10:17 +0530372 if (flt(val, d.precision("received_qty")) != flt(d.received_qty, d.precision("received_qty"))):
marination05ec7cc2021-11-15 17:49:14 +0530373 message = _("Row #{0}: Received Qty must be equal to Accepted + Rejected Qty for Item {1}").format(d.idx, d.item_code)
374 frappe.throw(msg=message, title=_("Mismatch"), exc=QtyMismatchError)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530375
Saurabh4f4d0a82017-03-13 14:31:48 +0530376 def validate_negative_quantity(self, item_row, field_list):
377 if self.is_return:
378 return
379
380 item_row = item_row.as_dict()
381 for fieldname in field_list:
382 if flt(item_row[fieldname]) < 0:
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530383 frappe.throw(_("Row #{0}: {1} can not be negative for item {2}").format(item_row['idx'],
384 frappe.get_meta(item_row.doctype).get_label(fieldname), item_row['item_code']))
Saurabh4f4d0a82017-03-13 14:31:48 +0530385
Mangesh-Khairnar5e474f42019-03-06 14:46:38 +0530386 def check_for_on_hold_or_closed_status(self, ref_doctype, ref_fieldname):
387 for d in self.get("items"):
388 if d.get(ref_fieldname):
389 status = frappe.db.get_value(ref_doctype, d.get(ref_fieldname), "status")
390 if status in ("Closed", "On Hold"):
391 frappe.throw(_("{0} {1} is {2}").format(ref_doctype,d.get(ref_fieldname), status))
392
Saurabhe29248b2016-04-04 11:55:52 +0530393 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait07e53762018-01-05 18:19:59 +0530394 self.update_ordered_and_reserved_qty()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530395
Saurabhe29248b2016-04-04 11:55:52 +0530396 sl_entries = []
397 stock_items = self.get_stock_items()
398
399 for d in self.get('items'):
400 if d.item_code in stock_items and d.warehouse:
401 pr_qty = flt(d.qty) * flt(d.conversion_factor)
402
403 if pr_qty:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530404
405 if d.from_warehouse and ((not cint(self.is_return) and self.docstatus==1)
406 or (cint(self.is_return) and self.docstatus==2)):
407 from_warehouse_sle = self.get_sl_entries(d, {
408 "actual_qty": -1 * pr_qty,
Nabin Haita77b8c92020-12-21 14:45:50 +0530409 "warehouse": d.from_warehouse,
Deepesh Gargb4be2922021-01-28 13:09:56 +0530410 "outgoing_rate": d.rate,
411 "recalculate_rate": 1,
Nabin Haita77b8c92020-12-21 14:45:50 +0530412 "dependant_sle_voucher_detail_no": d.name
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530413 })
414
415 sl_entries.append(from_warehouse_sle)
416
Saurabhe29248b2016-04-04 11:55:52 +0530417 sle = self.get_sl_entries(d, {
418 "actual_qty": flt(pr_qty),
419 "serial_no": cstr(d.serial_no).strip()
420 })
421 if self.is_return:
Nabin Haita77b8c92020-12-21 14:45:50 +0530422 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 +0530423
Saurabhe29248b2016-04-04 11:55:52 +0530424 sle.update({
Nabin Haita77b8c92020-12-21 14:45:50 +0530425 "outgoing_rate": outgoing_rate,
426 "recalculate_rate": 1
Saurabhe29248b2016-04-04 11:55:52 +0530427 })
Nabin Haita77b8c92020-12-21 14:45:50 +0530428 if d.from_warehouse:
429 sle.dependant_sle_voucher_detail_no = d.name
Saurabhe29248b2016-04-04 11:55:52 +0530430 else:
Nabin Haitb81ed452016-05-11 12:52:31 +0530431 val_rate_db_precision = 6 if cint(self.precision("valuation_rate", d)) <= 6 else 9
432 incoming_rate = flt(d.valuation_rate, val_rate_db_precision)
Saurabhe29248b2016-04-04 11:55:52 +0530433 sle.update({
Nabin Haita77b8c92020-12-21 14:45:50 +0530434 "incoming_rate": incoming_rate,
435 "recalculate_rate": 1 if (self.is_subcontracted and d.bom) or d.from_warehouse else 0
Saurabhe29248b2016-04-04 11:55:52 +0530436 })
437 sl_entries.append(sle)
438
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530439 if d.from_warehouse and ((not cint(self.is_return) and self.docstatus==2)
440 or (cint(self.is_return) and self.docstatus==1)):
441 from_warehouse_sle = self.get_sl_entries(d, {
442 "actual_qty": -1 * pr_qty,
Nabin Haita77b8c92020-12-21 14:45:50 +0530443 "warehouse": d.from_warehouse,
444 "recalculate_rate": 1
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530445 })
446
447 sl_entries.append(from_warehouse_sle)
448
Rohit Waghchaure560ba392016-08-29 18:19:32 +0530449 if flt(d.rejected_qty) != 0:
Saurabhe29248b2016-04-04 11:55:52 +0530450 sl_entries.append(self.get_sl_entries(d, {
451 "warehouse": d.rejected_warehouse,
452 "actual_qty": flt(d.rejected_qty) * flt(d.conversion_factor),
453 "serial_no": cstr(d.rejected_serial_no).strip(),
454 "incoming_rate": 0.0
455 }))
456
457 self.make_sl_entries_for_supplier_warehouse(sl_entries)
458 self.make_sl_entries(sl_entries, allow_negative_stock=allow_negative_stock,
459 via_landed_cost_voucher=via_landed_cost_voucher)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530460
Nabin Hait07e53762018-01-05 18:19:59 +0530461 def update_ordered_and_reserved_qty(self):
Nabin Hait14aa9c52016-04-18 15:54:01 +0530462 po_map = {}
463 for d in self.get("items"):
464 if self.doctype=="Purchase Receipt" \
Rohit Waghchaurea71d9d32016-07-05 00:34:00 +0530465 and d.purchase_order:
466 po_map.setdefault(d.purchase_order, []).append(d.purchase_order_item)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530467
Nabin Hait14aa9c52016-04-18 15:54:01 +0530468 elif self.doctype=="Purchase Invoice" and d.purchase_order and d.po_detail:
469 po_map.setdefault(d.purchase_order, []).append(d.po_detail)
470
471 for po, po_item_rows in po_map.items():
472 if po and po_item_rows:
473 po_obj = frappe.get_doc("Purchase Order", po)
474
475 if po_obj.status in ["Closed", "Cancelled"]:
476 frappe.throw(_("{0} {1} is cancelled or closed").format(_("Purchase Order"), po),
477 frappe.InvalidStatusError)
478
479 po_obj.update_ordered_qty(po_item_rows)
Nabin Hait07e53762018-01-05 18:19:59 +0530480 if self.is_subcontracted:
481 po_obj.update_reserved_qty_for_subcontract()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530482
Saurabhe29248b2016-04-04 11:55:52 +0530483 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
484 if hasattr(self, 'supplied_items'):
485 for d in self.get('supplied_items'):
486 # negative quantity is passed, as raw material qty has to be decreased
487 # when PR is submitted and it has to be increased when PR is cancelled
488 sl_entries.append(self.get_sl_entries(d, {
489 "item_code": d.rm_item_code,
490 "warehouse": self.supplier_warehouse,
491 "actual_qty": -1*flt(d.consumed_qty),
Nabin Haita77b8c92020-12-21 14:45:50 +0530492 "dependant_sle_voucher_detail_no": d.reference_name
Saurabhe29248b2016-04-04 11:55:52 +0530493 }))
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530494
rohitwaghchaurefe226862017-12-28 16:11:27 +0530495 def on_submit(self):
496 if self.get('is_return'):
497 return
498
Rohit Waghchaureab842542018-04-26 19:18:29 +0530499 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530500 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
501
502 self.process_fixed_asset()
503 self.update_fixed_asset(field)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530504
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530505 if self.doctype in ['Purchase Order', 'Purchase Receipt']:
506 update_last_purchase_rate(self, is_submit = 1)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530507
508 def on_cancel(self):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +0530509 super(BuyingController, self).on_cancel()
510
rohitwaghchaurefe226862017-12-28 16:11:27 +0530511 if self.get('is_return'):
512 return
513
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530514 if self.doctype in ['Purchase Order', 'Purchase Receipt']:
515 update_last_purchase_rate(self, is_submit = 0)
516
Rohit Waghchaureab842542018-04-26 19:18:29 +0530517 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530518 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
519
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530520 self.delete_linked_asset()
521 self.update_fixed_asset(field, delete_asset=True)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530522
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530523 def validate_budget(self):
524 if self.docstatus == 1:
525 for data in self.get('items'):
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530526 args = data.as_dict()
527 args.update({
528 'doctype': self.doctype,
rohitwaghchaure34c18772018-06-25 10:31:08 +0530529 'company': self.company,
530 'posting_date': (self.schedule_date
531 if self.doctype == 'Material Request' else self.transaction_date)
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530532 })
533
534 validate_expense_against_budget(args)
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530535
Rohit Waghchaureab842542018-04-26 19:18:29 +0530536 def process_fixed_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530537 if self.doctype == 'Purchase Invoice' and not self.update_stock:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530538 return
539
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530540 asset_items = self.get_asset_items()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530541 if asset_items:
Saqibd9956092019-11-18 11:46:55 +0530542 self.auto_make_assets(asset_items)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530543
Saqibd9956092019-11-18 11:46:55 +0530544 def auto_make_assets(self, asset_items):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530545 items_data = get_asset_item_details(asset_items)
Saqibf37a46e2019-11-22 16:32:50 +0530546 messages = []
Rohit Waghchaureab842542018-04-26 19:18:29 +0530547
548 for d in self.items:
549 if d.is_fixed_asset:
550 item_data = items_data.get(d.item_code)
551
Saqibd9956092019-11-18 11:46:55 +0530552 if item_data.get('auto_create_assets'):
553 # If asset has to be auto created
554 # Check for asset naming series
555 if item_data.get('asset_naming_series'):
Saqibbba78f02020-03-31 10:49:44 +0530556 created_assets = []
Saqib Ansari35a6b582022-01-18 13:10:23 +0530557 if item_data.get('is_grouped_asset'):
558 asset = self.make_asset(d, is_grouped_asset=True)
Saqibbba78f02020-03-31 10:49:44 +0530559 created_assets.append(asset)
Saqib Ansari35a6b582022-01-18 13:10:23 +0530560 else:
561 for qty in range(cint(d.qty)):
562 asset = self.make_asset(d)
563 created_assets.append(asset)
Marica1c8cbd02020-05-02 17:55:15 +0530564
Saqibbba78f02020-03-31 10:49:44 +0530565 if len(created_assets) > 5:
566 # dont show asset form links if more than 5 assets are created
Marica1c8cbd02020-05-02 17:55:15 +0530567 messages.append(_('{} Assets created for {}').format(len(created_assets), frappe.bold(d.item_code)))
Saqibbba78f02020-03-31 10:49:44 +0530568 else:
569 assets_link = list(map(lambda d: frappe.utils.get_link_to_form('Asset', d), created_assets))
570 assets_link = frappe.bold(','.join(assets_link))
571
572 is_plural = 's' if len(created_assets) != 1 else ''
573 messages.append(
574 _('Asset{} {assets_link} created for {}').format(is_plural, frappe.bold(d.item_code), assets_link=assets_link)
575 )
Saqibd9956092019-11-18 11:46:55 +0530576 else:
Saqibbba78f02020-03-31 10:49:44 +0530577 frappe.throw(_("Row {}: Asset Naming Series is mandatory for the auto creation for item {}")
578 .format(d.idx, frappe.bold(d.item_code)))
Saqibd9956092019-11-18 11:46:55 +0530579 else:
Saqibbba78f02020-03-31 10:49:44 +0530580 messages.append(_("Assets not created for {0}. You will have to create asset manually.")
581 .format(frappe.bold(d.item_code)))
Saqibf37a46e2019-11-22 16:32:50 +0530582
583 for message in messages:
Saqibbba78f02020-03-31 10:49:44 +0530584 frappe.msgprint(message, title="Success", indicator="green")
Rohit Waghchaureab842542018-04-26 19:18:29 +0530585
Saqib Ansari35a6b582022-01-18 13:10:23 +0530586 def make_asset(self, row, is_grouped_asset=False):
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530587 if not row.asset_location:
588 frappe.throw(_("Row {0}: Enter location for the asset item {1}").format(row.idx, row.item_code))
589
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530590 item_data = frappe.db.get_value('Item',
591 row.item_code, ['asset_naming_series', 'asset_category'], as_dict=1)
592
Saqib Ansari35a6b582022-01-18 13:10:23 +0530593 if is_grouped_asset:
594 purchase_amount = flt(row.base_amount + row.item_tax_amount)
595 else:
596 purchase_amount = flt(row.base_rate + row.item_tax_amount)
597
Rohit Waghchaureab842542018-04-26 19:18:29 +0530598 asset = frappe.get_doc({
599 'doctype': 'Asset',
600 'item_code': row.item_code,
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530601 'asset_name': row.item_name,
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530602 'naming_series': item_data.get('asset_naming_series') or 'AST',
603 'asset_category': item_data.get('asset_category'),
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530604 'location': row.asset_location,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530605 'company': self.company,
thefalconx33c15cc8f2019-09-24 18:49:16 +0530606 'supplier': self.supplier,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530607 'purchase_date': self.posting_date,
Rohit Waghchaure0ea6fe42018-05-08 23:31:58 +0530608 'calculate_depreciation': 1,
Rohit Waghchaure16bc8532018-05-12 12:06:00 +0530609 'purchase_receipt_amount': purchase_amount,
610 'gross_purchase_amount': purchase_amount,
Saqib Ansari35a6b582022-01-18 13:10:23 +0530611 'asset_quantity': row.qty if is_grouped_asset else 0,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530612 'purchase_receipt': self.name if self.doctype == 'Purchase Receipt' else None,
613 'purchase_invoice': self.name if self.doctype == 'Purchase Invoice' else None
614 })
615
616 asset.flags.ignore_validate = True
617 asset.flags.ignore_mandatory = True
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530618 asset.set_missing_values()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530619 asset.insert()
620
Saqibbba78f02020-03-31 10:49:44 +0530621 return asset.name
622
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530623 def update_fixed_asset(self, field, delete_asset = False):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530624 for d in self.get("items"):
Saqibd9956092019-11-18 11:46:55 +0530625 if d.is_fixed_asset:
626 is_auto_create_enabled = frappe.db.get_value('Item', d.item_code, 'auto_create_assets')
627 assets = frappe.db.get_all('Asset', filters={ field : self.name, 'item_code' : d.item_code })
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530628
Saqibd9956092019-11-18 11:46:55 +0530629 for asset in assets:
630 asset = frappe.get_doc('Asset', asset.name)
631 if delete_asset and is_auto_create_enabled:
632 # need to delete movements to delete assets otherwise throws link exists error
Saqibcd3976f2019-11-25 12:24:34 +0530633 movements = frappe.db.sql(
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530634 """SELECT asm.name
Saqibcd3976f2019-11-25 12:24:34 +0530635 FROM `tabAsset Movement` asm, `tabAsset Movement Item` asm_item
636 WHERE asm_item.parent=asm.name and asm_item.asset=%s""", asset.name, as_dict=1)
Saqibd9956092019-11-18 11:46:55 +0530637 for movement in movements:
638 frappe.delete_doc('Asset Movement', movement.name, force=1)
639 frappe.delete_doc("Asset", asset.name, force=1)
640 continue
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530641
Saqibd9956092019-11-18 11:46:55 +0530642 if self.docstatus in [0, 1] and not asset.get(field):
643 asset.set(field, self.name)
644 asset.purchase_date = self.posting_date
645 asset.supplier = self.supplier
646 elif self.docstatus == 2:
Saqibcd3976f2019-11-25 12:24:34 +0530647 if asset.docstatus == 0:
648 asset.set(field, None)
649 asset.supplier = None
650 if asset.docstatus == 1 and delete_asset:
Rohit Waghchaure103ecec2020-10-26 11:55:08 +0530651 frappe.throw(_('Cannot cancel this document as it is linked with submitted asset {0}. Please cancel it to continue.')
652 .format(frappe.utils.get_link_to_form('Asset', asset.name)))
Rohit Waghchaureab842542018-04-26 19:18:29 +0530653
Saqibd9956092019-11-18 11:46:55 +0530654 asset.flags.ignore_validate_update_after_submit = True
655 asset.flags.ignore_mandatory = True
656 if asset.docstatus == 0:
657 asset.flags.ignore_validate = True
Rohit Waghchaureab842542018-04-26 19:18:29 +0530658
Saqibd9956092019-11-18 11:46:55 +0530659 asset.save()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530660
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530661 def delete_linked_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530662 if self.doctype == 'Purchase Invoice' and not self.get('update_stock'):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530663 return
664
Nabin Hait1e7c32b2018-09-26 18:01:00 +0530665 frappe.db.sql("delete from `tabAsset Movement` where reference_name=%s", self.name)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530666
Nabin Hait5a834202017-10-05 19:51:10 +0530667 def validate_schedule_date(self):
Sahil Khan34766c02018-12-20 18:50:24 +0530668 if not self.get("items"):
669 return
Nabin Haita1138612019-10-15 12:43:27 +0530670
18alantom2a20a032021-05-05 11:59:15 +0530671 if any(d.schedule_date for d in self.get("items")):
672 # Select earliest schedule_date.
673 self.schedule_date = min(d.schedule_date for d in self.get("items")
674 if d.schedule_date is not None)
Nabin Hait5a834202017-10-05 19:51:10 +0530675
676 if self.schedule_date:
677 for d in self.get('items'):
678 if not d.schedule_date:
679 d.schedule_date = self.schedule_date
680
Prateeksha Singhcbd06fd2018-01-05 21:28:01 +0530681 if (d.schedule_date and self.transaction_date and
682 getdate(d.schedule_date) < getdate(self.transaction_date)):
Nabin Hait96b264b2018-01-02 11:50:29 +0530683 frappe.throw(_("Row #{0}: Reqd by Date cannot be before Transaction Date").format(d.idx))
Nabin Hait5a834202017-10-05 19:51:10 +0530684 else:
Nabin Hait96b264b2018-01-02 11:50:29 +0530685 frappe.throw(_("Please enter Reqd by Date"))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530686
Zarrarfc03a042018-06-04 12:52:52 +0530687 def validate_items(self):
688 # validate items to see if they have is_purchase_item or is_subcontracted_item enabled
Nabin Hait0bef91c2018-06-18 16:33:48 +0530689 if self.doctype=="Material Request": return
Zarrarfc03a042018-06-04 12:52:52 +0530690
rohitwaghchaure50d8c4a2018-06-05 13:08:10 +0530691 if hasattr(self, "is_subcontracted") and self.is_subcontracted == 'Yes':
Zarrarfc03a042018-06-04 12:52:52 +0530692 validate_item_type(self, "is_sub_contracted_item", "subcontracted")
693 else:
694 validate_item_type(self, "is_purchase_item", "purchase")
695
Rohit Waghchaureab842542018-04-26 19:18:29 +0530696def get_asset_item_details(asset_items):
697 asset_items_data = {}
Saqib Ansari35a6b582022-01-18 13:10:23 +0530698 for d in frappe.get_all('Item', fields = ["name", "auto_create_assets", "asset_naming_series", "is_grouped_asset"],
Rohit Waghchaureab842542018-04-26 19:18:29 +0530699 filters = {'name': ('in', asset_items)}):
700 asset_items_data.setdefault(d.name, d)
701
702 return asset_items_data
Ameya Shenoy873e28d2018-06-06 05:53:19 +0000703
Zarrarfc03a042018-06-04 12:52:52 +0530704def validate_item_type(doc, fieldname, message):
705 # iterate through items and check if they are valid sales or purchase items
Zarrar7c088ff2018-06-05 10:32:09 +0530706 items = [d.item_code for d in doc.items if d.item_code]
707
708 # No validation check inase of creating transaction using 'Opening Invoice Creation Tool'
709 if not items:
710 return
711
Suraj Shettybfc195d2018-09-21 10:20:52 +0530712 item_list = ", ".join(["%s" % frappe.db.escape(d) for d in items])
Zarrarfc03a042018-06-04 12:52:52 +0530713
714 invalid_items = [d[0] for d in frappe.db.sql("""
715 select item_code from tabItem where name in ({0}) and {1}=0
716 """.format(item_list, fieldname), as_list=True)]
717
718 if invalid_items:
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530719 items = ", ".join([d for d in invalid_items])
720
721 if len(invalid_items) > 1:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530722 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 +0530723 else:
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530724 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 +0530725
726 frappe.throw(error_message)