blob: 036733c0c345daa96de352d37b5b32c2f869c9e5 [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
s-aga-r6d89b2f2022-06-18 15:46:59 +053014from erpnext.controllers.subcontracting_controller import SubcontractingController
Chillar Anand915b3432021-09-02 16:44:59 +053015from erpnext.stock.get_item_details import get_conversion_factor
16from erpnext.stock.utils import get_incoming_rate
17
marination293f6cb2021-11-16 14:22:26 +053018
19class QtyMismatchError(ValidationError):
20 pass
Rohit Waghchaure7b7ceaa2021-05-24 20:11:15 +053021
Faris Ansaribc6a2b22020-10-27 19:42:58 +053022
s-aga-r6d89b2f2022-06-18 15:46:59 +053023class BuyingController(SubcontractingController):
24 def __setup__(self):
25 self.flags.ignore_permlevel_for_fields = ["buying_price_list", "price_list_currency"]
26
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053027 def get_feed(self):
rohitwaghchaurea1064a62016-03-03 14:00:35 +053028 if self.get("supplier_name"):
Ankush Menat494bd9e2022-03-28 18:52:46 +053029 return _("From {0} | {1} {2}").format(self.supplier_name, self.currency, 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
Ankush Menat494bd9e2022-03-28 18:52:46 +053044 if self.doctype == "Purchase Invoice":
Nabin Hait14aa9c52016-04-18 15:54:01 +053045 self.validate_purchase_receipt_if_update_stock()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053046
Ankush Menat494bd9e2022-03-28 18:52:46 +053047 if self.doctype == "Purchase Receipt" or (
48 self.doctype == "Purchase Invoice" and self.update_stock
49 ):
Rohit Waghchaure560ba392016-08-29 18:19:32 +053050 # self.validate_purchase_return()
Saurabhfbb342c2016-04-07 16:41:31 +053051 self.validate_rejected_warehouse()
52 self.validate_accepted_rejected_qty()
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053053 validate_for_items(self)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053054
Ankush Menat494bd9e2022-03-28 18:52:46 +053055 # sub-contracting
Saurabhfbb342c2016-04-07 16:41:31 +053056 self.validate_for_subcontracting()
s-aga-r6d89b2f2022-06-18 15:46:59 +053057 if self.get("is_old_subcontracting_flow"):
58 self.create_raw_materials_supplied()
Saurabhfbb342c2016-04-07 16:41:31 +053059 self.set_landed_cost_voucher_amount()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053060
Nabin Hait14aa9c52016-04-18 15:54:01 +053061 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Nabin Haita77b8c92020-12-21 14:45:50 +053062 self.update_valuation_rate()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053063
Rohit Waghchaure110e1522021-06-15 17:29:52 +053064 def onload(self):
65 super(BuyingController, self).onload()
Ankush Menat494bd9e2022-03-28 18:52:46 +053066 self.set_onload(
67 "backflush_based_on",
68 frappe.db.get_single_value(
69 "Buying Settings", "backflush_raw_materials_of_subcontract_based_on"
70 ),
71 )
Rohit Waghchaure110e1522021-06-15 17:29:52 +053072
Anand Doshi3543f302013-05-24 19:25:01 +053073 def set_missing_values(self, for_validate=False):
Anand Doshiabc10032013-06-14 17:44:03 +053074 super(BuyingController, self).set_missing_values(for_validate)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053075
Rushabh Mehta0b995402013-08-09 15:29:59 +053076 self.set_supplier_from_item_default()
Nabin Hait096d3632013-10-17 17:01:14 +053077 self.set_price_list_currency("Buying")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053078
Anand Doshi3543f302013-05-24 19:25:01 +053079 # set contact and address details for supplier, if they are not mentioned
Nabin Hait365ae272014-04-03 17:38:54 +053080 if getattr(self, "supplier", None):
marination78b6b292022-01-24 13:39:10 +053081 self.update_if_missing(
82 get_party_details(
83 self.supplier,
84 party_type="Supplier",
85 doctype=self.doctype,
86 company=self.company,
87 party_address=self.get("supplier_address"),
Ankush Menat494bd9e2022-03-28 18:52:46 +053088 shipping_address=self.get("shipping_address"),
89 fetch_payment_terms_template=not self.get("ignore_default_payment_terms_template"),
90 ignore_permissions=self.flags.ignore_permissions,
marination78b6b292022-01-24 13:39:10 +053091 )
92 )
Rushabh Mehta886c9ef2013-07-08 12:08:06 +053093
Nabin Haitcccc45e2016-10-05 17:15:43 +053094 self.set_missing_item_details(for_validate)
Rushabh Mehta436467a2013-07-08 12:37:59 +053095
Rushabh Mehta0b995402013-08-09 15:29:59 +053096 def set_supplier_from_item_default(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +053097 if self.meta.get_field("supplier") and not self.supplier:
Nabin Haitdd38a262014-12-26 13:15:21 +053098 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +053099 supplier = frappe.db.get_value(
100 "Item Default", {"parent": d.item_code, "company": self.company}, "default_supplier"
101 )
Rushabh Mehta0b995402013-08-09 15:29:59 +0530102 if supplier:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530103 self.supplier = supplier
Shreya Shah3c9839f2018-07-17 18:01:44 +0530104 else:
105 item_group = frappe.db.get_value("Item", d.item_code, "item_group")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530106 supplier = frappe.db.get_value(
107 "Item Default", {"parent": item_group, "company": self.company}, "default_supplier"
108 )
Shreya Shah3c9839f2018-07-17 18:01:44 +0530109 if supplier:
110 self.supplier = supplier
Rushabh Mehta0b995402013-08-09 15:29:59 +0530111 break
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530112
Nabin Hait205f7ce2013-04-26 13:35:06 +0530113 def validate_stock_or_nonstock_items(self):
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530114 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 +0530115 msg = _('Tax Category has been changed to "Total" because all the Items are non-stock items')
116 self.update_tax_category(msg)
117
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530118 def update_tax_category(self, msg):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530119 tax_for_valuation = [
120 d for d in self.get("taxes") if d.category in ["Valuation", "Valuation and Total"]
121 ]
tundebabzy9a346202017-06-16 11:00:14 +0100122
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530123 if tax_for_valuation:
124 for d in tax_for_valuation:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530125 d.category = "Total"
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530126
127 msgprint(msg)
Marica1c8cbd02020-05-02 17:55:15 +0530128
Saqib562fd0e2020-04-08 12:11:40 +0530129 def validate_asset_return(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530130 if self.doctype not in ["Purchase Receipt", "Purchase Invoice"] or not self.is_return:
Saqib562fd0e2020-04-08 12:11:40 +0530131 return
132
Ankush Menat494bd9e2022-03-28 18:52:46 +0530133 purchase_doc_field = (
134 "purchase_receipt" if self.doctype == "Purchase Receipt" else "purchase_invoice"
135 )
136 not_cancelled_asset = [
137 d.name
138 for d in frappe.db.get_all("Asset", {purchase_doc_field: self.return_against, "docstatus": 1})
139 ]
Saqib562fd0e2020-04-08 12:11:40 +0530140 if self.is_return and len(not_cancelled_asset):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530141 frappe.throw(
142 _(
143 "{} has submitted assets linked to it. You need to cancel the assets to create purchase return."
144 ).format(self.return_against),
145 title=_("Not Allowed"),
146 )
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530147
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530148 def get_asset_items(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530149 if self.doctype not in ["Purchase Order", "Purchase Invoice", "Purchase Receipt"]:
Rohit Waghchaured644e6d2018-05-12 15:27:18 +0530150 return []
151
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530152 return [d.item_code for d in self.items if d.is_fixed_asset]
153
Saurabhfbb342c2016-04-07 16:41:31 +0530154 def set_landed_cost_voucher_amount(self):
155 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530156 lc_voucher_data = frappe.db.sql(
157 """select sum(applicable_charges), cost_center
Saurabhfbb342c2016-04-07 16:41:31 +0530158 from `tabLanded Cost Item`
Ankush Menat494bd9e2022-03-28 18:52:46 +0530159 where docstatus = 1 and purchase_receipt_item = %s""",
160 d.name,
161 )
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530162 d.landed_cost_voucher_amount = lc_voucher_data[0][0] if lc_voucher_data else 0.0
163 if not d.cost_center and lc_voucher_data and lc_voucher_data[0][1]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530164 d.db_set("cost_center", lc_voucher_data[0][1])
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530165
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530166 def validate_from_warehouse(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530167 for item in self.get("items"):
168 if item.get("from_warehouse") and (item.get("from_warehouse") == item.get("warehouse")):
169 frappe.throw(
170 _("Row #{0}: Accepted Warehouse and Supplier Warehouse cannot be same").format(item.idx)
171 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530172
Sagar Sharma409df262022-04-19 14:57:31 +0530173 if item.get("from_warehouse") and self.get("is_subcontracted"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530174 frappe.throw(
175 _(
176 "Row #{0}: Cannot select Supplier Warehouse while suppling raw materials to subcontractor"
177 ).format(item.idx)
178 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530179
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530180 def set_supplier_address(self):
181 address_dict = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530182 "supplier_address": "address_display",
183 "shipping_address": "shipping_address_display",
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530184 }
185
186 for address_field, address_display_field in address_dict.items():
187 if self.get(address_field):
188 self.set(address_display_field, get_address_display(self.get(address_field)))
189
Nabin Haitd3b62502013-01-21 17:24:31 +0530190 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530191 from frappe.utils import money_in_words
Ankush Menat494bd9e2022-03-28 18:52:46 +0530192
Nabin Hait5690be12015-02-12 16:09:11 +0530193 if self.meta.get_field("base_in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530194 if self.meta.get_field("base_rounded_total") and not self.is_rounded_total_disabled():
195 amount = self.base_rounded_total
196 else:
197 amount = self.base_grand_total
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530198 self.base_in_words = money_in_words(amount, self.company_currency)
199
Nabin Hait5b4c2942013-01-22 11:12:02 +0530200 if self.meta.get_field("in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530201 if self.meta.get_field("rounded_total") and not self.is_rounded_total_disabled():
202 amount = self.rounded_total
203 else:
204 amount = self.grand_total
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530205
206 self.in_words = money_in_words(amount, self.currency)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530207
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530208 # update valuation rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530209 def update_valuation_rate(self, reset_outgoing_rate=True):
Anand Doshi8595fcf2013-02-08 19:28:14 +0530210 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530211 item_tax_amount is the total tax amount applied on that item
212 stored for valuation
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530213
Ankush Menat494bd9e2022-03-28 18:52:46 +0530214 TODO: rename item_tax_amount to valuation_tax_amount
Anand Doshi8595fcf2013-02-08 19:28:14 +0530215 """
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530216 stock_and_asset_items = []
Saqibd9956092019-11-18 11:46:55 +0530217 stock_and_asset_items = self.get_stock_items() + self.get_asset_items()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530218
Saqibd9956092019-11-18 11:46:55 +0530219 stock_and_asset_items_qty, stock_and_asset_items_amount = 0, 0
220 last_item_idx = 1
Nabin Haita77b8c92020-12-21 14:45:50 +0530221 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530222 if d.item_code and d.item_code in stock_and_asset_items:
Saqibd9956092019-11-18 11:46:55 +0530223 stock_and_asset_items_qty += flt(d.qty)
224 stock_and_asset_items_amount += flt(d.base_net_amount)
225 last_item_idx = d.idx
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530226
Ankush Menat494bd9e2022-03-28 18:52:46 +0530227 total_valuation_amount = sum(
228 flt(d.base_tax_amount_after_discount_amount)
229 for d in self.get("taxes")
230 if d.category in ["Valuation", "Valuation and Total"]
231 )
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530232
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530233 valuation_amount_adjustment = total_valuation_amount
Nabin Haita77b8c92020-12-21 14:45:50 +0530234 for i, item in enumerate(self.get("items")):
Saqibd9956092019-11-18 11:46:55 +0530235 if item.item_code and item.qty and item.item_code in stock_and_asset_items:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530236 item_proportion = (
237 flt(item.base_net_amount) / stock_and_asset_items_amount
238 if stock_and_asset_items_amount
Saqibd9956092019-11-18 11:46:55 +0530239 else flt(item.qty) / stock_and_asset_items_qty
Ankush Menat494bd9e2022-03-28 18:52:46 +0530240 )
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530241
Saqibd9956092019-11-18 11:46:55 +0530242 if i == (last_item_idx - 1):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530243 item.item_tax_amount = flt(
244 valuation_amount_adjustment, self.precision("item_tax_amount", item)
245 )
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530246 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530247 item.item_tax_amount = flt(
248 item_proportion * total_valuation_amount, self.precision("item_tax_amount", item)
249 )
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530250 valuation_amount_adjustment -= item.item_tax_amount
251
Anand Doshi39384d32013-05-11 19:39:53 +0530252 self.round_floats_in(item)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530253 if flt(item.conversion_factor) == 0.0:
254 item.conversion_factor = (
255 get_conversion_factor(item.item_code, item.uom).get("conversion_factor") or 1.0
256 )
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530257
Rushabh Mehta54047782013-12-26 11:07:46 +0530258 qty_in_stock_uom = flt(item.qty * item.conversion_factor)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530259 if self.get("is_old_subcontracting_flow"):
260 item.rm_supp_cost = self.get_supplied_items_cost(item.name, reset_outgoing_rate)
261 item.valuation_rate = (
262 item.base_net_amount
263 + item.item_tax_amount
264 + item.rm_supp_cost
265 + flt(item.landed_cost_voucher_amount)
266 ) / qty_in_stock_uom
267 else:
268 item.valuation_rate = (
269 item.base_net_amount + item.item_tax_amount + flt(item.landed_cost_voucher_amount)
270 ) / qty_in_stock_uom
Anand Doshi4a7248e2013-02-27 18:10:30 +0530271 else:
Anand Doshi5af812a2013-05-10 19:23:02 +0530272 item.valuation_rate = 0.0
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530273
Deepesh Gargb4be2922021-01-28 13:09:56 +0530274 def set_incoming_rate(self):
275 if self.doctype not in ("Purchase Receipt", "Purchase Invoice", "Purchase Order"):
276 return
277
278 ref_doctype_map = {
279 "Purchase Order": "Sales Order Item",
280 "Purchase Receipt": "Delivery Note Item",
281 "Purchase Invoice": "Sales Invoice Item",
282 }
283
284 ref_doctype = ref_doctype_map.get(self.doctype)
285 items = self.get("items")
286 for d in items:
287 if not cint(self.get("is_return")):
288 # Get outgoing rate based on original item cost based on valuation method
289
290 if not d.get(frappe.scrub(ref_doctype)):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530291 outgoing_rate = get_incoming_rate(
292 {
293 "item_code": d.item_code,
294 "warehouse": d.get("from_warehouse"),
295 "posting_date": self.get("posting_date") or self.get("transation_date"),
296 "posting_time": self.get("posting_time"),
297 "qty": -1 * flt(d.get("stock_qty")),
298 "serial_no": d.get("serial_no"),
299 "batch_no": d.get("batch_no"),
300 "company": self.company,
301 "voucher_type": self.doctype,
302 "voucher_no": self.name,
303 "allow_zero_valuation": d.get("allow_zero_valuation"),
304 },
305 raise_error_if_no_rate=False,
306 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530307
marinationaa043fe2022-07-05 19:43:02 +0530308 rate = flt(outgoing_rate * (d.conversion_factor or 1), d.precision("rate"))
Deepesh Gargb4be2922021-01-28 13:09:56 +0530309 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530310 rate = frappe.db.get_value(ref_doctype, d.get(frappe.scrub(ref_doctype)), "rate")
Deepesh Gargb4be2922021-01-28 13:09:56 +0530311
312 if self.is_internal_transfer():
313 if rate != d.rate:
314 d.rate = rate
Ankush Menat494bd9e2022-03-28 18:52:46 +0530315 frappe.msgprint(
316 _(
317 "Row {0}: Item rate has been updated as per valuation rate since its an internal stock transfer"
318 ).format(d.idx),
319 alert=1,
320 )
Ankush Menatee0a2772022-05-12 18:17:09 +0530321 d.discount_percentage = 0.0
322 d.discount_amount = 0.0
323 d.margin_rate_or_amount = 0.0
Deepesh Gargb4be2922021-01-28 13:09:56 +0530324
Nabin Hait54d209f2013-03-01 18:51:10 +0530325 def validate_for_subcontracting(self):
Sagar Sharmafd162f92022-07-01 16:51:19 +0530326 if self.is_subcontracted and self.get("is_old_subcontracting_flow"):
Saurabhfbb342c2016-04-07 16:41:31 +0530327 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] and not self.supplier_warehouse:
Afshan27bcb2a2021-03-09 22:25:48 +0530328 frappe.throw(_("Supplier Warehouse mandatory for sub-contracted {0}").format(self.doctype))
s-aga-r6d89b2f2022-06-18 15:46:59 +0530329
Sagar Sharmafd162f92022-07-01 16:51:19 +0530330 for item in self.get("items"):
331 if item in self.sub_contracted_items and not item.bom:
332 frappe.throw(_("Please select BOM in BOM field for Item {0}").format(item.item_code))
333 if self.doctype != "Purchase Order":
334 return
335 for row in self.get("supplied_items"):
336 if not row.reserve_warehouse:
337 msg = f"Reserved Warehouse is mandatory for the Item {frappe.bold(row.rm_item_code)} in Raw Materials supplied"
338 frappe.throw(_(msg))
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530339 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530340 for item in self.get("items"):
Sagar Sharma34bda142022-05-04 15:21:31 +0530341 if item.get("bom"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530342 item.bom = None
343
nabinhait614fb752014-07-14 10:47:50 +0530344 def set_qty_as_per_stock_uom(self):
Nabin Haitdd38a262014-12-26 13:15:21 +0530345 for d in self.get("items"):
Nabin Haitfd4bcd82015-05-22 16:55:40 +0530346 if d.meta.get_field("stock_qty"):
Deepesh Garg8b0302b2019-08-05 10:14:19 +0530347 # Check if item code is present
348 # Conversion factor should not be mandatory for non itemized items
349 if not d.conversion_factor and d.item_code:
Nabin Haite6e456b2015-05-13 17:21:44 +0530350 frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
Rushabh Mehta5b51cc82014-07-21 18:25:45 +0530351 d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530352
Ankush Menat494bd9e2022-03-28 18:52:46 +0530353 if self.doctype == "Purchase Receipt" and d.meta.get_field("received_stock_qty"):
marinationd6596a12020-11-02 15:07:48 +0530354 # Set Received Qty in Stock UOM
Ankush Menat494bd9e2022-03-28 18:52:46 +0530355 d.received_stock_qty = flt(d.received_qty) * flt(
356 d.conversion_factor, d.precision("conversion_factor")
357 )
marinationd6596a12020-11-02 15:07:48 +0530358
Saurabh130c57b2016-04-04 15:49:36 +0530359 def validate_purchase_return(self):
360 for d in self.get("items"):
361 if self.is_return and flt(d.rejected_qty) != 0:
362 frappe.throw(_("Row #{0}: Rejected Qty can not be entered in Purchase Return").format(d.idx))
363
364 # validate rate with ref PR
365
366 def validate_rejected_warehouse(self):
367 for d in self.get("items"):
368 if flt(d.rejected_qty) and not d.rejected_warehouse:
Saurabhfbb342c2016-04-07 16:41:31 +0530369 if self.rejected_warehouse:
370 d.rejected_warehouse = self.rejected_warehouse
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530371
Saurabh130c57b2016-04-04 15:49:36 +0530372 if not d.rejected_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530373 frappe.throw(
374 _("Row #{0}: Rejected Warehouse is mandatory against rejected Item {1}").format(
375 d.idx, d.item_code
376 )
377 )
Saurabh130c57b2016-04-04 15:49:36 +0530378
379 # validate accepted and rejected qty
380 def validate_accepted_rejected_qty(self):
381 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530382 self.validate_negative_quantity(d, ["received_qty", "qty", "rejected_qty"])
Saurabh130c57b2016-04-04 15:49:36 +0530383
marination5fb5a752021-11-08 13:22:57 +0530384 if not flt(d.received_qty) and (flt(d.qty) or flt(d.rejected_qty)):
385 d.received_qty = flt(d.qty) + flt(d.rejected_qty)
Saurabh130c57b2016-04-04 15:49:36 +0530386
Saurabh130c57b2016-04-04 15:49:36 +0530387 # Check Received Qty = Accepted Qty + Rejected Qty
marinationafe1c452021-11-15 17:17:29 +0530388 val = flt(d.qty) + flt(d.rejected_qty)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530389 if flt(val, d.precision("received_qty")) != flt(d.received_qty, d.precision("received_qty")):
390 message = _(
391 "Row #{0}: Received Qty must be equal to Accepted + Rejected Qty for Item {1}"
392 ).format(d.idx, d.item_code)
marination05ec7cc2021-11-15 17:49:14 +0530393 frappe.throw(msg=message, title=_("Mismatch"), exc=QtyMismatchError)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530394
Saurabh4f4d0a82017-03-13 14:31:48 +0530395 def validate_negative_quantity(self, item_row, field_list):
396 if self.is_return:
397 return
398
399 item_row = item_row.as_dict()
400 for fieldname in field_list:
401 if flt(item_row[fieldname]) < 0:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530402 frappe.throw(
403 _("Row #{0}: {1} can not be negative for item {2}").format(
404 item_row["idx"],
405 frappe.get_meta(item_row.doctype).get_label(fieldname),
406 item_row["item_code"],
407 )
408 )
Saurabh4f4d0a82017-03-13 14:31:48 +0530409
Mangesh-Khairnar5e474f42019-03-06 14:46:38 +0530410 def check_for_on_hold_or_closed_status(self, ref_doctype, ref_fieldname):
411 for d in self.get("items"):
412 if d.get(ref_fieldname):
413 status = frappe.db.get_value(ref_doctype, d.get(ref_fieldname), "status")
414 if status in ("Closed", "On Hold"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530415 frappe.throw(_("{0} {1} is {2}").format(ref_doctype, d.get(ref_fieldname), status))
Mangesh-Khairnar5e474f42019-03-06 14:46:38 +0530416
Saurabhe29248b2016-04-04 11:55:52 +0530417 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait07e53762018-01-05 18:19:59 +0530418 self.update_ordered_and_reserved_qty()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530419
Saurabhe29248b2016-04-04 11:55:52 +0530420 sl_entries = []
421 stock_items = self.get_stock_items()
422
Ankush Menat494bd9e2022-03-28 18:52:46 +0530423 for d in self.get("items"):
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530424 if d.item_code not in stock_items:
425 continue
426
Rohit Waghchaureac5df1a2022-04-04 15:38:42 +0530427 if d.warehouse:
Saurabhe29248b2016-04-04 11:55:52 +0530428 pr_qty = flt(d.qty) * flt(d.conversion_factor)
429
430 if pr_qty:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530431
Ankush Menat494bd9e2022-03-28 18:52:46 +0530432 if d.from_warehouse and (
433 (not cint(self.is_return) and self.docstatus == 1)
434 or (cint(self.is_return) and self.docstatus == 2)
435 ):
436 from_warehouse_sle = self.get_sl_entries(
437 d,
438 {
439 "actual_qty": -1 * pr_qty,
440 "warehouse": d.from_warehouse,
441 "outgoing_rate": d.rate,
442 "recalculate_rate": 1,
443 "dependant_sle_voucher_detail_no": d.name,
444 },
445 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530446
447 sl_entries.append(from_warehouse_sle)
448
Ankush Menat494bd9e2022-03-28 18:52:46 +0530449 sle = self.get_sl_entries(
450 d, {"actual_qty": flt(pr_qty), "serial_no": cstr(d.serial_no).strip()}
451 )
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530452
Saurabhe29248b2016-04-04 11:55:52 +0530453 if self.is_return:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530454 outgoing_rate = get_rate_for_return(
455 self.doctype, self.name, d.item_code, self.return_against, item_row=d
456 )
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530457
Ankush Menat494bd9e2022-03-28 18:52:46 +0530458 sle.update({"outgoing_rate": outgoing_rate, "recalculate_rate": 1})
Nabin Haita77b8c92020-12-21 14:45:50 +0530459 if d.from_warehouse:
460 sle.dependant_sle_voucher_detail_no = d.name
Saurabhe29248b2016-04-04 11:55:52 +0530461 else:
Nabin Haitb81ed452016-05-11 12:52:31 +0530462 val_rate_db_precision = 6 if cint(self.precision("valuation_rate", d)) <= 6 else 9
463 incoming_rate = flt(d.valuation_rate, val_rate_db_precision)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530464 sle.update(
465 {
466 "incoming_rate": incoming_rate,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530467 "recalculate_rate": 1
468 if (self.is_subcontracted and (d.bom or d.fg_item)) or d.from_warehouse
469 else 0,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530470 }
471 )
Saurabhe29248b2016-04-04 11:55:52 +0530472 sl_entries.append(sle)
473
Ankush Menat494bd9e2022-03-28 18:52:46 +0530474 if d.from_warehouse and (
475 (not cint(self.is_return) and self.docstatus == 2)
476 or (cint(self.is_return) and self.docstatus == 1)
477 ):
478 from_warehouse_sle = self.get_sl_entries(
479 d, {"actual_qty": -1 * pr_qty, "warehouse": d.from_warehouse, "recalculate_rate": 1}
480 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530481
482 sl_entries.append(from_warehouse_sle)
483
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530484 if flt(d.rejected_qty) != 0:
485 sl_entries.append(
486 self.get_sl_entries(
487 d,
488 {
489 "warehouse": d.rejected_warehouse,
490 "actual_qty": flt(d.rejected_qty) * flt(d.conversion_factor),
491 "serial_no": cstr(d.rejected_serial_no).strip(),
492 "incoming_rate": 0.0,
493 },
Ankush Menat494bd9e2022-03-28 18:52:46 +0530494 )
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530495 )
Saurabhe29248b2016-04-04 11:55:52 +0530496
s-aga-r6d89b2f2022-06-18 15:46:59 +0530497 if self.get("is_old_subcontracting_flow"):
498 self.make_sl_entries_for_supplier_warehouse(sl_entries)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530499 self.make_sl_entries(
500 sl_entries,
501 allow_negative_stock=allow_negative_stock,
502 via_landed_cost_voucher=via_landed_cost_voucher,
503 )
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530504
Nabin Hait07e53762018-01-05 18:19:59 +0530505 def update_ordered_and_reserved_qty(self):
Nabin Hait14aa9c52016-04-18 15:54:01 +0530506 po_map = {}
507 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530508 if self.doctype == "Purchase Receipt" and d.purchase_order:
509 po_map.setdefault(d.purchase_order, []).append(d.purchase_order_item)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530510
Ankush Menat494bd9e2022-03-28 18:52:46 +0530511 elif self.doctype == "Purchase Invoice" and d.purchase_order and d.po_detail:
Nabin Hait14aa9c52016-04-18 15:54:01 +0530512 po_map.setdefault(d.purchase_order, []).append(d.po_detail)
513
514 for po, po_item_rows in po_map.items():
515 if po and po_item_rows:
516 po_obj = frappe.get_doc("Purchase Order", po)
517
518 if po_obj.status in ["Closed", "Cancelled"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530519 frappe.throw(
520 _("{0} {1} is cancelled or closed").format(_("Purchase Order"), po),
521 frappe.InvalidStatusError,
522 )
Nabin Hait14aa9c52016-04-18 15:54:01 +0530523
524 po_obj.update_ordered_qty(po_item_rows)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530525 if self.get("is_old_subcontracting_flow"):
526 po_obj.update_reserved_qty_for_subcontract()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530527
rohitwaghchaurefe226862017-12-28 16:11:27 +0530528 def on_submit(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530529 if self.get("is_return"):
rohitwaghchaurefe226862017-12-28 16:11:27 +0530530 return
531
Ankush Menat494bd9e2022-03-28 18:52:46 +0530532 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
533 field = "purchase_invoice" if self.doctype == "Purchase Invoice" else "purchase_receipt"
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530534
535 self.process_fixed_asset()
536 self.update_fixed_asset(field)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530537
Ankush Menat494bd9e2022-03-28 18:52:46 +0530538 if self.doctype in ["Purchase Order", "Purchase Receipt"]:
539 update_last_purchase_rate(self, is_submit=1)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530540
541 def on_cancel(self):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +0530542 super(BuyingController, self).on_cancel()
543
Ankush Menat494bd9e2022-03-28 18:52:46 +0530544 if self.get("is_return"):
rohitwaghchaurefe226862017-12-28 16:11:27 +0530545 return
546
Ankush Menat494bd9e2022-03-28 18:52:46 +0530547 if self.doctype in ["Purchase Order", "Purchase Receipt"]:
548 update_last_purchase_rate(self, is_submit=0)
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530549
Ankush Menat494bd9e2022-03-28 18:52:46 +0530550 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
551 field = "purchase_invoice" if self.doctype == "Purchase Invoice" else "purchase_receipt"
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530552
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530553 self.delete_linked_asset()
554 self.update_fixed_asset(field, delete_asset=True)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530555
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530556 def validate_budget(self):
557 if self.docstatus == 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530558 for data in self.get("items"):
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530559 args = data.as_dict()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530560 args.update(
561 {
562 "doctype": self.doctype,
563 "company": self.company,
564 "posting_date": (
565 self.schedule_date if self.doctype == "Material Request" else self.transaction_date
566 ),
567 }
568 )
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530569
570 validate_expense_against_budget(args)
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530571
Rohit Waghchaureab842542018-04-26 19:18:29 +0530572 def process_fixed_asset(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530573 if self.doctype == "Purchase Invoice" and not self.update_stock:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530574 return
575
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530576 asset_items = self.get_asset_items()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530577 if asset_items:
Saqibd9956092019-11-18 11:46:55 +0530578 self.auto_make_assets(asset_items)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530579
Saqibd9956092019-11-18 11:46:55 +0530580 def auto_make_assets(self, asset_items):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530581 items_data = get_asset_item_details(asset_items)
Saqibf37a46e2019-11-22 16:32:50 +0530582 messages = []
Rohit Waghchaureab842542018-04-26 19:18:29 +0530583
584 for d in self.items:
585 if d.is_fixed_asset:
586 item_data = items_data.get(d.item_code)
587
Ankush Menat494bd9e2022-03-28 18:52:46 +0530588 if item_data.get("auto_create_assets"):
Saqibd9956092019-11-18 11:46:55 +0530589 # If asset has to be auto created
590 # Check for asset naming series
Ankush Menat494bd9e2022-03-28 18:52:46 +0530591 if item_data.get("asset_naming_series"):
Saqibbba78f02020-03-31 10:49:44 +0530592 created_assets = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530593 if item_data.get("is_grouped_asset"):
Saqib Ansari35a6b582022-01-18 13:10:23 +0530594 asset = self.make_asset(d, is_grouped_asset=True)
Saqibbba78f02020-03-31 10:49:44 +0530595 created_assets.append(asset)
Saqib Ansari35a6b582022-01-18 13:10:23 +0530596 else:
597 for qty in range(cint(d.qty)):
598 asset = self.make_asset(d)
599 created_assets.append(asset)
Marica1c8cbd02020-05-02 17:55:15 +0530600
Saqibbba78f02020-03-31 10:49:44 +0530601 if len(created_assets) > 5:
602 # dont show asset form links if more than 5 assets are created
Saqibbba78f02020-03-31 10:49:44 +0530603 messages.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530604 _("{} Assets created for {}").format(len(created_assets), frappe.bold(d.item_code))
605 )
606 else:
607 assets_link = list(map(lambda d: frappe.utils.get_link_to_form("Asset", d), created_assets))
608 assets_link = frappe.bold(",".join(assets_link))
609
610 is_plural = "s" if len(created_assets) != 1 else ""
611 messages.append(
612 _("Asset{} {assets_link} created for {}").format(
613 is_plural, frappe.bold(d.item_code), assets_link=assets_link
614 )
Saqibbba78f02020-03-31 10:49:44 +0530615 )
Saqibd9956092019-11-18 11:46:55 +0530616 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530617 frappe.throw(
618 _("Row {}: Asset Naming Series is mandatory for the auto creation for item {}").format(
619 d.idx, frappe.bold(d.item_code)
620 )
621 )
Saqibd9956092019-11-18 11:46:55 +0530622 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530623 messages.append(
624 _("Assets not created for {0}. You will have to create asset manually.").format(
625 frappe.bold(d.item_code)
626 )
627 )
Saqibf37a46e2019-11-22 16:32:50 +0530628
629 for message in messages:
Saqibbba78f02020-03-31 10:49:44 +0530630 frappe.msgprint(message, title="Success", indicator="green")
Rohit Waghchaureab842542018-04-26 19:18:29 +0530631
Saqib Ansari35a6b582022-01-18 13:10:23 +0530632 def make_asset(self, row, is_grouped_asset=False):
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530633 if not row.asset_location:
634 frappe.throw(_("Row {0}: Enter location for the asset item {1}").format(row.idx, row.item_code))
635
Ankush Menat494bd9e2022-03-28 18:52:46 +0530636 item_data = frappe.db.get_value(
637 "Item", row.item_code, ["asset_naming_series", "asset_category"], as_dict=1
638 )
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530639
Saqib Ansari35a6b582022-01-18 13:10:23 +0530640 if is_grouped_asset:
641 purchase_amount = flt(row.base_amount + row.item_tax_amount)
642 else:
643 purchase_amount = flt(row.base_rate + row.item_tax_amount)
644
Ankush Menat494bd9e2022-03-28 18:52:46 +0530645 asset = frappe.get_doc(
646 {
647 "doctype": "Asset",
648 "item_code": row.item_code,
649 "asset_name": row.item_name,
650 "naming_series": item_data.get("asset_naming_series") or "AST",
651 "asset_category": item_data.get("asset_category"),
652 "location": row.asset_location,
653 "company": self.company,
654 "supplier": self.supplier,
655 "purchase_date": self.posting_date,
656 "calculate_depreciation": 1,
657 "purchase_receipt_amount": purchase_amount,
658 "gross_purchase_amount": purchase_amount,
659 "asset_quantity": row.qty if is_grouped_asset else 0,
660 "purchase_receipt": self.name if self.doctype == "Purchase Receipt" else None,
661 "purchase_invoice": self.name if self.doctype == "Purchase Invoice" else None,
662 }
663 )
Rohit Waghchaureab842542018-04-26 19:18:29 +0530664
665 asset.flags.ignore_validate = True
666 asset.flags.ignore_mandatory = True
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530667 asset.set_missing_values()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530668 asset.insert()
669
Saqibbba78f02020-03-31 10:49:44 +0530670 return asset.name
671
Ankush Menat494bd9e2022-03-28 18:52:46 +0530672 def update_fixed_asset(self, field, delete_asset=False):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530673 for d in self.get("items"):
Saqibd9956092019-11-18 11:46:55 +0530674 if d.is_fixed_asset:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530675 is_auto_create_enabled = frappe.db.get_value("Item", d.item_code, "auto_create_assets")
676 assets = frappe.db.get_all("Asset", filters={field: self.name, "item_code": d.item_code})
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530677
Saqibd9956092019-11-18 11:46:55 +0530678 for asset in assets:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530679 asset = frappe.get_doc("Asset", asset.name)
Saqibd9956092019-11-18 11:46:55 +0530680 if delete_asset and is_auto_create_enabled:
681 # need to delete movements to delete assets otherwise throws link exists error
Saqibcd3976f2019-11-25 12:24:34 +0530682 movements = frappe.db.sql(
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530683 """SELECT asm.name
Saqibcd3976f2019-11-25 12:24:34 +0530684 FROM `tabAsset Movement` asm, `tabAsset Movement Item` asm_item
Ankush Menat494bd9e2022-03-28 18:52:46 +0530685 WHERE asm_item.parent=asm.name and asm_item.asset=%s""",
686 asset.name,
687 as_dict=1,
688 )
Saqibd9956092019-11-18 11:46:55 +0530689 for movement in movements:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530690 frappe.delete_doc("Asset Movement", movement.name, force=1)
Saqibd9956092019-11-18 11:46:55 +0530691 frappe.delete_doc("Asset", asset.name, force=1)
692 continue
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530693
Saqibd9956092019-11-18 11:46:55 +0530694 if self.docstatus in [0, 1] and not asset.get(field):
695 asset.set(field, self.name)
696 asset.purchase_date = self.posting_date
697 asset.supplier = self.supplier
698 elif self.docstatus == 2:
Saqibcd3976f2019-11-25 12:24:34 +0530699 if asset.docstatus == 0:
700 asset.set(field, None)
701 asset.supplier = None
702 if asset.docstatus == 1 and delete_asset:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530703 frappe.throw(
704 _(
705 "Cannot cancel this document as it is linked with submitted asset {0}. Please cancel it to continue."
706 ).format(frappe.utils.get_link_to_form("Asset", asset.name))
707 )
Rohit Waghchaureab842542018-04-26 19:18:29 +0530708
Saqibd9956092019-11-18 11:46:55 +0530709 asset.flags.ignore_validate_update_after_submit = True
710 asset.flags.ignore_mandatory = True
711 if asset.docstatus == 0:
712 asset.flags.ignore_validate = True
Rohit Waghchaureab842542018-04-26 19:18:29 +0530713
Saqibd9956092019-11-18 11:46:55 +0530714 asset.save()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530715
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530716 def delete_linked_asset(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530717 if self.doctype == "Purchase Invoice" and not self.get("update_stock"):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530718 return
719
Nabin Hait1e7c32b2018-09-26 18:01:00 +0530720 frappe.db.sql("delete from `tabAsset Movement` where reference_name=%s", self.name)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530721
Nabin Hait5a834202017-10-05 19:51:10 +0530722 def validate_schedule_date(self):
Sahil Khan34766c02018-12-20 18:50:24 +0530723 if not self.get("items"):
724 return
Nabin Haita1138612019-10-15 12:43:27 +0530725
18alantom2a20a032021-05-05 11:59:15 +0530726 if any(d.schedule_date for d in self.get("items")):
727 # Select earliest schedule_date.
Ankush Menat494bd9e2022-03-28 18:52:46 +0530728 self.schedule_date = min(
729 d.schedule_date for d in self.get("items") if d.schedule_date is not None
730 )
Nabin Hait5a834202017-10-05 19:51:10 +0530731
732 if self.schedule_date:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530733 for d in self.get("items"):
Nabin Hait5a834202017-10-05 19:51:10 +0530734 if not d.schedule_date:
735 d.schedule_date = self.schedule_date
736
Ankush Menat494bd9e2022-03-28 18:52:46 +0530737 if (
738 d.schedule_date
739 and self.transaction_date
740 and getdate(d.schedule_date) < getdate(self.transaction_date)
741 ):
Nabin Hait96b264b2018-01-02 11:50:29 +0530742 frappe.throw(_("Row #{0}: Reqd by Date cannot be before Transaction Date").format(d.idx))
Nabin Hait5a834202017-10-05 19:51:10 +0530743 else:
Nabin Hait96b264b2018-01-02 11:50:29 +0530744 frappe.throw(_("Please enter Reqd by Date"))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530745
Zarrarfc03a042018-06-04 12:52:52 +0530746 def validate_items(self):
747 # validate items to see if they have is_purchase_item or is_subcontracted_item enabled
Ankush Menat494bd9e2022-03-28 18:52:46 +0530748 if self.doctype == "Material Request":
749 return
Zarrarfc03a042018-06-04 12:52:52 +0530750
s-aga-r6d89b2f2022-06-18 15:46:59 +0530751 if self.get("is_old_subcontracting_flow"):
752 validate_item_type(self, "is_sub_contracted_item", "subcontracted")
753 else:
754 validate_item_type(self, "is_purchase_item", "purchase")
Zarrarfc03a042018-06-04 12:52:52 +0530755
Ankush Menat494bd9e2022-03-28 18:52:46 +0530756
Rohit Waghchaureab842542018-04-26 19:18:29 +0530757def get_asset_item_details(asset_items):
758 asset_items_data = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530759 for d in frappe.get_all(
760 "Item",
761 fields=["name", "auto_create_assets", "asset_naming_series", "is_grouped_asset"],
762 filters={"name": ("in", asset_items)},
763 ):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530764 asset_items_data.setdefault(d.name, d)
765
766 return asset_items_data
Ameya Shenoy873e28d2018-06-06 05:53:19 +0000767
Ankush Menat494bd9e2022-03-28 18:52:46 +0530768
Zarrarfc03a042018-06-04 12:52:52 +0530769def validate_item_type(doc, fieldname, message):
770 # iterate through items and check if they are valid sales or purchase items
Zarrar7c088ff2018-06-05 10:32:09 +0530771 items = [d.item_code for d in doc.items if d.item_code]
772
773 # No validation check inase of creating transaction using 'Opening Invoice Creation Tool'
774 if not items:
775 return
776
Suraj Shettybfc195d2018-09-21 10:20:52 +0530777 item_list = ", ".join(["%s" % frappe.db.escape(d) for d in items])
Zarrarfc03a042018-06-04 12:52:52 +0530778
Ankush Menat494bd9e2022-03-28 18:52:46 +0530779 invalid_items = [
780 d[0]
781 for d in frappe.db.sql(
782 """
Zarrarfc03a042018-06-04 12:52:52 +0530783 select item_code from tabItem where name in ({0}) and {1}=0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530784 """.format(
785 item_list, fieldname
786 ),
787 as_list=True,
788 )
789 ]
Zarrarfc03a042018-06-04 12:52:52 +0530790
791 if invalid_items:
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530792 items = ", ".join([d for d in invalid_items])
793
794 if len(invalid_items) > 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530795 error_message = _(
796 "Following items {0} are not marked as {1} item. You can enable them as {1} item from its Item master"
797 ).format(items, message)
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530798 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530799 error_message = _(
800 "Following item {0} is not marked as {1} item. You can enable them as {1} item from its Item master"
801 ).format(items, message)
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530802
803 frappe.throw(error_message)