blob: fa091df8683afe024fecebd7fdc14c871cc4a288 [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
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
Sagar Sharma34bda142022-05-04 15:21:31 +053023class BuyingController(StockController):
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053024 def get_feed(self):
rohitwaghchaurea1064a62016-03-03 14:00:35 +053025 if self.get("supplier_name"):
Ankush Menat494bd9e2022-03-28 18:52:46 +053026 return _("From {0} | {1} {2}").format(self.supplier_name, self.currency, 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
Ankush Menat494bd9e2022-03-28 18:52:46 +053041 if self.doctype == "Purchase Invoice":
Nabin Hait14aa9c52016-04-18 15:54:01 +053042 self.validate_purchase_receipt_if_update_stock()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053043
Ankush Menat494bd9e2022-03-28 18:52:46 +053044 if self.doctype == "Purchase Receipt" or (
45 self.doctype == "Purchase Invoice" and self.update_stock
46 ):
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
Ankush Menat494bd9e2022-03-28 18:52:46 +053052 # sub-contracting
Saurabhfbb342c2016-04-07 16:41:31 +053053 self.validate_for_subcontracting()
Saurabhfbb342c2016-04-07 16:41:31 +053054 self.set_landed_cost_voucher_amount()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053055
Nabin Hait14aa9c52016-04-18 15:54:01 +053056 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Nabin Haita77b8c92020-12-21 14:45:50 +053057 self.update_valuation_rate()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053058
Rohit Waghchaure110e1522021-06-15 17:29:52 +053059 def onload(self):
60 super(BuyingController, self).onload()
Ankush Menat494bd9e2022-03-28 18:52:46 +053061 self.set_onload(
62 "backflush_based_on",
63 frappe.db.get_single_value(
64 "Buying Settings", "backflush_raw_materials_of_subcontract_based_on"
65 ),
66 )
Rohit Waghchaure110e1522021-06-15 17:29:52 +053067
Anand Doshi3543f302013-05-24 19:25:01 +053068 def set_missing_values(self, for_validate=False):
Anand Doshiabc10032013-06-14 17:44:03 +053069 super(BuyingController, self).set_missing_values(for_validate)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053070
Rushabh Mehta0b995402013-08-09 15:29:59 +053071 self.set_supplier_from_item_default()
Nabin Hait096d3632013-10-17 17:01:14 +053072 self.set_price_list_currency("Buying")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053073
Anand Doshi3543f302013-05-24 19:25:01 +053074 # set contact and address details for supplier, if they are not mentioned
Nabin Hait365ae272014-04-03 17:38:54 +053075 if getattr(self, "supplier", None):
marination78b6b292022-01-24 13:39:10 +053076 self.update_if_missing(
77 get_party_details(
78 self.supplier,
79 party_type="Supplier",
80 doctype=self.doctype,
81 company=self.company,
82 party_address=self.get("supplier_address"),
Ankush Menat494bd9e2022-03-28 18:52:46 +053083 shipping_address=self.get("shipping_address"),
84 fetch_payment_terms_template=not self.get("ignore_default_payment_terms_template"),
85 ignore_permissions=self.flags.ignore_permissions,
marination78b6b292022-01-24 13:39:10 +053086 )
87 )
Rushabh Mehta886c9ef2013-07-08 12:08:06 +053088
Nabin Haitcccc45e2016-10-05 17:15:43 +053089 self.set_missing_item_details(for_validate)
Rushabh Mehta436467a2013-07-08 12:37:59 +053090
Rushabh Mehta0b995402013-08-09 15:29:59 +053091 def set_supplier_from_item_default(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +053092 if self.meta.get_field("supplier") and not self.supplier:
Nabin Haitdd38a262014-12-26 13:15:21 +053093 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +053094 supplier = frappe.db.get_value(
95 "Item Default", {"parent": d.item_code, "company": self.company}, "default_supplier"
96 )
Rushabh Mehta0b995402013-08-09 15:29:59 +053097 if supplier:
Anand Doshif78d1ae2014-03-28 13:55:00 +053098 self.supplier = supplier
Shreya Shah3c9839f2018-07-17 18:01:44 +053099 else:
100 item_group = frappe.db.get_value("Item", d.item_code, "item_group")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530101 supplier = frappe.db.get_value(
102 "Item Default", {"parent": item_group, "company": self.company}, "default_supplier"
103 )
Shreya Shah3c9839f2018-07-17 18:01:44 +0530104 if supplier:
105 self.supplier = supplier
Rushabh Mehta0b995402013-08-09 15:29:59 +0530106 break
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530107
Nabin Hait205f7ce2013-04-26 13:35:06 +0530108 def validate_stock_or_nonstock_items(self):
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530109 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 +0530110 msg = _('Tax Category has been changed to "Total" because all the Items are non-stock items')
111 self.update_tax_category(msg)
112
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530113 def update_tax_category(self, msg):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530114 tax_for_valuation = [
115 d for d in self.get("taxes") if d.category in ["Valuation", "Valuation and Total"]
116 ]
tundebabzy9a346202017-06-16 11:00:14 +0100117
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530118 if tax_for_valuation:
119 for d in tax_for_valuation:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530120 d.category = "Total"
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530121
122 msgprint(msg)
Marica1c8cbd02020-05-02 17:55:15 +0530123
Saqib562fd0e2020-04-08 12:11:40 +0530124 def validate_asset_return(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530125 if self.doctype not in ["Purchase Receipt", "Purchase Invoice"] or not self.is_return:
Saqib562fd0e2020-04-08 12:11:40 +0530126 return
127
Ankush Menat494bd9e2022-03-28 18:52:46 +0530128 purchase_doc_field = (
129 "purchase_receipt" if self.doctype == "Purchase Receipt" else "purchase_invoice"
130 )
131 not_cancelled_asset = [
132 d.name
133 for d in frappe.db.get_all("Asset", {purchase_doc_field: self.return_against, "docstatus": 1})
134 ]
Saqib562fd0e2020-04-08 12:11:40 +0530135 if self.is_return and len(not_cancelled_asset):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530136 frappe.throw(
137 _(
138 "{} has submitted assets linked to it. You need to cancel the assets to create purchase return."
139 ).format(self.return_against),
140 title=_("Not Allowed"),
141 )
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530142
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530143 def get_asset_items(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530144 if self.doctype not in ["Purchase Order", "Purchase Invoice", "Purchase Receipt"]:
Rohit Waghchaured644e6d2018-05-12 15:27:18 +0530145 return []
146
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530147 return [d.item_code for d in self.items if d.is_fixed_asset]
148
Saurabhfbb342c2016-04-07 16:41:31 +0530149 def set_landed_cost_voucher_amount(self):
150 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530151 lc_voucher_data = frappe.db.sql(
152 """select sum(applicable_charges), cost_center
Saurabhfbb342c2016-04-07 16:41:31 +0530153 from `tabLanded Cost Item`
Ankush Menat494bd9e2022-03-28 18:52:46 +0530154 where docstatus = 1 and purchase_receipt_item = %s""",
155 d.name,
156 )
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530157 d.landed_cost_voucher_amount = lc_voucher_data[0][0] if lc_voucher_data else 0.0
158 if not d.cost_center and lc_voucher_data and lc_voucher_data[0][1]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530159 d.db_set("cost_center", lc_voucher_data[0][1])
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530160
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530161 def validate_from_warehouse(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530162 for item in self.get("items"):
163 if item.get("from_warehouse") and (item.get("from_warehouse") == item.get("warehouse")):
164 frappe.throw(
165 _("Row #{0}: Accepted Warehouse and Supplier Warehouse cannot be same").format(item.idx)
166 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530167
Sagar Sharma409df262022-04-19 14:57:31 +0530168 if item.get("from_warehouse") and self.get("is_subcontracted"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530169 frappe.throw(
170 _(
171 "Row #{0}: Cannot select Supplier Warehouse while suppling raw materials to subcontractor"
172 ).format(item.idx)
173 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530174
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530175 def set_supplier_address(self):
176 address_dict = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530177 "supplier_address": "address_display",
178 "shipping_address": "shipping_address_display",
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530179 }
180
181 for address_field, address_display_field in address_dict.items():
182 if self.get(address_field):
183 self.set(address_display_field, get_address_display(self.get(address_field)))
184
Nabin Haitd3b62502013-01-21 17:24:31 +0530185 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530186 from frappe.utils import money_in_words
Ankush Menat494bd9e2022-03-28 18:52:46 +0530187
Nabin Hait5690be12015-02-12 16:09:11 +0530188 if self.meta.get_field("base_in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530189 if self.meta.get_field("base_rounded_total") and not self.is_rounded_total_disabled():
190 amount = self.base_rounded_total
191 else:
192 amount = self.base_grand_total
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530193 self.base_in_words = money_in_words(amount, self.company_currency)
194
Nabin Hait5b4c2942013-01-22 11:12:02 +0530195 if self.meta.get_field("in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530196 if self.meta.get_field("rounded_total") and not self.is_rounded_total_disabled():
197 amount = self.rounded_total
198 else:
199 amount = self.grand_total
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530200
201 self.in_words = money_in_words(amount, self.currency)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530202
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530203 # update valuation rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530204 def update_valuation_rate(self, reset_outgoing_rate=True):
Anand Doshi8595fcf2013-02-08 19:28:14 +0530205 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530206 item_tax_amount is the total tax amount applied on that item
207 stored for valuation
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530208
Ankush Menat494bd9e2022-03-28 18:52:46 +0530209 TODO: rename item_tax_amount to valuation_tax_amount
Anand Doshi8595fcf2013-02-08 19:28:14 +0530210 """
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530211 stock_and_asset_items = []
Saqibd9956092019-11-18 11:46:55 +0530212 stock_and_asset_items = self.get_stock_items() + self.get_asset_items()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530213
Saqibd9956092019-11-18 11:46:55 +0530214 stock_and_asset_items_qty, stock_and_asset_items_amount = 0, 0
215 last_item_idx = 1
Nabin Haita77b8c92020-12-21 14:45:50 +0530216 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530217 if d.item_code and d.item_code in stock_and_asset_items:
Saqibd9956092019-11-18 11:46:55 +0530218 stock_and_asset_items_qty += flt(d.qty)
219 stock_and_asset_items_amount += flt(d.base_net_amount)
220 last_item_idx = d.idx
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530221
Ankush Menat494bd9e2022-03-28 18:52:46 +0530222 total_valuation_amount = sum(
223 flt(d.base_tax_amount_after_discount_amount)
224 for d in self.get("taxes")
225 if d.category in ["Valuation", "Valuation and Total"]
226 )
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530227
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530228 valuation_amount_adjustment = total_valuation_amount
Nabin Haita77b8c92020-12-21 14:45:50 +0530229 for i, item in enumerate(self.get("items")):
Saqibd9956092019-11-18 11:46:55 +0530230 if item.item_code and item.qty and item.item_code in stock_and_asset_items:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530231 item_proportion = (
232 flt(item.base_net_amount) / stock_and_asset_items_amount
233 if stock_and_asset_items_amount
Saqibd9956092019-11-18 11:46:55 +0530234 else flt(item.qty) / stock_and_asset_items_qty
Ankush Menat494bd9e2022-03-28 18:52:46 +0530235 )
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530236
Saqibd9956092019-11-18 11:46:55 +0530237 if i == (last_item_idx - 1):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530238 item.item_tax_amount = flt(
239 valuation_amount_adjustment, self.precision("item_tax_amount", item)
240 )
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530241 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530242 item.item_tax_amount = flt(
243 item_proportion * total_valuation_amount, self.precision("item_tax_amount", item)
244 )
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530245 valuation_amount_adjustment -= item.item_tax_amount
246
Anand Doshi39384d32013-05-11 19:39:53 +0530247 self.round_floats_in(item)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530248 if flt(item.conversion_factor) == 0.0:
249 item.conversion_factor = (
250 get_conversion_factor(item.item_code, item.uom).get("conversion_factor") or 1.0
251 )
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530252
Rushabh Mehta54047782013-12-26 11:07:46 +0530253 qty_in_stock_uom = flt(item.qty * item.conversion_factor)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530254 item.valuation_rate = (
Sagar Sharma213113b2022-05-20 11:56:25 +0530255 item.base_net_amount + item.item_tax_amount + flt(item.landed_cost_voucher_amount)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530256 ) / qty_in_stock_uom
Anand Doshi4a7248e2013-02-27 18:10:30 +0530257 else:
Anand Doshi5af812a2013-05-10 19:23:02 +0530258 item.valuation_rate = 0.0
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530259
Deepesh Gargb4be2922021-01-28 13:09:56 +0530260 def set_incoming_rate(self):
261 if self.doctype not in ("Purchase Receipt", "Purchase Invoice", "Purchase Order"):
262 return
263
264 ref_doctype_map = {
265 "Purchase Order": "Sales Order Item",
266 "Purchase Receipt": "Delivery Note Item",
267 "Purchase Invoice": "Sales Invoice Item",
268 }
269
270 ref_doctype = ref_doctype_map.get(self.doctype)
271 items = self.get("items")
272 for d in items:
273 if not cint(self.get("is_return")):
274 # Get outgoing rate based on original item cost based on valuation method
275
276 if not d.get(frappe.scrub(ref_doctype)):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530277 outgoing_rate = get_incoming_rate(
278 {
279 "item_code": d.item_code,
280 "warehouse": d.get("from_warehouse"),
281 "posting_date": self.get("posting_date") or self.get("transation_date"),
282 "posting_time": self.get("posting_time"),
283 "qty": -1 * flt(d.get("stock_qty")),
284 "serial_no": d.get("serial_no"),
285 "batch_no": d.get("batch_no"),
286 "company": self.company,
287 "voucher_type": self.doctype,
288 "voucher_no": self.name,
289 "allow_zero_valuation": d.get("allow_zero_valuation"),
290 },
291 raise_error_if_no_rate=False,
292 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530293
Ankush Menat494bd9e2022-03-28 18:52:46 +0530294 rate = flt(outgoing_rate * d.conversion_factor, d.precision("rate"))
Deepesh Gargb4be2922021-01-28 13:09:56 +0530295 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530296 rate = frappe.db.get_value(ref_doctype, d.get(frappe.scrub(ref_doctype)), "rate")
Deepesh Gargb4be2922021-01-28 13:09:56 +0530297
298 if self.is_internal_transfer():
299 if rate != d.rate:
300 d.rate = rate
Ankush Menat494bd9e2022-03-28 18:52:46 +0530301 frappe.msgprint(
302 _(
303 "Row {0}: Item rate has been updated as per valuation rate since its an internal stock transfer"
304 ).format(d.idx),
305 alert=1,
306 )
Ankush Menatee0a2772022-05-12 18:17:09 +0530307 d.discount_percentage = 0.0
308 d.discount_amount = 0.0
309 d.margin_rate_or_amount = 0.0
Deepesh Gargb4be2922021-01-28 13:09:56 +0530310
Nabin Hait54d209f2013-03-01 18:51:10 +0530311 def validate_for_subcontracting(self):
Sagar Sharma409df262022-04-19 14:57:31 +0530312 if self.is_subcontracted:
Saurabhfbb342c2016-04-07 16:41:31 +0530313 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] and not self.supplier_warehouse:
Afshan27bcb2a2021-03-09 22:25:48 +0530314 frappe.throw(_("Supplier Warehouse mandatory for sub-contracted {0}").format(self.doctype))
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530315 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530316 for item in self.get("items"):
Sagar Sharma34bda142022-05-04 15:21:31 +0530317 if item.get("bom"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530318 item.bom = None
319
nabinhait614fb752014-07-14 10:47:50 +0530320 def set_qty_as_per_stock_uom(self):
Nabin Haitdd38a262014-12-26 13:15:21 +0530321 for d in self.get("items"):
Nabin Haitfd4bcd82015-05-22 16:55:40 +0530322 if d.meta.get_field("stock_qty"):
Deepesh Garg8b0302b2019-08-05 10:14:19 +0530323 # Check if item code is present
324 # Conversion factor should not be mandatory for non itemized items
325 if not d.conversion_factor and d.item_code:
Nabin Haite6e456b2015-05-13 17:21:44 +0530326 frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
Rushabh Mehta5b51cc82014-07-21 18:25:45 +0530327 d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530328
Ankush Menat494bd9e2022-03-28 18:52:46 +0530329 if self.doctype == "Purchase Receipt" and d.meta.get_field("received_stock_qty"):
marinationd6596a12020-11-02 15:07:48 +0530330 # Set Received Qty in Stock UOM
Ankush Menat494bd9e2022-03-28 18:52:46 +0530331 d.received_stock_qty = flt(d.received_qty) * flt(
332 d.conversion_factor, d.precision("conversion_factor")
333 )
marinationd6596a12020-11-02 15:07:48 +0530334
Saurabh130c57b2016-04-04 15:49:36 +0530335 def validate_purchase_return(self):
336 for d in self.get("items"):
337 if self.is_return and flt(d.rejected_qty) != 0:
338 frappe.throw(_("Row #{0}: Rejected Qty can not be entered in Purchase Return").format(d.idx))
339
340 # validate rate with ref PR
341
342 def validate_rejected_warehouse(self):
343 for d in self.get("items"):
344 if flt(d.rejected_qty) and not d.rejected_warehouse:
Saurabhfbb342c2016-04-07 16:41:31 +0530345 if self.rejected_warehouse:
346 d.rejected_warehouse = self.rejected_warehouse
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530347
Saurabh130c57b2016-04-04 15:49:36 +0530348 if not d.rejected_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530349 frappe.throw(
350 _("Row #{0}: Rejected Warehouse is mandatory against rejected Item {1}").format(
351 d.idx, d.item_code
352 )
353 )
Saurabh130c57b2016-04-04 15:49:36 +0530354
355 # validate accepted and rejected qty
356 def validate_accepted_rejected_qty(self):
357 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530358 self.validate_negative_quantity(d, ["received_qty", "qty", "rejected_qty"])
Saurabh130c57b2016-04-04 15:49:36 +0530359
marination5fb5a752021-11-08 13:22:57 +0530360 if not flt(d.received_qty) and (flt(d.qty) or flt(d.rejected_qty)):
361 d.received_qty = flt(d.qty) + flt(d.rejected_qty)
Saurabh130c57b2016-04-04 15:49:36 +0530362
Saurabh130c57b2016-04-04 15:49:36 +0530363 # Check Received Qty = Accepted Qty + Rejected Qty
marinationafe1c452021-11-15 17:17:29 +0530364 val = flt(d.qty) + flt(d.rejected_qty)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530365 if flt(val, d.precision("received_qty")) != flt(d.received_qty, d.precision("received_qty")):
366 message = _(
367 "Row #{0}: Received Qty must be equal to Accepted + Rejected Qty for Item {1}"
368 ).format(d.idx, d.item_code)
marination05ec7cc2021-11-15 17:49:14 +0530369 frappe.throw(msg=message, title=_("Mismatch"), exc=QtyMismatchError)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530370
Saurabh4f4d0a82017-03-13 14:31:48 +0530371 def validate_negative_quantity(self, item_row, field_list):
372 if self.is_return:
373 return
374
375 item_row = item_row.as_dict()
376 for fieldname in field_list:
377 if flt(item_row[fieldname]) < 0:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530378 frappe.throw(
379 _("Row #{0}: {1} can not be negative for item {2}").format(
380 item_row["idx"],
381 frappe.get_meta(item_row.doctype).get_label(fieldname),
382 item_row["item_code"],
383 )
384 )
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"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530391 frappe.throw(_("{0} {1} is {2}").format(ref_doctype, d.get(ref_fieldname), status))
Mangesh-Khairnar5e474f42019-03-06 14:46:38 +0530392
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
Ankush Menat494bd9e2022-03-28 18:52:46 +0530399 for d in self.get("items"):
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530400 if d.item_code not in stock_items:
401 continue
402
Rohit Waghchaureac5df1a2022-04-04 15:38:42 +0530403 if d.warehouse:
Saurabhe29248b2016-04-04 11:55:52 +0530404 pr_qty = flt(d.qty) * flt(d.conversion_factor)
405
406 if pr_qty:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530407
Ankush Menat494bd9e2022-03-28 18:52:46 +0530408 if d.from_warehouse and (
409 (not cint(self.is_return) and self.docstatus == 1)
410 or (cint(self.is_return) and self.docstatus == 2)
411 ):
412 from_warehouse_sle = self.get_sl_entries(
413 d,
414 {
415 "actual_qty": -1 * pr_qty,
416 "warehouse": d.from_warehouse,
417 "outgoing_rate": d.rate,
418 "recalculate_rate": 1,
419 "dependant_sle_voucher_detail_no": d.name,
420 },
421 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530422
423 sl_entries.append(from_warehouse_sle)
424
Ankush Menat494bd9e2022-03-28 18:52:46 +0530425 sle = self.get_sl_entries(
426 d, {"actual_qty": flt(pr_qty), "serial_no": cstr(d.serial_no).strip()}
427 )
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530428
Saurabhe29248b2016-04-04 11:55:52 +0530429 if self.is_return:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530430 outgoing_rate = get_rate_for_return(
431 self.doctype, self.name, d.item_code, self.return_against, item_row=d
432 )
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530433
Ankush Menat494bd9e2022-03-28 18:52:46 +0530434 sle.update({"outgoing_rate": outgoing_rate, "recalculate_rate": 1})
Nabin Haita77b8c92020-12-21 14:45:50 +0530435 if d.from_warehouse:
436 sle.dependant_sle_voucher_detail_no = d.name
Saurabhe29248b2016-04-04 11:55:52 +0530437 else:
Nabin Haitb81ed452016-05-11 12:52:31 +0530438 val_rate_db_precision = 6 if cint(self.precision("valuation_rate", d)) <= 6 else 9
439 incoming_rate = flt(d.valuation_rate, val_rate_db_precision)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530440 sle.update(
441 {
442 "incoming_rate": incoming_rate,
Sagar Sharma34bda142022-05-04 15:21:31 +0530443 "recalculate_rate": 1 if (self.is_subcontracted and d.fg_item) or d.from_warehouse else 0,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530444 }
445 )
Saurabhe29248b2016-04-04 11:55:52 +0530446 sl_entries.append(sle)
447
Ankush Menat494bd9e2022-03-28 18:52:46 +0530448 if d.from_warehouse and (
449 (not cint(self.is_return) and self.docstatus == 2)
450 or (cint(self.is_return) and self.docstatus == 1)
451 ):
452 from_warehouse_sle = self.get_sl_entries(
453 d, {"actual_qty": -1 * pr_qty, "warehouse": d.from_warehouse, "recalculate_rate": 1}
454 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530455
456 sl_entries.append(from_warehouse_sle)
457
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530458 if flt(d.rejected_qty) != 0:
459 sl_entries.append(
460 self.get_sl_entries(
461 d,
462 {
463 "warehouse": d.rejected_warehouse,
464 "actual_qty": flt(d.rejected_qty) * flt(d.conversion_factor),
465 "serial_no": cstr(d.rejected_serial_no).strip(),
466 "incoming_rate": 0.0,
467 },
Ankush Menat494bd9e2022-03-28 18:52:46 +0530468 )
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530469 )
Saurabhe29248b2016-04-04 11:55:52 +0530470
Ankush Menat494bd9e2022-03-28 18:52:46 +0530471 self.make_sl_entries(
472 sl_entries,
473 allow_negative_stock=allow_negative_stock,
474 via_landed_cost_voucher=via_landed_cost_voucher,
475 )
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530476
Nabin Hait07e53762018-01-05 18:19:59 +0530477 def update_ordered_and_reserved_qty(self):
Nabin Hait14aa9c52016-04-18 15:54:01 +0530478 po_map = {}
479 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530480 if self.doctype == "Purchase Receipt" and d.purchase_order:
481 po_map.setdefault(d.purchase_order, []).append(d.purchase_order_item)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530482
Ankush Menat494bd9e2022-03-28 18:52:46 +0530483 elif self.doctype == "Purchase Invoice" and d.purchase_order and d.po_detail:
Nabin Hait14aa9c52016-04-18 15:54:01 +0530484 po_map.setdefault(d.purchase_order, []).append(d.po_detail)
485
486 for po, po_item_rows in po_map.items():
487 if po and po_item_rows:
488 po_obj = frappe.get_doc("Purchase Order", po)
489
490 if po_obj.status in ["Closed", "Cancelled"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530491 frappe.throw(
492 _("{0} {1} is cancelled or closed").format(_("Purchase Order"), po),
493 frappe.InvalidStatusError,
494 )
Nabin Hait14aa9c52016-04-18 15:54:01 +0530495
496 po_obj.update_ordered_qty(po_item_rows)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530497
rohitwaghchaurefe226862017-12-28 16:11:27 +0530498 def on_submit(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530499 if self.get("is_return"):
rohitwaghchaurefe226862017-12-28 16:11:27 +0530500 return
501
Ankush Menat494bd9e2022-03-28 18:52:46 +0530502 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
503 field = "purchase_invoice" if self.doctype == "Purchase Invoice" else "purchase_receipt"
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530504
505 self.process_fixed_asset()
506 self.update_fixed_asset(field)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530507
Ankush Menat494bd9e2022-03-28 18:52:46 +0530508 if self.doctype in ["Purchase Order", "Purchase Receipt"]:
509 update_last_purchase_rate(self, is_submit=1)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530510
511 def on_cancel(self):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +0530512 super(BuyingController, self).on_cancel()
513
Ankush Menat494bd9e2022-03-28 18:52:46 +0530514 if self.get("is_return"):
rohitwaghchaurefe226862017-12-28 16:11:27 +0530515 return
516
Ankush Menat494bd9e2022-03-28 18:52:46 +0530517 if self.doctype in ["Purchase Order", "Purchase Receipt"]:
518 update_last_purchase_rate(self, is_submit=0)
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530519
Ankush Menat494bd9e2022-03-28 18:52:46 +0530520 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
521 field = "purchase_invoice" if self.doctype == "Purchase Invoice" else "purchase_receipt"
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530522
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530523 self.delete_linked_asset()
524 self.update_fixed_asset(field, delete_asset=True)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530525
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530526 def validate_budget(self):
527 if self.docstatus == 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530528 for data in self.get("items"):
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530529 args = data.as_dict()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530530 args.update(
531 {
532 "doctype": self.doctype,
533 "company": self.company,
534 "posting_date": (
535 self.schedule_date if self.doctype == "Material Request" else self.transaction_date
536 ),
537 }
538 )
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530539
540 validate_expense_against_budget(args)
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530541
Rohit Waghchaureab842542018-04-26 19:18:29 +0530542 def process_fixed_asset(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530543 if self.doctype == "Purchase Invoice" and not self.update_stock:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530544 return
545
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530546 asset_items = self.get_asset_items()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530547 if asset_items:
Saqibd9956092019-11-18 11:46:55 +0530548 self.auto_make_assets(asset_items)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530549
Saqibd9956092019-11-18 11:46:55 +0530550 def auto_make_assets(self, asset_items):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530551 items_data = get_asset_item_details(asset_items)
Saqibf37a46e2019-11-22 16:32:50 +0530552 messages = []
Rohit Waghchaureab842542018-04-26 19:18:29 +0530553
554 for d in self.items:
555 if d.is_fixed_asset:
556 item_data = items_data.get(d.item_code)
557
Ankush Menat494bd9e2022-03-28 18:52:46 +0530558 if item_data.get("auto_create_assets"):
Saqibd9956092019-11-18 11:46:55 +0530559 # If asset has to be auto created
560 # Check for asset naming series
Ankush Menat494bd9e2022-03-28 18:52:46 +0530561 if item_data.get("asset_naming_series"):
Saqibbba78f02020-03-31 10:49:44 +0530562 created_assets = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530563 if item_data.get("is_grouped_asset"):
Saqib Ansari35a6b582022-01-18 13:10:23 +0530564 asset = self.make_asset(d, is_grouped_asset=True)
Saqibbba78f02020-03-31 10:49:44 +0530565 created_assets.append(asset)
Saqib Ansari35a6b582022-01-18 13:10:23 +0530566 else:
567 for qty in range(cint(d.qty)):
568 asset = self.make_asset(d)
569 created_assets.append(asset)
Marica1c8cbd02020-05-02 17:55:15 +0530570
Saqibbba78f02020-03-31 10:49:44 +0530571 if len(created_assets) > 5:
572 # dont show asset form links if more than 5 assets are created
Saqibbba78f02020-03-31 10:49:44 +0530573 messages.append(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530574 _("{} Assets created for {}").format(len(created_assets), frappe.bold(d.item_code))
575 )
576 else:
577 assets_link = list(map(lambda d: frappe.utils.get_link_to_form("Asset", d), created_assets))
578 assets_link = frappe.bold(",".join(assets_link))
579
580 is_plural = "s" if len(created_assets) != 1 else ""
581 messages.append(
582 _("Asset{} {assets_link} created for {}").format(
583 is_plural, frappe.bold(d.item_code), assets_link=assets_link
584 )
Saqibbba78f02020-03-31 10:49:44 +0530585 )
Saqibd9956092019-11-18 11:46:55 +0530586 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530587 frappe.throw(
588 _("Row {}: Asset Naming Series is mandatory for the auto creation for item {}").format(
589 d.idx, frappe.bold(d.item_code)
590 )
591 )
Saqibd9956092019-11-18 11:46:55 +0530592 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530593 messages.append(
594 _("Assets not created for {0}. You will have to create asset manually.").format(
595 frappe.bold(d.item_code)
596 )
597 )
Saqibf37a46e2019-11-22 16:32:50 +0530598
599 for message in messages:
Saqibbba78f02020-03-31 10:49:44 +0530600 frappe.msgprint(message, title="Success", indicator="green")
Rohit Waghchaureab842542018-04-26 19:18:29 +0530601
Saqib Ansari35a6b582022-01-18 13:10:23 +0530602 def make_asset(self, row, is_grouped_asset=False):
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530603 if not row.asset_location:
604 frappe.throw(_("Row {0}: Enter location for the asset item {1}").format(row.idx, row.item_code))
605
Ankush Menat494bd9e2022-03-28 18:52:46 +0530606 item_data = frappe.db.get_value(
607 "Item", row.item_code, ["asset_naming_series", "asset_category"], as_dict=1
608 )
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530609
Saqib Ansari35a6b582022-01-18 13:10:23 +0530610 if is_grouped_asset:
611 purchase_amount = flt(row.base_amount + row.item_tax_amount)
612 else:
613 purchase_amount = flt(row.base_rate + row.item_tax_amount)
614
Ankush Menat494bd9e2022-03-28 18:52:46 +0530615 asset = frappe.get_doc(
616 {
617 "doctype": "Asset",
618 "item_code": row.item_code,
619 "asset_name": row.item_name,
620 "naming_series": item_data.get("asset_naming_series") or "AST",
621 "asset_category": item_data.get("asset_category"),
622 "location": row.asset_location,
623 "company": self.company,
624 "supplier": self.supplier,
625 "purchase_date": self.posting_date,
626 "calculate_depreciation": 1,
627 "purchase_receipt_amount": purchase_amount,
628 "gross_purchase_amount": purchase_amount,
629 "asset_quantity": row.qty if is_grouped_asset else 0,
630 "purchase_receipt": self.name if self.doctype == "Purchase Receipt" else None,
631 "purchase_invoice": self.name if self.doctype == "Purchase Invoice" else None,
632 }
633 )
Rohit Waghchaureab842542018-04-26 19:18:29 +0530634
635 asset.flags.ignore_validate = True
636 asset.flags.ignore_mandatory = True
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530637 asset.set_missing_values()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530638 asset.insert()
639
Saqibbba78f02020-03-31 10:49:44 +0530640 return asset.name
641
Ankush Menat494bd9e2022-03-28 18:52:46 +0530642 def update_fixed_asset(self, field, delete_asset=False):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530643 for d in self.get("items"):
Saqibd9956092019-11-18 11:46:55 +0530644 if d.is_fixed_asset:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530645 is_auto_create_enabled = frappe.db.get_value("Item", d.item_code, "auto_create_assets")
646 assets = frappe.db.get_all("Asset", filters={field: self.name, "item_code": d.item_code})
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530647
Saqibd9956092019-11-18 11:46:55 +0530648 for asset in assets:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530649 asset = frappe.get_doc("Asset", asset.name)
Saqibd9956092019-11-18 11:46:55 +0530650 if delete_asset and is_auto_create_enabled:
651 # need to delete movements to delete assets otherwise throws link exists error
Saqibcd3976f2019-11-25 12:24:34 +0530652 movements = frappe.db.sql(
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530653 """SELECT asm.name
Saqibcd3976f2019-11-25 12:24:34 +0530654 FROM `tabAsset Movement` asm, `tabAsset Movement Item` asm_item
Ankush Menat494bd9e2022-03-28 18:52:46 +0530655 WHERE asm_item.parent=asm.name and asm_item.asset=%s""",
656 asset.name,
657 as_dict=1,
658 )
Saqibd9956092019-11-18 11:46:55 +0530659 for movement in movements:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530660 frappe.delete_doc("Asset Movement", movement.name, force=1)
Saqibd9956092019-11-18 11:46:55 +0530661 frappe.delete_doc("Asset", asset.name, force=1)
662 continue
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530663
Saqibd9956092019-11-18 11:46:55 +0530664 if self.docstatus in [0, 1] and not asset.get(field):
665 asset.set(field, self.name)
666 asset.purchase_date = self.posting_date
667 asset.supplier = self.supplier
668 elif self.docstatus == 2:
Saqibcd3976f2019-11-25 12:24:34 +0530669 if asset.docstatus == 0:
670 asset.set(field, None)
671 asset.supplier = None
672 if asset.docstatus == 1 and delete_asset:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530673 frappe.throw(
674 _(
675 "Cannot cancel this document as it is linked with submitted asset {0}. Please cancel it to continue."
676 ).format(frappe.utils.get_link_to_form("Asset", asset.name))
677 )
Rohit Waghchaureab842542018-04-26 19:18:29 +0530678
Saqibd9956092019-11-18 11:46:55 +0530679 asset.flags.ignore_validate_update_after_submit = True
680 asset.flags.ignore_mandatory = True
681 if asset.docstatus == 0:
682 asset.flags.ignore_validate = True
Rohit Waghchaureab842542018-04-26 19:18:29 +0530683
Saqibd9956092019-11-18 11:46:55 +0530684 asset.save()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530685
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530686 def delete_linked_asset(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530687 if self.doctype == "Purchase Invoice" and not self.get("update_stock"):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530688 return
689
Nabin Hait1e7c32b2018-09-26 18:01:00 +0530690 frappe.db.sql("delete from `tabAsset Movement` where reference_name=%s", self.name)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530691
Nabin Hait5a834202017-10-05 19:51:10 +0530692 def validate_schedule_date(self):
Sahil Khan34766c02018-12-20 18:50:24 +0530693 if not self.get("items"):
694 return
Nabin Haita1138612019-10-15 12:43:27 +0530695
18alantom2a20a032021-05-05 11:59:15 +0530696 if any(d.schedule_date for d in self.get("items")):
697 # Select earliest schedule_date.
Ankush Menat494bd9e2022-03-28 18:52:46 +0530698 self.schedule_date = min(
699 d.schedule_date for d in self.get("items") if d.schedule_date is not None
700 )
Nabin Hait5a834202017-10-05 19:51:10 +0530701
702 if self.schedule_date:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530703 for d in self.get("items"):
Nabin Hait5a834202017-10-05 19:51:10 +0530704 if not d.schedule_date:
705 d.schedule_date = self.schedule_date
706
Ankush Menat494bd9e2022-03-28 18:52:46 +0530707 if (
708 d.schedule_date
709 and self.transaction_date
710 and getdate(d.schedule_date) < getdate(self.transaction_date)
711 ):
Nabin Hait96b264b2018-01-02 11:50:29 +0530712 frappe.throw(_("Row #{0}: Reqd by Date cannot be before Transaction Date").format(d.idx))
Nabin Hait5a834202017-10-05 19:51:10 +0530713 else:
Nabin Hait96b264b2018-01-02 11:50:29 +0530714 frappe.throw(_("Please enter Reqd by Date"))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530715
Zarrarfc03a042018-06-04 12:52:52 +0530716 def validate_items(self):
717 # validate items to see if they have is_purchase_item or is_subcontracted_item enabled
Ankush Menat494bd9e2022-03-28 18:52:46 +0530718 if self.doctype == "Material Request":
719 return
Zarrarfc03a042018-06-04 12:52:52 +0530720
Sagar Sharma77db8432022-05-05 19:41:05 +0530721 validate_item_type(self, "is_purchase_item", "purchase")
Zarrarfc03a042018-06-04 12:52:52 +0530722
Ankush Menat494bd9e2022-03-28 18:52:46 +0530723
Rohit Waghchaureab842542018-04-26 19:18:29 +0530724def get_asset_item_details(asset_items):
725 asset_items_data = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530726 for d in frappe.get_all(
727 "Item",
728 fields=["name", "auto_create_assets", "asset_naming_series", "is_grouped_asset"],
729 filters={"name": ("in", asset_items)},
730 ):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530731 asset_items_data.setdefault(d.name, d)
732
733 return asset_items_data
Ameya Shenoy873e28d2018-06-06 05:53:19 +0000734
Ankush Menat494bd9e2022-03-28 18:52:46 +0530735
Zarrarfc03a042018-06-04 12:52:52 +0530736def validate_item_type(doc, fieldname, message):
737 # iterate through items and check if they are valid sales or purchase items
Zarrar7c088ff2018-06-05 10:32:09 +0530738 items = [d.item_code for d in doc.items if d.item_code]
739
740 # No validation check inase of creating transaction using 'Opening Invoice Creation Tool'
741 if not items:
742 return
743
Suraj Shettybfc195d2018-09-21 10:20:52 +0530744 item_list = ", ".join(["%s" % frappe.db.escape(d) for d in items])
Zarrarfc03a042018-06-04 12:52:52 +0530745
Ankush Menat494bd9e2022-03-28 18:52:46 +0530746 invalid_items = [
747 d[0]
748 for d in frappe.db.sql(
749 """
Zarrarfc03a042018-06-04 12:52:52 +0530750 select item_code from tabItem where name in ({0}) and {1}=0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530751 """.format(
752 item_list, fieldname
753 ),
754 as_list=True,
755 )
756 ]
Zarrarfc03a042018-06-04 12:52:52 +0530757
758 if invalid_items:
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530759 items = ", ".join([d for d in invalid_items])
760
761 if len(invalid_items) > 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530762 error_message = _(
763 "Following items {0} are not marked as {1} item. You can enable them as {1} item from its Item master"
764 ).format(items, message)
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530765 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530766 error_message = _(
767 "Following item {0} is not marked as {1} item. You can enable them as {1} item from its Item master"
768 ).format(items, message)
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530769
770 frappe.throw(error_message)