blob: 58bcc8c5fbee84ab019d72ae269e09cd3f77bb66 [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
s-aga-re019d432023-11-03 00:53:30 +05307from frappe.contacts.doctype.address.address import render_address
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +05308from frappe.utils import cint, flt, getdate
Rohit Waghchaurecb763932022-09-15 11:47:10 +05309from frappe.utils.data import nowtime
Anand Doshi756dca72013-01-15 18:39:21 +053010
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +053011from erpnext.accounts.doctype.budget.budget import validate_expense_against_budget
Chillar Anand915b3432021-09-02 16:44:59 +053012from erpnext.accounts.party import get_party_details
13from erpnext.buying.utils import update_last_purchase_rate, validate_for_items
Nabin Haita77b8c92020-12-21 14:45:50 +053014from erpnext.controllers.sales_and_purchase_return import get_rate_for_return
s-aga-r6d89b2f2022-06-18 15:46:59 +053015from erpnext.controllers.subcontracting_controller import SubcontractingController
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
Faris Ansaribc6a2b22020-10-27 19:42:58 +053023
s-aga-r6d89b2f2022-06-18 15:46:59 +053024class BuyingController(SubcontractingController):
25 def __setup__(self):
26 self.flags.ignore_permlevel_for_fields = ["buying_price_list", "price_list_currency"]
27
Saurabh6f753182013-03-20 12:55:28 +053028 def validate(self):
Rohit Waghchaure6e198182023-06-15 14:45:19 +053029 self.set_rate_for_standalone_debit_note()
30
Akhil Narang3effaf22024-03-27 11:37:26 +053031 super().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()
Deepesh Gargfa152212022-11-28 19:22:35 +053042 self.validate_auto_repeat_subscription_dates()
Rohit Waghchaure86da3062023-03-20 14:15:34 +053043 self.create_package_for_transfer()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053044
Ankush Menat494bd9e2022-03-28 18:52:46 +053045 if self.doctype == "Purchase Invoice":
Nabin Hait14aa9c52016-04-18 15:54:01 +053046 self.validate_purchase_receipt_if_update_stock()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053047
Akhil Narang3effaf22024-03-27 11:37:26 +053048 if self.doctype == "Purchase Receipt" or (self.doctype == "Purchase Invoice" and self.update_stock):
Rohit Waghchaure560ba392016-08-29 18:19:32 +053049 # self.validate_purchase_return()
Saurabhfbb342c2016-04-07 16:41:31 +053050 self.validate_rejected_warehouse()
51 self.validate_accepted_rejected_qty()
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053052 validate_for_items(self)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053053
Ankush Menat494bd9e2022-03-28 18:52:46 +053054 # sub-contracting
Saurabhfbb342c2016-04-07 16:41:31 +053055 self.validate_for_subcontracting()
s-aga-r6d89b2f2022-06-18 15:46:59 +053056 if self.get("is_old_subcontracting_flow"):
57 self.create_raw_materials_supplied()
Saurabhfbb342c2016-04-07 16:41:31 +053058 self.set_landed_cost_voucher_amount()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053059
Nabin Hait14aa9c52016-04-18 15:54:01 +053060 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Nabin Haita77b8c92020-12-21 14:45:50 +053061 self.update_valuation_rate()
Rohit Waghchauree6143ab2023-03-13 14:51:43 +053062 self.set_serial_and_batch_bundle()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053063
Rohit Waghchaure110e1522021-06-15 17:29:52 +053064 def onload(self):
Akhil Narang3effaf22024-03-27 11:37:26 +053065 super().onload()
Ankush Menat494bd9e2022-03-28 18:52:46 +053066 self.set_onload(
67 "backflush_based_on",
Akhil Narang3effaf22024-03-27 11:37:26 +053068 frappe.db.get_single_value("Buying Settings", "backflush_raw_materials_of_subcontract_based_on"),
Ankush Menat494bd9e2022-03-28 18:52:46 +053069 )
Rohit Waghchaure110e1522021-06-15 17:29:52 +053070
Rohit Waghchaure86da3062023-03-20 14:15:34 +053071 def create_package_for_transfer(self) -> None:
72 """Create serial and batch package for Sourece Warehouse in case of inter transfer."""
73
74 if self.is_internal_transfer() and (
75 self.doctype == "Purchase Receipt" or (self.doctype == "Purchase Invoice" and self.update_stock)
76 ):
77 field = "delivery_note_item" if self.doctype == "Purchase Receipt" else "sales_invoice_item"
78
79 doctype = "Delivery Note Item" if self.doctype == "Purchase Receipt" else "Sales Invoice Item"
80
81 ids = [d.get(field) for d in self.get("items") if d.get(field)]
82 bundle_ids = {}
83 if ids:
84 for bundle in frappe.get_all(
85 doctype, filters={"name": ("in", ids)}, fields=["serial_and_batch_bundle", "name"]
86 ):
87 bundle_ids[bundle.name] = bundle.serial_and_batch_bundle
88
89 if not bundle_ids:
90 return
91
92 for item in self.get("items"):
Rohit Waghchaured3ceb072023-03-31 09:03:54 +053093 if item.get(field) and not item.serial_and_batch_bundle and bundle_ids.get(item.get(field)):
Rohit Waghchaure86da3062023-03-20 14:15:34 +053094 item.serial_and_batch_bundle = self.make_package_for_transfer(
95 bundle_ids.get(item.get(field)),
96 item.from_warehouse,
97 type_of_transaction="Outward",
98 do_not_submit=True,
99 )
100
Rohit Waghchaure6e198182023-06-15 14:45:19 +0530101 def set_rate_for_standalone_debit_note(self):
102 if self.get("is_return") and self.get("update_stock") and not self.return_against:
103 for row in self.items:
s-aga-r5cce5222023-11-06 17:13:29 +0530104 if row.rate <= 0:
105 # override the rate with valuation rate
106 row.rate = get_incoming_rate(
107 {
108 "item_code": row.item_code,
109 "warehouse": row.warehouse,
110 "posting_date": self.get("posting_date"),
111 "posting_time": self.get("posting_time"),
112 "qty": row.qty,
113 "serial_and_batch_bundle": row.get("serial_and_batch_bundle"),
114 "company": self.company,
115 "voucher_type": self.doctype,
116 "voucher_no": self.name,
rohitwaghchaure5e9016f2023-12-01 21:42:22 +0530117 "voucher_detail_no": row.name,
s-aga-r5cce5222023-11-06 17:13:29 +0530118 },
119 raise_error_if_no_rate=False,
120 )
Rohit Waghchauref9f66262023-06-15 15:01:15 +0530121
s-aga-r5cce5222023-11-06 17:13:29 +0530122 row.discount_percentage = 0.0
123 row.discount_amount = 0.0
124 row.margin_rate_or_amount = 0.0
Rohit Waghchaure6e198182023-06-15 14:45:19 +0530125
Anand Doshi3543f302013-05-24 19:25:01 +0530126 def set_missing_values(self, for_validate=False):
Akhil Narang3effaf22024-03-27 11:37:26 +0530127 super().set_missing_values(for_validate)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530128
Rushabh Mehta0b995402013-08-09 15:29:59 +0530129 self.set_supplier_from_item_default()
Nabin Hait096d3632013-10-17 17:01:14 +0530130 self.set_price_list_currency("Buying")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530131
Anand Doshi3543f302013-05-24 19:25:01 +0530132 # set contact and address details for supplier, if they are not mentioned
Nabin Hait365ae272014-04-03 17:38:54 +0530133 if getattr(self, "supplier", None):
marination78b6b292022-01-24 13:39:10 +0530134 self.update_if_missing(
135 get_party_details(
136 self.supplier,
137 party_type="Supplier",
138 doctype=self.doctype,
139 company=self.company,
140 party_address=self.get("supplier_address"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530141 shipping_address=self.get("shipping_address"),
Sagar Voraa3625b32022-07-29 12:41:40 +0530142 company_address=self.get("billing_address"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530143 fetch_payment_terms_template=not self.get("ignore_default_payment_terms_template"),
144 ignore_permissions=self.flags.ignore_permissions,
marination78b6b292022-01-24 13:39:10 +0530145 )
146 )
Rushabh Mehta886c9ef2013-07-08 12:08:06 +0530147
Nabin Haitcccc45e2016-10-05 17:15:43 +0530148 self.set_missing_item_details(for_validate)
Rushabh Mehta436467a2013-07-08 12:37:59 +0530149
Rushabh Mehta0b995402013-08-09 15:29:59 +0530150 def set_supplier_from_item_default(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530151 if self.meta.get_field("supplier") and not self.supplier:
Nabin Haitdd38a262014-12-26 13:15:21 +0530152 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530153 supplier = frappe.db.get_value(
154 "Item Default", {"parent": d.item_code, "company": self.company}, "default_supplier"
155 )
Rushabh Mehta0b995402013-08-09 15:29:59 +0530156 if supplier:
Anand Doshif78d1ae2014-03-28 13:55:00 +0530157 self.supplier = supplier
Shreya Shah3c9839f2018-07-17 18:01:44 +0530158 else:
159 item_group = frappe.db.get_value("Item", d.item_code, "item_group")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530160 supplier = frappe.db.get_value(
161 "Item Default", {"parent": item_group, "company": self.company}, "default_supplier"
162 )
Shreya Shah3c9839f2018-07-17 18:01:44 +0530163 if supplier:
164 self.supplier = supplier
Rushabh Mehta0b995402013-08-09 15:29:59 +0530165 break
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530166
Nabin Hait205f7ce2013-04-26 13:35:06 +0530167 def validate_stock_or_nonstock_items(self):
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530168 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 +0530169 msg = _('Tax Category has been changed to "Total" because all the Items are non-stock items')
170 self.update_tax_category(msg)
171
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530172 def update_tax_category(self, msg):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530173 tax_for_valuation = [
174 d for d in self.get("taxes") if d.category in ["Valuation", "Valuation and Total"]
175 ]
tundebabzy9a346202017-06-16 11:00:14 +0100176
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530177 if tax_for_valuation:
178 for d in tax_for_valuation:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530179 d.category = "Total"
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530180
181 msgprint(msg)
Marica1c8cbd02020-05-02 17:55:15 +0530182
Saqib562fd0e2020-04-08 12:11:40 +0530183 def validate_asset_return(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530184 if self.doctype not in ["Purchase Receipt", "Purchase Invoice"] or not self.is_return:
Saqib562fd0e2020-04-08 12:11:40 +0530185 return
186
Akhil Narang3effaf22024-03-27 11:37:26 +0530187 purchase_doc_field = "purchase_receipt" if self.doctype == "Purchase Receipt" else "purchase_invoice"
ruthra kumar097b9892023-09-15 17:54:20 +0530188 not_cancelled_asset = []
189 if self.return_against:
190 not_cancelled_asset = [
191 d.name
192 for d in frappe.db.get_all("Asset", {purchase_doc_field: self.return_against, "docstatus": 1})
193 ]
194
Saqib562fd0e2020-04-08 12:11:40 +0530195 if self.is_return and len(not_cancelled_asset):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530196 frappe.throw(
197 _(
198 "{} has submitted assets linked to it. You need to cancel the assets to create purchase return."
199 ).format(self.return_against),
200 title=_("Not Allowed"),
201 )
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530202
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530203 def get_asset_items(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530204 if self.doctype not in ["Purchase Order", "Purchase Invoice", "Purchase Receipt"]:
Rohit Waghchaured644e6d2018-05-12 15:27:18 +0530205 return []
206
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530207 return [d.item_code for d in self.items if d.is_fixed_asset]
208
Saurabhfbb342c2016-04-07 16:41:31 +0530209 def set_landed_cost_voucher_amount(self):
210 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530211 lc_voucher_data = frappe.db.sql(
212 """select sum(applicable_charges), cost_center
Saurabhfbb342c2016-04-07 16:41:31 +0530213 from `tabLanded Cost Item`
rohitwaghchaure6239fd72024-02-14 15:29:20 +0530214 where docstatus = 1 and purchase_receipt_item = %s and receipt_document = %s""",
215 (d.name, self.name),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530216 )
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530217 d.landed_cost_voucher_amount = lc_voucher_data[0][0] if lc_voucher_data else 0.0
218 if not d.cost_center and lc_voucher_data and lc_voucher_data[0][1]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530219 d.db_set("cost_center", lc_voucher_data[0][1])
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530220
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530221 def validate_from_warehouse(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530222 for item in self.get("items"):
223 if item.get("from_warehouse") and (item.get("from_warehouse") == item.get("warehouse")):
224 frappe.throw(
225 _("Row #{0}: Accepted Warehouse and Supplier Warehouse cannot be same").format(item.idx)
226 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530227
Sagar Sharma409df262022-04-19 14:57:31 +0530228 if item.get("from_warehouse") and self.get("is_subcontracted"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530229 frappe.throw(
230 _(
231 "Row #{0}: Cannot select Supplier Warehouse while suppling raw materials to subcontractor"
232 ).format(item.idx)
233 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530234
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530235 def set_supplier_address(self):
236 address_dict = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530237 "supplier_address": "address_display",
238 "shipping_address": "shipping_address_display",
Deepesh Gargbb21c042023-05-31 11:02:30 +0530239 "billing_address": "billing_address_display",
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530240 }
241
242 for address_field, address_display_field in address_dict.items():
243 if self.get(address_field):
s-aga-re019d432023-11-03 00:53:30 +0530244 self.set(
245 address_display_field, render_address(self.get(address_field), check_permissions=False)
246 )
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530247
Nabin Haitd3b62502013-01-21 17:24:31 +0530248 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530249 from frappe.utils import money_in_words
Ankush Menat494bd9e2022-03-28 18:52:46 +0530250
Nabin Hait5690be12015-02-12 16:09:11 +0530251 if self.meta.get_field("base_in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530252 if self.meta.get_field("base_rounded_total") and not self.is_rounded_total_disabled():
ruthra kumar70f64842022-09-20 17:32:12 +0530253 amount = abs(self.base_rounded_total)
Nabin Hait6b539d62018-08-29 12:41:12 +0530254 else:
ruthra kumar70f64842022-09-20 17:32:12 +0530255 amount = abs(self.base_grand_total)
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530256 self.base_in_words = money_in_words(amount, self.company_currency)
257
Nabin Hait5b4c2942013-01-22 11:12:02 +0530258 if self.meta.get_field("in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530259 if self.meta.get_field("rounded_total") and not self.is_rounded_total_disabled():
ruthra kumar70f64842022-09-20 17:32:12 +0530260 amount = abs(self.rounded_total)
Nabin Hait6b539d62018-08-29 12:41:12 +0530261 else:
ruthra kumar70f64842022-09-20 17:32:12 +0530262 amount = abs(self.grand_total)
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530263
264 self.in_words = money_in_words(amount, self.currency)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530265
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530266 # update valuation rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530267 def update_valuation_rate(self, reset_outgoing_rate=True):
Anand Doshi8595fcf2013-02-08 19:28:14 +0530268 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530269 item_tax_amount is the total tax amount applied on that item
270 stored for valuation
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530271
Ankush Menat494bd9e2022-03-28 18:52:46 +0530272 TODO: rename item_tax_amount to valuation_tax_amount
Anand Doshi8595fcf2013-02-08 19:28:14 +0530273 """
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530274 stock_and_asset_items = []
Saqibd9956092019-11-18 11:46:55 +0530275 stock_and_asset_items = self.get_stock_items() + self.get_asset_items()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530276
Saqibd9956092019-11-18 11:46:55 +0530277 stock_and_asset_items_qty, stock_and_asset_items_amount = 0, 0
278 last_item_idx = 1
Nabin Haita77b8c92020-12-21 14:45:50 +0530279 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530280 if d.item_code and d.item_code in stock_and_asset_items:
Saqibd9956092019-11-18 11:46:55 +0530281 stock_and_asset_items_qty += flt(d.qty)
282 stock_and_asset_items_amount += flt(d.base_net_amount)
283 last_item_idx = d.idx
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530284
Ankush Menat494bd9e2022-03-28 18:52:46 +0530285 total_valuation_amount = sum(
286 flt(d.base_tax_amount_after_discount_amount)
287 for d in self.get("taxes")
288 if d.category in ["Valuation", "Valuation and Total"]
289 )
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530290
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530291 valuation_amount_adjustment = total_valuation_amount
Nabin Haita77b8c92020-12-21 14:45:50 +0530292 for i, item in enumerate(self.get("items")):
Saqibd9956092019-11-18 11:46:55 +0530293 if item.item_code and item.qty and item.item_code in stock_and_asset_items:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530294 item_proportion = (
295 flt(item.base_net_amount) / stock_and_asset_items_amount
296 if stock_and_asset_items_amount
Saqibd9956092019-11-18 11:46:55 +0530297 else flt(item.qty) / stock_and_asset_items_qty
Ankush Menat494bd9e2022-03-28 18:52:46 +0530298 )
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530299
Saqibd9956092019-11-18 11:46:55 +0530300 if i == (last_item_idx - 1):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530301 item.item_tax_amount = flt(
302 valuation_amount_adjustment, self.precision("item_tax_amount", item)
303 )
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530304 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530305 item.item_tax_amount = flt(
306 item_proportion * total_valuation_amount, self.precision("item_tax_amount", item)
307 )
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530308 valuation_amount_adjustment -= item.item_tax_amount
309
Anand Doshi39384d32013-05-11 19:39:53 +0530310 self.round_floats_in(item)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530311 if flt(item.conversion_factor) == 0.0:
312 item.conversion_factor = (
313 get_conversion_factor(item.item_code, item.uom).get("conversion_factor") or 1.0
314 )
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530315
Rushabh Mehta54047782013-12-26 11:07:46 +0530316 qty_in_stock_uom = flt(item.qty * item.conversion_factor)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530317 if self.get("is_old_subcontracting_flow"):
318 item.rm_supp_cost = self.get_supplied_items_cost(item.name, reset_outgoing_rate)
319 item.valuation_rate = (
320 item.base_net_amount
321 + item.item_tax_amount
322 + item.rm_supp_cost
323 + flt(item.landed_cost_voucher_amount)
324 ) / qty_in_stock_uom
325 else:
326 item.valuation_rate = (
Rohit Waghchaureeab775e2023-02-22 12:30:09 +0530327 item.base_net_amount
328 + item.item_tax_amount
329 + flt(item.landed_cost_voucher_amount)
Rohit Waghchaurea8445da2023-02-28 15:47:45 +0530330 + flt(item.get("rate_difference_with_purchase_invoice"))
s-aga-r6d89b2f2022-06-18 15:46:59 +0530331 ) / qty_in_stock_uom
Anand Doshi4a7248e2013-02-27 18:10:30 +0530332 else:
Anand Doshi5af812a2013-05-10 19:23:02 +0530333 item.valuation_rate = 0.0
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530334
Deepesh Gargb4be2922021-01-28 13:09:56 +0530335 def set_incoming_rate(self):
336 if self.doctype not in ("Purchase Receipt", "Purchase Invoice", "Purchase Order"):
337 return
338
Rohit Waghchaured1d46712023-01-09 15:12:46 +0530339 if not self.is_internal_transfer():
Rohit Waghchaure72496572023-01-09 14:53:54 +0530340 return
341
Deepesh Gargb4be2922021-01-28 13:09:56 +0530342 ref_doctype_map = {
343 "Purchase Order": "Sales Order Item",
344 "Purchase Receipt": "Delivery Note Item",
345 "Purchase Invoice": "Sales Invoice Item",
346 }
347
348 ref_doctype = ref_doctype_map.get(self.doctype)
349 items = self.get("items")
350 for d in items:
351 if not cint(self.get("is_return")):
352 # Get outgoing rate based on original item cost based on valuation method
353
354 if not d.get(frappe.scrub(ref_doctype)):
Rohit Waghchaurecb763932022-09-15 11:47:10 +0530355 posting_time = self.get("posting_time")
356 if not posting_time and self.doctype == "Purchase Order":
357 posting_time = nowtime()
358
Ankush Menat494bd9e2022-03-28 18:52:46 +0530359 outgoing_rate = get_incoming_rate(
360 {
361 "item_code": d.item_code,
362 "warehouse": d.get("from_warehouse"),
anandbaburajanb097bb22023-11-13 18:09:09 +0530363 "posting_date": self.get("posting_date") or self.get("transaction_date"),
Rohit Waghchaurecb763932022-09-15 11:47:10 +0530364 "posting_time": posting_time,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530365 "qty": -1 * flt(d.get("stock_qty")),
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530366 "serial_and_batch_bundle": d.get("serial_and_batch_bundle"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530367 "company": self.company,
368 "voucher_type": self.doctype,
369 "voucher_no": self.name,
370 "allow_zero_valuation": d.get("allow_zero_valuation"),
rohitwaghchaure5e9016f2023-12-01 21:42:22 +0530371 "voucher_detail_no": d.name,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530372 },
373 raise_error_if_no_rate=False,
374 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530375
marinationaa043fe2022-07-05 19:43:02 +0530376 rate = flt(outgoing_rate * (d.conversion_factor or 1), d.precision("rate"))
Deepesh Gargb4be2922021-01-28 13:09:56 +0530377 else:
mergify[bot]32a608f2023-12-18 18:13:47 +0530378 field = (
379 "incoming_rate"
380 if self.get("is_internal_supplier") and not self.doctype == "Purchase Order"
381 else "rate"
382 )
Deepesh Garg0f655e42022-09-09 12:40:57 +0530383 rate = flt(
384 frappe.db.get_value(ref_doctype, d.get(frappe.scrub(ref_doctype)), field)
385 * (d.conversion_factor or 1),
386 d.precision("rate"),
387 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530388
389 if self.is_internal_transfer():
Deepesh Gargef9d1262022-12-05 10:17:19 +0530390 if self.doctype == "Purchase Receipt" or self.get("update_stock"):
391 if rate != d.rate:
392 d.rate = rate
393 frappe.msgprint(
394 _(
395 "Row {0}: Item rate has been updated as per valuation rate since its an internal stock transfer"
396 ).format(d.idx),
397 alert=1,
398 )
399 d.discount_percentage = 0.0
400 d.discount_amount = 0.0
401 d.margin_rate_or_amount = 0.0
Deepesh Gargb4be2922021-01-28 13:09:56 +0530402
Nabin Hait54d209f2013-03-01 18:51:10 +0530403 def validate_for_subcontracting(self):
Sagar Sharmafd162f92022-07-01 16:51:19 +0530404 if self.is_subcontracted and self.get("is_old_subcontracting_flow"):
Saurabhfbb342c2016-04-07 16:41:31 +0530405 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] and not self.supplier_warehouse:
Afshan27bcb2a2021-03-09 22:25:48 +0530406 frappe.throw(_("Supplier Warehouse mandatory for sub-contracted {0}").format(self.doctype))
s-aga-r6d89b2f2022-06-18 15:46:59 +0530407
Sagar Sharmafd162f92022-07-01 16:51:19 +0530408 for item in self.get("items"):
409 if item in self.sub_contracted_items and not item.bom:
410 frappe.throw(_("Please select BOM in BOM field for Item {0}").format(item.item_code))
411 if self.doctype != "Purchase Order":
412 return
413 for row in self.get("supplied_items"):
414 if not row.reserve_warehouse:
415 msg = f"Reserved Warehouse is mandatory for the Item {frappe.bold(row.rm_item_code)} in Raw Materials supplied"
416 frappe.throw(_(msg))
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530417 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530418 for item in self.get("items"):
Sagar Sharma34bda142022-05-04 15:21:31 +0530419 if item.get("bom"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530420 item.bom = None
421
nabinhait614fb752014-07-14 10:47:50 +0530422 def set_qty_as_per_stock_uom(self):
rohitwaghchauredd4769e2023-09-20 18:09:03 +0530423 allow_to_edit_stock_qty = frappe.db.get_single_value(
424 "Stock Settings", "allow_to_edit_stock_uom_qty_for_purchase"
425 )
426
Nabin Haitdd38a262014-12-26 13:15:21 +0530427 for d in self.get("items"):
Nabin Haitfd4bcd82015-05-22 16:55:40 +0530428 if d.meta.get_field("stock_qty"):
Deepesh Garg8b0302b2019-08-05 10:14:19 +0530429 # Check if item code is present
430 # Conversion factor should not be mandatory for non itemized items
431 if not d.conversion_factor and d.item_code:
Nabin Haite6e456b2015-05-13 17:21:44 +0530432 frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
Rushabh Mehta5b51cc82014-07-21 18:25:45 +0530433 d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530434
Ankush Menat494bd9e2022-03-28 18:52:46 +0530435 if self.doctype == "Purchase Receipt" and d.meta.get_field("received_stock_qty"):
marinationd6596a12020-11-02 15:07:48 +0530436 # Set Received Qty in Stock UOM
Ankush Menat494bd9e2022-03-28 18:52:46 +0530437 d.received_stock_qty = flt(d.received_qty) * flt(
438 d.conversion_factor, d.precision("conversion_factor")
439 )
marinationd6596a12020-11-02 15:07:48 +0530440
rohitwaghchauredd4769e2023-09-20 18:09:03 +0530441 if allow_to_edit_stock_qty:
442 d.stock_qty = flt(d.stock_qty, d.precision("stock_qty"))
s-aga-r60a81a52023-12-01 11:27:54 +0530443 if d.get("received_stock_qty") and d.meta.get_field("received_stock_qty"):
rohitwaghchauredd4769e2023-09-20 18:09:03 +0530444 d.received_stock_qty = flt(d.received_stock_qty, d.precision("received_stock_qty"))
445
Saurabh130c57b2016-04-04 15:49:36 +0530446 def validate_purchase_return(self):
447 for d in self.get("items"):
448 if self.is_return and flt(d.rejected_qty) != 0:
449 frappe.throw(_("Row #{0}: Rejected Qty can not be entered in Purchase Return").format(d.idx))
450
451 # validate rate with ref PR
452
Saurabh130c57b2016-04-04 15:49:36 +0530453 # validate accepted and rejected qty
454 def validate_accepted_rejected_qty(self):
455 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530456 self.validate_negative_quantity(d, ["received_qty", "qty", "rejected_qty"])
Saurabh130c57b2016-04-04 15:49:36 +0530457
marination5fb5a752021-11-08 13:22:57 +0530458 if not flt(d.received_qty) and (flt(d.qty) or flt(d.rejected_qty)):
459 d.received_qty = flt(d.qty) + flt(d.rejected_qty)
Saurabh130c57b2016-04-04 15:49:36 +0530460
Saurabh130c57b2016-04-04 15:49:36 +0530461 # Check Received Qty = Accepted Qty + Rejected Qty
marinationafe1c452021-11-15 17:17:29 +0530462 val = flt(d.qty) + flt(d.rejected_qty)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530463 if flt(val, d.precision("received_qty")) != flt(d.received_qty, d.precision("received_qty")):
464 message = _(
465 "Row #{0}: Received Qty must be equal to Accepted + Rejected Qty for Item {1}"
466 ).format(d.idx, d.item_code)
marination05ec7cc2021-11-15 17:49:14 +0530467 frappe.throw(msg=message, title=_("Mismatch"), exc=QtyMismatchError)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530468
Saurabh4f4d0a82017-03-13 14:31:48 +0530469 def validate_negative_quantity(self, item_row, field_list):
470 if self.is_return:
471 return
472
473 item_row = item_row.as_dict()
474 for fieldname in field_list:
475 if flt(item_row[fieldname]) < 0:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530476 frappe.throw(
477 _("Row #{0}: {1} can not be negative for item {2}").format(
478 item_row["idx"],
479 frappe.get_meta(item_row.doctype).get_label(fieldname),
480 item_row["item_code"],
481 )
482 )
Saurabh4f4d0a82017-03-13 14:31:48 +0530483
Mangesh-Khairnar5e474f42019-03-06 14:46:38 +0530484 def check_for_on_hold_or_closed_status(self, ref_doctype, ref_fieldname):
485 for d in self.get("items"):
486 if d.get(ref_fieldname):
487 status = frappe.db.get_value(ref_doctype, d.get(ref_fieldname), "status")
488 if status in ("Closed", "On Hold"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530489 frappe.throw(_("{0} {1} is {2}").format(ref_doctype, d.get(ref_fieldname), status))
Mangesh-Khairnar5e474f42019-03-06 14:46:38 +0530490
Saurabhe29248b2016-04-04 11:55:52 +0530491 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait07e53762018-01-05 18:19:59 +0530492 self.update_ordered_and_reserved_qty()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530493
Saurabhe29248b2016-04-04 11:55:52 +0530494 sl_entries = []
495 stock_items = self.get_stock_items()
496
Ankush Menat494bd9e2022-03-28 18:52:46 +0530497 for d in self.get("items"):
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530498 if d.item_code not in stock_items:
499 continue
500
Rohit Waghchaureac5df1a2022-04-04 15:38:42 +0530501 if d.warehouse:
mergify[bot]50f83852023-06-15 20:18:17 +0530502 pr_qty = flt(flt(d.qty) * flt(d.conversion_factor), d.precision("stock_qty"))
Saurabhe29248b2016-04-04 11:55:52 +0530503
504 if pr_qty:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530505 if d.from_warehouse and (
506 (not cint(self.is_return) and self.docstatus == 1)
507 or (cint(self.is_return) and self.docstatus == 2)
508 ):
rohitwaghchaure59222812024-03-15 17:55:41 +0530509 serial_and_batch_bundle = d.get("serial_and_batch_bundle")
510 if self.is_internal_transfer() and self.is_return and self.docstatus == 2:
511 serial_and_batch_bundle = frappe.db.get_value(
512 "Stock Ledger Entry",
513 {"voucher_detail_no": d.name, "warehouse": d.from_warehouse},
514 "serial_and_batch_bundle",
515 )
516
Ankush Menat494bd9e2022-03-28 18:52:46 +0530517 from_warehouse_sle = self.get_sl_entries(
518 d,
519 {
520 "actual_qty": -1 * pr_qty,
521 "warehouse": d.from_warehouse,
522 "outgoing_rate": d.rate,
523 "recalculate_rate": 1,
524 "dependant_sle_voucher_detail_no": d.name,
rohitwaghchaure59222812024-03-15 17:55:41 +0530525 "serial_and_batch_bundle": serial_and_batch_bundle,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530526 },
527 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530528
529 sl_entries.append(from_warehouse_sle)
530
rohitwaghchaure59222812024-03-15 17:55:41 +0530531 type_of_transaction = "Inward"
532 if self.docstatus == 2:
533 type_of_transaction = "Outward"
534
Ankush Menat494bd9e2022-03-28 18:52:46 +0530535 sle = self.get_sl_entries(
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530536 d,
537 {
538 "actual_qty": flt(pr_qty),
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530539 "serial_and_batch_bundle": (
540 d.serial_and_batch_bundle
rohitwaghchaure59222812024-03-15 17:55:41 +0530541 if not self.is_internal_transfer() or self.is_return
Akhil Narang3effaf22024-03-27 11:37:26 +0530542 else self.get_package_for_target_warehouse(
543 d, type_of_transaction=type_of_transaction
544 )
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530545 ),
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530546 },
Ankush Menat494bd9e2022-03-28 18:52:46 +0530547 )
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530548
Saurabhe29248b2016-04-04 11:55:52 +0530549 if self.is_return:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530550 outgoing_rate = get_rate_for_return(
551 self.doctype, self.name, d.item_code, self.return_against, item_row=d
552 )
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530553
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530554 sle.update(
555 {
556 "outgoing_rate": outgoing_rate,
557 "recalculate_rate": 1,
558 "serial_and_batch_bundle": d.serial_and_batch_bundle,
559 }
560 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530561 if d.from_warehouse:
562 sle.dependant_sle_voucher_detail_no = d.name
Saurabhe29248b2016-04-04 11:55:52 +0530563 else:
Nabin Haitb81ed452016-05-11 12:52:31 +0530564 val_rate_db_precision = 6 if cint(self.precision("valuation_rate", d)) <= 6 else 9
565 incoming_rate = flt(d.valuation_rate, val_rate_db_precision)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530566 sle.update(
567 {
568 "incoming_rate": incoming_rate,
s-aga-r6d89b2f2022-06-18 15:46:59 +0530569 "recalculate_rate": 1
rohitwaghchaure48da9522024-03-06 12:51:04 +0530570 if (self.is_subcontracted and (d.bom or d.get("fg_item"))) or d.from_warehouse
s-aga-r6d89b2f2022-06-18 15:46:59 +0530571 else 0,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530572 }
573 )
Saurabhe29248b2016-04-04 11:55:52 +0530574 sl_entries.append(sle)
575
Ankush Menat494bd9e2022-03-28 18:52:46 +0530576 if d.from_warehouse and (
577 (not cint(self.is_return) and self.docstatus == 2)
578 or (cint(self.is_return) and self.docstatus == 1)
579 ):
580 from_warehouse_sle = self.get_sl_entries(
rohitwaghchaure59222812024-03-15 17:55:41 +0530581 d,
582 {
583 "actual_qty": -1 * pr_qty,
584 "warehouse": d.from_warehouse,
585 "recalculate_rate": 1,
586 "serial_and_batch_bundle": (
587 self.get_package_for_target_warehouse(d, d.from_warehouse, "Inward")
588 if self.is_internal_transfer() and self.is_return
589 else None
590 ),
591 },
Ankush Menat494bd9e2022-03-28 18:52:46 +0530592 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530593
594 sl_entries.append(from_warehouse_sle)
595
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530596 if flt(d.rejected_qty) != 0:
597 sl_entries.append(
598 self.get_sl_entries(
599 d,
600 {
601 "warehouse": d.rejected_warehouse,
Akhil Narang3effaf22024-03-27 11:37:26 +0530602 "actual_qty": flt(
603 flt(d.rejected_qty) * flt(d.conversion_factor), d.precision("stock_qty")
604 ),
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530605 "incoming_rate": 0.0,
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530606 "serial_and_batch_bundle": d.rejected_serial_and_batch_bundle,
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530607 },
Ankush Menat494bd9e2022-03-28 18:52:46 +0530608 )
Rohit Waghchaure0a71cab2022-04-04 15:10:57 +0530609 )
Saurabhe29248b2016-04-04 11:55:52 +0530610
s-aga-r6d89b2f2022-06-18 15:46:59 +0530611 if self.get("is_old_subcontracting_flow"):
612 self.make_sl_entries_for_supplier_warehouse(sl_entries)
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530613
Ankush Menat494bd9e2022-03-28 18:52:46 +0530614 self.make_sl_entries(
615 sl_entries,
616 allow_negative_stock=allow_negative_stock,
617 via_landed_cost_voucher=via_landed_cost_voucher,
618 )
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530619
rohitwaghchaure59222812024-03-15 17:55:41 +0530620 def get_package_for_target_warehouse(self, item, warehouse=None, type_of_transaction=None) -> str:
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530621 if not item.serial_and_batch_bundle:
622 return ""
623
rohitwaghchaure59222812024-03-15 17:55:41 +0530624 if not warehouse:
625 warehouse = item.warehouse
626
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530627 return self.make_package_for_transfer(
rohitwaghchaure59222812024-03-15 17:55:41 +0530628 item.serial_and_batch_bundle, warehouse, type_of_transaction=type_of_transaction
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530629 )
630
Nabin Hait07e53762018-01-05 18:19:59 +0530631 def update_ordered_and_reserved_qty(self):
Nabin Hait14aa9c52016-04-18 15:54:01 +0530632 po_map = {}
633 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530634 if self.doctype == "Purchase Receipt" and d.purchase_order:
635 po_map.setdefault(d.purchase_order, []).append(d.purchase_order_item)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530636
Ankush Menat494bd9e2022-03-28 18:52:46 +0530637 elif self.doctype == "Purchase Invoice" and d.purchase_order and d.po_detail:
Nabin Hait14aa9c52016-04-18 15:54:01 +0530638 po_map.setdefault(d.purchase_order, []).append(d.po_detail)
639
640 for po, po_item_rows in po_map.items():
641 if po and po_item_rows:
642 po_obj = frappe.get_doc("Purchase Order", po)
643
644 if po_obj.status in ["Closed", "Cancelled"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530645 frappe.throw(
646 _("{0} {1} is cancelled or closed").format(_("Purchase Order"), po),
647 frappe.InvalidStatusError,
648 )
Nabin Hait14aa9c52016-04-18 15:54:01 +0530649
650 po_obj.update_ordered_qty(po_item_rows)
s-aga-r6d89b2f2022-06-18 15:46:59 +0530651 if self.get("is_old_subcontracting_flow"):
652 po_obj.update_reserved_qty_for_subcontract()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530653
rohitwaghchaurefe226862017-12-28 16:11:27 +0530654 def on_submit(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530655 if self.get("is_return"):
rohitwaghchaurefe226862017-12-28 16:11:27 +0530656 return
657
Ankush Menat494bd9e2022-03-28 18:52:46 +0530658 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
659 field = "purchase_invoice" if self.doctype == "Purchase Invoice" else "purchase_receipt"
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530660
661 self.process_fixed_asset()
662 self.update_fixed_asset(field)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530663
Rohit Waghchaured1d46712023-01-09 15:12:46 +0530664 if self.doctype in ["Purchase Order", "Purchase Receipt"] and not frappe.db.get_single_value(
665 "Buying Settings", "disable_last_purchase_rate"
666 ):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530667 update_last_purchase_rate(self, is_submit=1)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530668
669 def on_cancel(self):
Akhil Narang3effaf22024-03-27 11:37:26 +0530670 super().on_cancel()
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +0530671
Ankush Menat494bd9e2022-03-28 18:52:46 +0530672 if self.get("is_return"):
rohitwaghchaurefe226862017-12-28 16:11:27 +0530673 return
674
Rohit Waghchaured1d46712023-01-09 15:12:46 +0530675 if self.doctype in ["Purchase Order", "Purchase Receipt"] and not frappe.db.get_single_value(
676 "Buying Settings", "disable_last_purchase_rate"
677 ):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530678 update_last_purchase_rate(self, is_submit=0)
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530679
Ankush Menat494bd9e2022-03-28 18:52:46 +0530680 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
681 field = "purchase_invoice" if self.doctype == "Purchase Invoice" else "purchase_receipt"
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530682
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530683 self.delete_linked_asset()
684 self.update_fixed_asset(field, delete_asset=True)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530685
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530686 def validate_budget(self):
687 if self.docstatus == 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530688 for data in self.get("items"):
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530689 args = data.as_dict()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530690 args.update(
691 {
692 "doctype": self.doctype,
693 "company": self.company,
694 "posting_date": (
Akhil Narang3effaf22024-03-27 11:37:26 +0530695 self.schedule_date
696 if self.doctype == "Material Request"
697 else self.transaction_date
Ankush Menat494bd9e2022-03-28 18:52:46 +0530698 ),
699 }
700 )
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530701
702 validate_expense_against_budget(args)
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530703
Rohit Waghchaureab842542018-04-26 19:18:29 +0530704 def process_fixed_asset(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530705 if self.doctype == "Purchase Invoice" and not self.update_stock:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530706 return
707
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530708 asset_items = self.get_asset_items()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530709 if asset_items:
Saqibd9956092019-11-18 11:46:55 +0530710 self.auto_make_assets(asset_items)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530711
Saqibd9956092019-11-18 11:46:55 +0530712 def auto_make_assets(self, asset_items):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530713 items_data = get_asset_item_details(asset_items)
Saqibf37a46e2019-11-22 16:32:50 +0530714 messages = []
Rohit Waghchaureab842542018-04-26 19:18:29 +0530715
716 for d in self.items:
717 if d.is_fixed_asset:
718 item_data = items_data.get(d.item_code)
719
Ankush Menat494bd9e2022-03-28 18:52:46 +0530720 if item_data.get("auto_create_assets"):
Saqibd9956092019-11-18 11:46:55 +0530721 # If asset has to be auto created
722 # Check for asset naming series
Ankush Menat494bd9e2022-03-28 18:52:46 +0530723 if item_data.get("asset_naming_series"):
Saqibbba78f02020-03-31 10:49:44 +0530724 created_assets = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530725 if item_data.get("is_grouped_asset"):
Saqib Ansari35a6b582022-01-18 13:10:23 +0530726 asset = self.make_asset(d, is_grouped_asset=True)
Saqibbba78f02020-03-31 10:49:44 +0530727 created_assets.append(asset)
Saqib Ansari35a6b582022-01-18 13:10:23 +0530728 else:
Akhil Narang3effaf22024-03-27 11:37:26 +0530729 for _qty in range(cint(d.qty)):
Saqib Ansari35a6b582022-01-18 13:10:23 +0530730 asset = self.make_asset(d)
731 created_assets.append(asset)
Marica1c8cbd02020-05-02 17:55:15 +0530732
Saqibbba78f02020-03-31 10:49:44 +0530733 if len(created_assets) > 5:
734 # dont show asset form links if more than 5 assets are created
Saqibbba78f02020-03-31 10:49:44 +0530735 messages.append(
Akhil Narang3effaf22024-03-27 11:37:26 +0530736 _("{} Assets created for {}").format(
737 len(created_assets), frappe.bold(d.item_code)
738 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530739 )
740 else:
Akhil Narang3effaf22024-03-27 11:37:26 +0530741 assets_link = list(
742 map(lambda d: frappe.utils.get_link_to_form("Asset", d), created_assets)
743 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530744 assets_link = frappe.bold(",".join(assets_link))
745
746 is_plural = "s" if len(created_assets) != 1 else ""
747 messages.append(
748 _("Asset{} {assets_link} created for {}").format(
749 is_plural, frappe.bold(d.item_code), assets_link=assets_link
750 )
Saqibbba78f02020-03-31 10:49:44 +0530751 )
Saqibd9956092019-11-18 11:46:55 +0530752 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530753 frappe.throw(
Akhil Narang3effaf22024-03-27 11:37:26 +0530754 _(
755 "Row {}: Asset Naming Series is mandatory for the auto creation for item {}"
756 ).format(d.idx, frappe.bold(d.item_code))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530757 )
Saqibd9956092019-11-18 11:46:55 +0530758 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530759 messages.append(
760 _("Assets not created for {0}. You will have to create asset manually.").format(
761 frappe.bold(d.item_code)
762 )
763 )
Saqibf37a46e2019-11-22 16:32:50 +0530764
765 for message in messages:
Saqibbba78f02020-03-31 10:49:44 +0530766 frappe.msgprint(message, title="Success", indicator="green")
Rohit Waghchaureab842542018-04-26 19:18:29 +0530767
Saqib Ansari35a6b582022-01-18 13:10:23 +0530768 def make_asset(self, row, is_grouped_asset=False):
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530769 if not row.asset_location:
770 frappe.throw(_("Row {0}: Enter location for the asset item {1}").format(row.idx, row.item_code))
771
Ankush Menat494bd9e2022-03-28 18:52:46 +0530772 item_data = frappe.db.get_value(
773 "Item", row.item_code, ["asset_naming_series", "asset_category"], as_dict=1
774 )
Nabin Hait135e19d2024-01-09 12:51:57 +0530775 asset_quantity = row.qty if is_grouped_asset else 1
776 purchase_amount = flt(row.valuation_rate) * asset_quantity
Saqib Ansari35a6b582022-01-18 13:10:23 +0530777
Ankush Menat494bd9e2022-03-28 18:52:46 +0530778 asset = frappe.get_doc(
779 {
780 "doctype": "Asset",
781 "item_code": row.item_code,
782 "asset_name": row.item_name,
783 "naming_series": item_data.get("asset_naming_series") or "AST",
784 "asset_category": item_data.get("asset_category"),
785 "location": row.asset_location,
786 "company": self.company,
787 "supplier": self.supplier,
788 "purchase_date": self.posting_date,
Anand Baburajan8f049452023-08-22 12:36:09 +0530789 "calculate_depreciation": 0,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530790 "purchase_receipt_amount": purchase_amount,
791 "gross_purchase_amount": purchase_amount,
Nabin Hait135e19d2024-01-09 12:51:57 +0530792 "asset_quantity": asset_quantity,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530793 "purchase_receipt": self.name if self.doctype == "Purchase Receipt" else None,
794 "purchase_invoice": self.name if self.doctype == "Purchase Invoice" else None,
795 }
796 )
Rohit Waghchaureab842542018-04-26 19:18:29 +0530797
798 asset.flags.ignore_validate = True
799 asset.flags.ignore_mandatory = True
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530800 asset.set_missing_values()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530801 asset.insert()
802
Saqibbba78f02020-03-31 10:49:44 +0530803 return asset.name
804
Ankush Menat494bd9e2022-03-28 18:52:46 +0530805 def update_fixed_asset(self, field, delete_asset=False):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530806 for d in self.get("items"):
Saqibd9956092019-11-18 11:46:55 +0530807 if d.is_fixed_asset:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530808 is_auto_create_enabled = frappe.db.get_value("Item", d.item_code, "auto_create_assets")
809 assets = frappe.db.get_all("Asset", filters={field: self.name, "item_code": d.item_code})
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530810
Saqibd9956092019-11-18 11:46:55 +0530811 for asset in assets:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530812 asset = frappe.get_doc("Asset", asset.name)
Saqibd9956092019-11-18 11:46:55 +0530813 if delete_asset and is_auto_create_enabled:
814 # need to delete movements to delete assets otherwise throws link exists error
Saqibcd3976f2019-11-25 12:24:34 +0530815 movements = frappe.db.sql(
Suraj Shetty48e9bc32020-01-29 15:06:18 +0530816 """SELECT asm.name
Saqibcd3976f2019-11-25 12:24:34 +0530817 FROM `tabAsset Movement` asm, `tabAsset Movement Item` asm_item
Ankush Menat494bd9e2022-03-28 18:52:46 +0530818 WHERE asm_item.parent=asm.name and asm_item.asset=%s""",
819 asset.name,
820 as_dict=1,
821 )
Saqibd9956092019-11-18 11:46:55 +0530822 for movement in movements:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530823 frappe.delete_doc("Asset Movement", movement.name, force=1)
Saqibd9956092019-11-18 11:46:55 +0530824 frappe.delete_doc("Asset", asset.name, force=1)
825 continue
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530826
Saqibd9956092019-11-18 11:46:55 +0530827 if self.docstatus in [0, 1] and not asset.get(field):
828 asset.set(field, self.name)
829 asset.purchase_date = self.posting_date
830 asset.supplier = self.supplier
831 elif self.docstatus == 2:
anandbaburajanb9613212023-02-03 22:58:22 +0530832 if asset.docstatus == 2:
anandbaburajan3380dc52023-02-04 11:20:26 +0530833 continue
Saqibcd3976f2019-11-25 12:24:34 +0530834 if asset.docstatus == 0:
835 asset.set(field, None)
836 asset.supplier = None
837 if asset.docstatus == 1 and delete_asset:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530838 frappe.throw(
839 _(
840 "Cannot cancel this document as it is linked with submitted asset {0}. Please cancel it to continue."
841 ).format(frappe.utils.get_link_to_form("Asset", asset.name))
842 )
Rohit Waghchaureab842542018-04-26 19:18:29 +0530843
Saqibd9956092019-11-18 11:46:55 +0530844 asset.flags.ignore_validate_update_after_submit = True
845 asset.flags.ignore_mandatory = True
846 if asset.docstatus == 0:
847 asset.flags.ignore_validate = True
Rohit Waghchaureab842542018-04-26 19:18:29 +0530848
Saqibd9956092019-11-18 11:46:55 +0530849 asset.save()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530850
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530851 def delete_linked_asset(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530852 if self.doctype == "Purchase Invoice" and not self.get("update_stock"):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530853 return
854
Nabin Hait17f85de2024-02-20 18:10:34 +0530855 asset_movement = frappe.db.get_value("Asset Movement", {"reference_name": self.name}, "name")
856 frappe.delete_doc("Asset Movement", asset_movement, force=1)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530857
Nabin Hait5a834202017-10-05 19:51:10 +0530858 def validate_schedule_date(self):
Sahil Khan34766c02018-12-20 18:50:24 +0530859 if not self.get("items"):
860 return
Nabin Haita1138612019-10-15 12:43:27 +0530861
18alantom2a20a032021-05-05 11:59:15 +0530862 if any(d.schedule_date for d in self.get("items")):
863 # Select earliest schedule_date.
Ankush Menat494bd9e2022-03-28 18:52:46 +0530864 self.schedule_date = min(
865 d.schedule_date for d in self.get("items") if d.schedule_date is not None
866 )
Nabin Hait5a834202017-10-05 19:51:10 +0530867
868 if self.schedule_date:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530869 for d in self.get("items"):
Nabin Hait5a834202017-10-05 19:51:10 +0530870 if not d.schedule_date:
871 d.schedule_date = self.schedule_date
872
Ankush Menat494bd9e2022-03-28 18:52:46 +0530873 if (
874 d.schedule_date
875 and self.transaction_date
876 and getdate(d.schedule_date) < getdate(self.transaction_date)
877 ):
Nabin Hait96b264b2018-01-02 11:50:29 +0530878 frappe.throw(_("Row #{0}: Reqd by Date cannot be before Transaction Date").format(d.idx))
Nabin Hait5a834202017-10-05 19:51:10 +0530879 else:
Nabin Hait96b264b2018-01-02 11:50:29 +0530880 frappe.throw(_("Please enter Reqd by Date"))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530881
Zarrarfc03a042018-06-04 12:52:52 +0530882 def validate_items(self):
883 # validate items to see if they have is_purchase_item or is_subcontracted_item enabled
Ankush Menat494bd9e2022-03-28 18:52:46 +0530884 if self.doctype == "Material Request":
885 return
Zarrarfc03a042018-06-04 12:52:52 +0530886
s-aga-r6d89b2f2022-06-18 15:46:59 +0530887 if self.get("is_old_subcontracting_flow"):
888 validate_item_type(self, "is_sub_contracted_item", "subcontracted")
889 else:
890 validate_item_type(self, "is_purchase_item", "purchase")
Zarrarfc03a042018-06-04 12:52:52 +0530891
Ankush Menat494bd9e2022-03-28 18:52:46 +0530892
Rohit Waghchaureab842542018-04-26 19:18:29 +0530893def get_asset_item_details(asset_items):
894 asset_items_data = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530895 for d in frappe.get_all(
896 "Item",
897 fields=["name", "auto_create_assets", "asset_naming_series", "is_grouped_asset"],
898 filters={"name": ("in", asset_items)},
899 ):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530900 asset_items_data.setdefault(d.name, d)
901
902 return asset_items_data
Ameya Shenoy873e28d2018-06-06 05:53:19 +0000903
Ankush Menat494bd9e2022-03-28 18:52:46 +0530904
Zarrarfc03a042018-06-04 12:52:52 +0530905def validate_item_type(doc, fieldname, message):
906 # iterate through items and check if they are valid sales or purchase items
Zarrar7c088ff2018-06-05 10:32:09 +0530907 items = [d.item_code for d in doc.items if d.item_code]
908
909 # No validation check inase of creating transaction using 'Opening Invoice Creation Tool'
910 if not items:
911 return
912
Suraj Shettybfc195d2018-09-21 10:20:52 +0530913 item_list = ", ".join(["%s" % frappe.db.escape(d) for d in items])
Zarrarfc03a042018-06-04 12:52:52 +0530914
Ankush Menat494bd9e2022-03-28 18:52:46 +0530915 invalid_items = [
916 d[0]
917 for d in frappe.db.sql(
Akhil Narang3effaf22024-03-27 11:37:26 +0530918 f"""
919 select item_code from tabItem where name in ({item_list}) and {fieldname}=0
920 """,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530921 as_list=True,
922 )
923 ]
Zarrarfc03a042018-06-04 12:52:52 +0530924
925 if invalid_items:
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530926 items = ", ".join([d for d in invalid_items])
927
928 if len(invalid_items) > 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530929 error_message = _(
930 "Following items {0} are not marked as {1} item. You can enable them as {1} item from its Item master"
931 ).format(items, message)
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530932 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530933 error_message = _(
934 "Following item {0} is not marked as {1} item. You can enable them as {1} item from its Item master"
935 ).format(items, message)
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530936
937 frappe.throw(error_message)