blob: fed1fdd01f52068ff018322d3b531276f8f819a2 [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Anand Doshi756dca72013-01-15 18:39:21 +05303
4from __future__ import unicode_literals
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
6from frappe import _, msgprint
Nabin Hait5a834202017-10-05 19:51:10 +05307from frappe.utils import flt,cint, cstr, getdate
Sambhaji Kolatee3d26432014-09-10 13:07:59 +05308
Rushabh Mehtacc008cc2014-02-03 16:14:56 +05309from erpnext.accounts.party import get_party_details
Rushabh Mehta724f9e52014-10-07 15:29:58 +053010from erpnext.stock.get_item_details import get_conversion_factor
rohitwaghchaurefe226862017-12-28 16:11:27 +053011from erpnext.buying.utils import validate_for_items, update_last_purchase_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053012from erpnext.stock.stock_ledger import get_valuation_rate
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +053013from erpnext.stock.doctype.stock_entry.stock_entry import get_used_alternative_items
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +053014from erpnext.stock.doctype.serial_no.serial_no import get_auto_serial_nos, auto_make_serial_nos, get_serial_nos
Rohit Waghchauref4dc7162018-11-15 17:04:02 +053015from frappe.contacts.doctype.address.address import get_address_display
Anand Doshi756dca72013-01-15 18:39:21 +053016
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +053017from erpnext.accounts.doctype.budget.budget import validate_expense_against_budget
Rushabh Mehta1f847992013-12-12 19:12:19 +053018from erpnext.controllers.stock_controller import StockController
Nabin Haitbf495c92013-01-30 12:49:08 +053019
Nabin Hait89a94d82013-03-19 12:01:46 +053020class BuyingController(StockController):
Rushabh Mehta5b51cc82014-07-21 18:25:45 +053021 def __setup__(self):
Nabin Haitde9c8a92015-02-23 01:06:00 +053022 if hasattr(self, "taxes"):
Nabin Hait45dce892017-09-14 15:17:38 +053023 self.flags.print_taxes_with_zero_amount = cint(frappe.db.get_single_value("Print Settings",
24 "print_taxes_with_zero_amount"))
rohitwaghchaurebf4c1142018-01-08 15:20:15 +053025 self.flags.show_inclusive_tax_in_print = self.is_inclusive_tax()
26
Rushabh Mehtac567e8e2015-02-03 17:55:52 +053027 self.print_templates = {
rohitwaghchaurebf4c1142018-01-08 15:20:15 +053028 "total": "templates/print_formats/includes/total.html",
Rushabh Mehtac567e8e2015-02-03 17:55:52 +053029 "taxes": "templates/print_formats/includes/taxes.html"
Rushabh Mehta5b51cc82014-07-21 18:25:45 +053030 }
31
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053032 def get_feed(self):
rohitwaghchaurea1064a62016-03-03 14:00:35 +053033 if self.get("supplier_name"):
34 return _("From {0} | {1} {2}").format(self.supplier_name, self.currency,
35 self.grand_total)
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053036
Saurabh6f753182013-03-20 12:55:28 +053037 def validate(self):
38 super(BuyingController, self).validate()
Nabin Hait365ae272014-04-03 17:38:54 +053039 if getattr(self, "supplier", None) and not self.supplier_name:
Nabin Hait1d218422015-07-17 15:19:02 +053040 self.supplier_name = frappe.db.get_value("Supplier", self.supplier, "supplier_name")
Rushabh Mehtaea0ff232016-07-07 14:02:26 +053041
Zarrarfc03a042018-06-04 12:52:52 +053042 self.validate_items()
nabinhait614fb752014-07-14 10:47:50 +053043 self.set_qty_as_per_stock_uom()
Nabin Hait205f7ce2013-04-26 13:35:06 +053044 self.validate_stock_or_nonstock_items()
Anand Doshi373680b2013-10-10 16:04:40 +053045 self.validate_warehouse()
Rohit Waghchauref4dc7162018-11-15 17:04:02 +053046 self.set_supplier_address()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053047
Nabin Hait14aa9c52016-04-18 15:54:01 +053048 if self.doctype=="Purchase Invoice":
49 self.validate_purchase_receipt_if_update_stock()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053050
Nabin Hait14aa9c52016-04-18 15:54:01 +053051 if self.doctype=="Purchase Receipt" or (self.doctype=="Purchase Invoice" and self.update_stock):
Rohit Waghchaure560ba392016-08-29 18:19:32 +053052 # self.validate_purchase_return()
Saurabhfbb342c2016-04-07 16:41:31 +053053 self.validate_rejected_warehouse()
54 self.validate_accepted_rejected_qty()
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053055 validate_for_items(self)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053056
Saurabhfbb342c2016-04-07 16:41:31 +053057 #sub-contracting
58 self.validate_for_subcontracting()
59 self.create_raw_materials_supplied("supplied_items")
60 self.set_landed_cost_voucher_amount()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053061
Nabin Hait14aa9c52016-04-18 15:54:01 +053062 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Saurabhfbb342c2016-04-07 16:41:31 +053063 self.update_valuation_rate("items")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053064
Anand Doshi3543f302013-05-24 19:25:01 +053065 def set_missing_values(self, for_validate=False):
Anand Doshiabc10032013-06-14 17:44:03 +053066 super(BuyingController, self).set_missing_values(for_validate)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053067
Rushabh Mehta0b995402013-08-09 15:29:59 +053068 self.set_supplier_from_item_default()
Nabin Hait096d3632013-10-17 17:01:14 +053069 self.set_price_list_currency("Buying")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053070
Anand Doshi3543f302013-05-24 19:25:01 +053071 # set contact and address details for supplier, if they are not mentioned
Nabin Hait365ae272014-04-03 17:38:54 +053072 if getattr(self, "supplier", None):
Shreya Shah5615cb42018-10-07 11:42:07 +053073 self.update_if_missing(get_party_details(self.supplier, party_type="Supplier", ignore_permissions=self.flags.ignore_permissions,
Shreya Shah314c97c2018-10-11 16:59:40 +053074 doctype=self.doctype, company=self.company, party_address=self.supplier_address, shipping_address=self.get('shipping_address')))
Rushabh Mehta886c9ef2013-07-08 12:08:06 +053075
Nabin Haitcccc45e2016-10-05 17:15:43 +053076 self.set_missing_item_details(for_validate)
Rushabh Mehta436467a2013-07-08 12:37:59 +053077
Rushabh Mehta0b995402013-08-09 15:29:59 +053078 def set_supplier_from_item_default(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +053079 if self.meta.get_field("supplier") and not self.supplier:
Nabin Haitdd38a262014-12-26 13:15:21 +053080 for d in self.get("items"):
Nabin Hait33df0b42018-05-26 09:09:02 +053081 supplier = frappe.db.get_value("Item Default",
82 {"parent": d.item_code, "company": self.company}, "default_supplier")
Rushabh Mehta0b995402013-08-09 15:29:59 +053083 if supplier:
Anand Doshif78d1ae2014-03-28 13:55:00 +053084 self.supplier = supplier
Shreya Shah3c9839f2018-07-17 18:01:44 +053085 else:
86 item_group = frappe.db.get_value("Item", d.item_code, "item_group")
87 supplier = frappe.db.get_value("Item Default",
88 {"parent": item_group, "company": self.company}, "default_supplier")
89 if supplier:
90 self.supplier = supplier
Rushabh Mehta0b995402013-08-09 15:29:59 +053091 break
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053092
Nabin Hait205f7ce2013-04-26 13:35:06 +053093 def validate_stock_or_nonstock_items(self):
Rohit Waghchaureaf059952018-05-07 18:46:53 +053094 if self.meta.get_field("taxes") and not self.get_stock_items() and not self.get_asset_items():
tundebabzy9a346202017-06-16 11:00:14 +010095 tax_for_valuation = [d for d in self.get("taxes")
Nabin Hait205f7ce2013-04-26 13:35:06 +053096 if d.category in ["Valuation", "Valuation and Total"]]
tundebabzy9a346202017-06-16 11:00:14 +010097
Nabin Hait205f7ce2013-04-26 13:35:06 +053098 if tax_for_valuation:
tundebabzy9a346202017-06-16 11:00:14 +010099 for d in tax_for_valuation:
100 d.category = 'Total'
101 msgprint(_('Tax Category has been changed to "Total" because all the Items are non-stock items'))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530102
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530103 def get_asset_items(self):
Rohit Waghchaured644e6d2018-05-12 15:27:18 +0530104 if self.doctype not in ['Purchase Invoice', 'Purchase Receipt']:
105 return []
106
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530107 return [d.item_code for d in self.items if d.is_fixed_asset]
108
Saurabhfbb342c2016-04-07 16:41:31 +0530109 def set_landed_cost_voucher_amount(self):
110 for d in self.get("items"):
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530111 lc_voucher_data = frappe.db.sql("""select sum(applicable_charges), cost_center
Saurabhfbb342c2016-04-07 16:41:31 +0530112 from `tabLanded Cost Item`
113 where docstatus = 1 and purchase_receipt_item = %s""", d.name)
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530114 d.landed_cost_voucher_amount = lc_voucher_data[0][0] if lc_voucher_data else 0.0
115 if not d.cost_center and lc_voucher_data and lc_voucher_data[0][1]:
116 d.db_set('cost_center', lc_voucher_data[0][1])
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530117
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530118 def set_supplier_address(self):
119 address_dict = {
120 'supplier_address': 'address_display',
121 'shipping_address': 'shipping_address_display'
122 }
123
124 for address_field, address_display_field in address_dict.items():
125 if self.get(address_field):
126 self.set(address_display_field, get_address_display(self.get(address_field)))
127
Nabin Haitd3b62502013-01-21 17:24:31 +0530128 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530129 from frappe.utils import money_in_words
Nabin Hait5690be12015-02-12 16:09:11 +0530130 if self.meta.get_field("base_in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530131 if self.meta.get_field("base_rounded_total") and not self.is_rounded_total_disabled():
132 amount = self.base_rounded_total
133 else:
134 amount = self.base_grand_total
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530135 self.base_in_words = money_in_words(amount, self.company_currency)
136
Nabin Hait5b4c2942013-01-22 11:12:02 +0530137 if self.meta.get_field("in_words"):
Nabin Hait6b539d62018-08-29 12:41:12 +0530138 if self.meta.get_field("rounded_total") and not self.is_rounded_total_disabled():
139 amount = self.rounded_total
140 else:
141 amount = self.grand_total
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530142
143 self.in_words = money_in_words(amount, self.currency)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530144
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530145 # update valuation rate
146 def update_valuation_rate(self, parentfield):
Anand Doshi8595fcf2013-02-08 19:28:14 +0530147 """
148 item_tax_amount is the total tax amount applied on that item
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530149 stored for valuation
150
Anand Doshi8595fcf2013-02-08 19:28:14 +0530151 TODO: rename item_tax_amount to valuation_tax_amount
152 """
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530153 stock_items = self.get_stock_items() + self.get_asset_items()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530154
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530155 stock_items_qty, stock_items_amount = 0, 0
156 last_stock_item_idx = 1
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530157 for d in self.get(parentfield):
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530158 if d.item_code and d.item_code in stock_items:
159 stock_items_qty += flt(d.qty)
Nabin Hait82e3e252015-02-23 16:58:30 +0530160 stock_items_amount += flt(d.base_net_amount)
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530161 last_stock_item_idx = d.idx
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530162
Nabin Hait82e3e252015-02-23 16:58:30 +0530163 total_valuation_amount = sum([flt(d.base_tax_amount_after_discount_amount) for d in self.get("taxes")
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530164 if d.category in ["Valuation", "Valuation and Total"]])
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530165
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530166 valuation_amount_adjustment = total_valuation_amount
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530167 for i, item in enumerate(self.get(parentfield)):
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530168 if item.item_code and item.qty and item.item_code in stock_items:
Nabin Hait82e3e252015-02-23 16:58:30 +0530169 item_proportion = flt(item.base_net_amount) / stock_items_amount if stock_items_amount \
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530170 else flt(item.qty) / stock_items_qty
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530171 if i == (last_stock_item_idx - 1):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530172 item.item_tax_amount = flt(valuation_amount_adjustment,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530173 self.precision("item_tax_amount", item))
174 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530175 item.item_tax_amount = flt(item_proportion * total_valuation_amount,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530176 self.precision("item_tax_amount", item))
177 valuation_amount_adjustment -= item.item_tax_amount
178
Anand Doshi39384d32013-05-11 19:39:53 +0530179 self.round_floats_in(item)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530180 if flt(item.conversion_factor)==0.0:
bobzz-zoneb4c7bad2015-08-05 11:30:12 +0700181 item.conversion_factor = get_conversion_factor(item.item_code, item.uom).get("conversion_factor") or 1.0
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530182
Rushabh Mehta54047782013-12-26 11:07:46 +0530183 qty_in_stock_uom = flt(item.qty * item.conversion_factor)
Saurabhfbb342c2016-04-07 16:41:31 +0530184 rm_supp_cost = flt(item.rm_supp_cost) if self.doctype in ["Purchase Receipt", "Purchase Invoice"] else 0.0
nabinhaitcc0692d2014-07-17 19:16:38 +0530185
nabinhait87f24012014-07-16 19:48:29 +0530186 landed_cost_voucher_amount = flt(item.landed_cost_voucher_amount) \
Saurabhfbb342c2016-04-07 16:41:31 +0530187 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] else 0.0
Nabin Hait14b8af22014-08-28 12:42:28 +0530188
Nabin Hait82e3e252015-02-23 16:58:30 +0530189 item.valuation_rate = ((item.base_net_amount + item.item_tax_amount + rm_supp_cost
nabinhait87f24012014-07-16 19:48:29 +0530190 + landed_cost_voucher_amount) / qty_in_stock_uom)
Anand Doshi4a7248e2013-02-27 18:10:30 +0530191 else:
Anand Doshi5af812a2013-05-10 19:23:02 +0530192 item.valuation_rate = 0.0
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530193
Nabin Hait54d209f2013-03-01 18:51:10 +0530194 def validate_for_subcontracting(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530195 if not self.is_subcontracted and self.sub_contracted_items:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530196 frappe.throw(_("Please enter 'Is Subcontracted' as Yes or No"))
197
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530198 if self.is_subcontracted == "Yes":
Saurabhfbb342c2016-04-07 16:41:31 +0530199 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] and not self.supplier_warehouse:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530200 frappe.throw(_("Supplier Warehouse mandatory for sub-contracted Purchase Receipt"))
201
Nabin Haitdd38a262014-12-26 13:15:21 +0530202 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530203 if item in self.sub_contracted_items and not item.bom:
204 frappe.throw(_("Please select BOM in BOM field for Item {0}").format(item.item_code))
205
Nabin Hait07e53762018-01-05 18:19:59 +0530206 if self.doctype == "Purchase Order":
207 for supplied_item in self.get("supplied_items"):
208 if not supplied_item.reserve_warehouse:
209 frappe.throw(_("Reserved Warehouse is mandatory for Item {0} in Raw Materials supplied").format(frappe.bold(supplied_item.rm_item_code)))
pawan54465f52017-11-29 10:18:38 +0530210
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530211 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530212 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530213 if item.bom:
214 item.bom = None
215
Nabin Hait344f4432014-05-08 19:08:20 +0530216 def create_raw_materials_supplied(self, raw_material_table):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530217 if self.is_subcontracted=="Yes":
Nabin Hait344f4432014-05-08 19:08:20 +0530218 parent_items = []
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530219 backflush_raw_materials_based_on = frappe.db.get_single_value("Buying Settings",
220 "backflush_raw_materials_of_subcontract_based_on")
221 if (self.doctype == 'Purchase Receipt' and
222 backflush_raw_materials_based_on != 'BOM'):
223 self.update_raw_materials_supplied_based_on_stock_entries(raw_material_table)
224 else:
225 for item in self.get("items"):
226 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
227 item.rm_supp_cost = 0.0
228 if item.bom and item.item_code in self.sub_contracted_items:
229 self.update_raw_materials_supplied_based_on_bom(item, raw_material_table)
Nabin Hait344f4432014-05-08 19:08:20 +0530230
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530231 if [item.item_code, item.name] not in parent_items:
232 parent_items.append([item.item_code, item.name])
Nabin Hait344f4432014-05-08 19:08:20 +0530233
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530234 self.cleanup_raw_materials_supplied(parent_items, raw_material_table)
Nabin Hait54d209f2013-03-01 18:51:10 +0530235
Saurabhfbb342c2016-04-07 16:41:31 +0530236 elif self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Haitdd38a262014-12-26 13:15:21 +0530237 for item in self.get("items"):
Nabin Haita0c239d2014-04-01 18:54:38 +0530238 item.rm_supp_cost = 0.0
239
Rohit Waghchaure4b9d2f22017-02-16 15:53:40 +0530240 if self.is_subcontracted == "No" and self.get("supplied_items"):
241 self.set('supplied_items', [])
242
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530243 def update_raw_materials_supplied_based_on_stock_entries(self, raw_material_table):
244 self.set(raw_material_table, [])
245 purchase_orders = [d.purchase_order for d in self.items]
246 if purchase_orders:
247 items = get_subcontracted_raw_materials_from_se(purchase_orders)
248 backflushed_raw_materials = get_backflushed_subcontracted_raw_materials_from_se(purchase_orders, self.name)
249
250 for d in items:
251 qty = d.qty - backflushed_raw_materials.get(d.item_code, 0)
252 rm = self.append(raw_material_table, {})
253 rm.rm_item_code = d.item_code
254 rm.item_name = d.item_name
255 rm.main_item_code = d.main_item_code
256 rm.description = d.description
257 rm.stock_uom = d.stock_uom
258 rm.required_qty = qty
259 rm.consumed_qty = qty
260 rm.serial_no = d.serial_no
261 rm.batch_no = d.batch_no
262
263 # get raw materials rate
264 from erpnext.stock.utils import get_incoming_rate
265 rm.rate = get_incoming_rate({
266 "item_code": d.item_code,
267 "warehouse": self.supplier_warehouse,
268 "posting_date": self.posting_date,
269 "posting_time": self.posting_time,
270 "qty": -1 * qty,
271 "serial_no": rm.serial_no
272 })
273 if not rm.rate:
274 rm.rate = get_valuation_rate(d.item_code, self.supplier_warehouse,
275 self.doctype, self.name, currency=self.company_currency, company = self.company)
276
277 rm.amount = qty * flt(rm.rate)
278
279 def update_raw_materials_supplied_based_on_bom(self, item, raw_material_table):
rohitwaghchaurebbd9b712018-03-07 15:39:40 +0530280 exploded_item = 1
281 if hasattr(item, 'include_exploded_items'):
282 exploded_item = item.get('include_exploded_items')
283
284 bom_items = get_items_from_bom(item.item_code, item.bom, exploded_item)
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530285
286 used_alternative_items = []
287 if self.doctype == 'Purchase Receipt' and item.purchase_order:
288 used_alternative_items = get_used_alternative_items(purchase_order = item.purchase_order)
289
Nabin Hait54d209f2013-03-01 18:51:10 +0530290 raw_materials_cost = 0
pawan2ff844e2017-11-30 18:14:55 +0530291 items = list(set([d.item_code for d in bom_items]))
Manas Solanki087a2252018-05-04 16:02:38 +0530292 item_wh = frappe._dict(frappe.db.sql("""select i.item_code, id.default_warehouse
Nabin Hait5f861752018-05-23 19:37:06 +0530293 from `tabItem` i, `tabItem Default` id
294 where id.parent=i.name and id.company=%s and i.name in ({0})"""
Manas Solanki087a2252018-05-04 16:02:38 +0530295 .format(", ".join(["%s"] * len(items))), [self.company] + items))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530296
Nabin Hait344f4432014-05-08 19:08:20 +0530297 for bom_item in bom_items:
Nabin Hait07e53762018-01-05 18:19:59 +0530298 if self.doctype == "Purchase Order":
299 reserve_warehouse = bom_item.source_warehouse or item_wh.get(bom_item.item_code)
300 if frappe.db.get_value("Warehouse", reserve_warehouse, "company") != self.company:
301 reserve_warehouse = None
302
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530303 conversion_factor = item.conversion_factor
304 if (self.doctype == 'Purchase Receipt' and item.purchase_order and
305 bom_item.item_code in used_alternative_items):
306 alternative_item_data = used_alternative_items.get(bom_item.item_code)
307 bom_item.item_code = alternative_item_data.item_code
308 bom_item.item_name = alternative_item_data.item_name
309 bom_item.stock_uom = alternative_item_data.stock_uom
310 conversion_factor = alternative_item_data.conversion_factor
311 bom_item.description = alternative_item_data.description
312
Nabin Hait344f4432014-05-08 19:08:20 +0530313 # check if exists
314 exists = 0
315 for d in self.get(raw_material_table):
316 if d.main_item_code == item.item_code and d.rm_item_code == bom_item.item_code \
317 and d.reference_name == item.name:
318 rm, exists = d, 1
319 break
320
321 if not exists:
322 rm = self.append(raw_material_table, {})
323
Fahim Ali Zain TP277935b2018-02-12 11:59:07 +0530324 required_qty = flt(flt(bom_item.qty_consumed_per_unit) * (flt(item.qty) + getattr(item, 'rejected_qty', 0)) *
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530325 flt(conversion_factor), rm.precision("required_qty"))
Nabin Hait344f4432014-05-08 19:08:20 +0530326 rm.reference_name = item.name
327 rm.bom_detail_no = bom_item.name
328 rm.main_item_code = item.item_code
329 rm.rm_item_code = bom_item.item_code
330 rm.stock_uom = bom_item.stock_uom
331 rm.required_qty = required_qty
Nabin Hait07e53762018-01-05 18:19:59 +0530332 if self.doctype == "Purchase Order" and not rm.reserve_warehouse:
333 rm.reserve_warehouse = reserve_warehouse
Nabin Hait344f4432014-05-08 19:08:20 +0530334
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530335 rm.conversion_factor = conversion_factor
Nabin Hait344f4432014-05-08 19:08:20 +0530336
Saurabhfbb342c2016-04-07 16:41:31 +0530337 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Hait344f4432014-05-08 19:08:20 +0530338 rm.consumed_qty = required_qty
339 rm.description = bom_item.description
340 if item.batch_no and not rm.batch_no:
341 rm.batch_no = item.batch_no
342
Nabin Haite96e83d2014-10-08 18:06:14 +0530343 # get raw materials rate
Nabin Haitfce28812014-10-08 18:38:27 +0530344 if self.doctype == "Purchase Receipt":
345 from erpnext.stock.utils import get_incoming_rate
Nabin Haitfb6e4342014-10-15 11:34:40 +0530346 rm.rate = get_incoming_rate({
Nabin Haitfce28812014-10-08 18:38:27 +0530347 "item_code": bom_item.item_code,
348 "warehouse": self.supplier_warehouse,
349 "posting_date": self.posting_date,
350 "posting_time": self.posting_time,
351 "qty": -1 * required_qty,
352 "serial_no": rm.serial_no
353 })
Nabin Haitfb6e4342014-10-15 11:34:40 +0530354 if not rm.rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530355 rm.rate = get_valuation_rate(bom_item.item_code, self.supplier_warehouse,
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530356 self.doctype, self.name, currency=self.company_currency, company = self.company)
Nabin Haitfce28812014-10-08 18:38:27 +0530357 else:
358 rm.rate = bom_item.rate
Nabin Haite96e83d2014-10-08 18:06:14 +0530359
Nabin Haitfce28812014-10-08 18:38:27 +0530360 rm.amount = required_qty * flt(rm.rate)
Nabin Haite96e83d2014-10-08 18:06:14 +0530361 raw_materials_cost += flt(rm.amount)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530362
Nabin Hait14aa9c52016-04-18 15:54:01 +0530363 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Nabin Hait344f4432014-05-08 19:08:20 +0530364 item.rm_supp_cost = raw_materials_cost
365
366 def cleanup_raw_materials_supplied(self, parent_items, raw_material_table):
367 """Remove all those child items which are no longer present in main item table"""
368 delete_list = []
369 for d in self.get(raw_material_table):
370 if [d.main_item_code, d.reference_name] not in parent_items:
371 # mark for deletion from doclist
Nabin Haitc3d1d6a2014-06-04 16:41:22 +0530372 delete_list.append(d)
Nabin Hait344f4432014-05-08 19:08:20 +0530373
374 # delete from doclist
375 if delete_list:
376 rm_supplied_details = self.get(raw_material_table)
377 self.set(raw_material_table, [])
378 for d in rm_supplied_details:
379 if d not in delete_list:
380 self.append(raw_material_table, d)
Nabin Hait54d209f2013-03-01 18:51:10 +0530381
Nabin Hait5418d712013-02-27 18:11:17 +0530382 @property
383 def sub_contracted_items(self):
384 if not hasattr(self, "_sub_contracted_items"):
Nabin Haitebd51442013-04-23 15:36:26 +0530385 self._sub_contracted_items = []
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530386 item_codes = list(set(item.item_code for item in
Nabin Haitdd38a262014-12-26 13:15:21 +0530387 self.get("items")))
Nabin Haitebd51442013-04-23 15:36:26 +0530388 if item_codes:
Anand Doshie9baaa62014-02-26 12:35:33 +0530389 self._sub_contracted_items = [r[0] for r in frappe.db.sql("""select name
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530390 from `tabItem` where name in (%s) and is_sub_contracted_item=1""" % \
Nabin Haitebd51442013-04-23 15:36:26 +0530391 (", ".join((["%s"]*len(item_codes))),), item_codes)]
Nabin Hait5418d712013-02-27 18:11:17 +0530392
393 return self._sub_contracted_items
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530394
nabinhait614fb752014-07-14 10:47:50 +0530395 def set_qty_as_per_stock_uom(self):
Nabin Haitdd38a262014-12-26 13:15:21 +0530396 for d in self.get("items"):
Nabin Haitfd4bcd82015-05-22 16:55:40 +0530397 if d.meta.get_field("stock_qty"):
nabinhait614fb752014-07-14 10:47:50 +0530398 if not d.conversion_factor:
Nabin Haite6e456b2015-05-13 17:21:44 +0530399 frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
Rushabh Mehta5b51cc82014-07-21 18:25:45 +0530400 d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530401
Saurabh130c57b2016-04-04 15:49:36 +0530402 def validate_purchase_return(self):
403 for d in self.get("items"):
404 if self.is_return and flt(d.rejected_qty) != 0:
405 frappe.throw(_("Row #{0}: Rejected Qty can not be entered in Purchase Return").format(d.idx))
406
407 # validate rate with ref PR
408
409 def validate_rejected_warehouse(self):
410 for d in self.get("items"):
411 if flt(d.rejected_qty) and not d.rejected_warehouse:
Saurabhfbb342c2016-04-07 16:41:31 +0530412 if self.rejected_warehouse:
413 d.rejected_warehouse = self.rejected_warehouse
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530414
Saurabh130c57b2016-04-04 15:49:36 +0530415 if not d.rejected_warehouse:
416 frappe.throw(_("Row #{0}: Rejected Warehouse is mandatory against rejected Item {1}").format(d.idx, d.item_code))
417
418 # validate accepted and rejected qty
419 def validate_accepted_rejected_qty(self):
420 for d in self.get("items"):
Saurabh4f4d0a82017-03-13 14:31:48 +0530421 self.validate_negative_quantity(d, ["received_qty","qty", "rejected_qty"])
Saurabh130c57b2016-04-04 15:49:36 +0530422 if not flt(d.received_qty) and flt(d.qty):
423 d.received_qty = flt(d.qty) - flt(d.rejected_qty)
424
425 elif not flt(d.qty) and flt(d.rejected_qty):
426 d.qty = flt(d.received_qty) - flt(d.rejected_qty)
427
428 elif not flt(d.rejected_qty):
429 d.rejected_qty = flt(d.received_qty) - flt(d.qty)
430
431 # Check Received Qty = Accepted Qty + Rejected Qty
432 if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)):
433 frappe.throw(_("Accepted + Rejected Qty must be equal to Received quantity for Item {0}").format(d.item_code))
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530434
Saurabh4f4d0a82017-03-13 14:31:48 +0530435 def validate_negative_quantity(self, item_row, field_list):
436 if self.is_return:
437 return
438
439 item_row = item_row.as_dict()
440 for fieldname in field_list:
441 if flt(item_row[fieldname]) < 0:
442 frappe.throw(_("Row #{0}: {1} can not be negative for item {2}".format(item_row['idx'],
443 frappe.get_meta(item_row.doctype).get_label(fieldname), item_row['item_code'])))
444
Mangesh-Khairnar5e474f42019-03-06 14:46:38 +0530445 def check_for_on_hold_or_closed_status(self, ref_doctype, ref_fieldname):
446 for d in self.get("items"):
447 if d.get(ref_fieldname):
448 status = frappe.db.get_value(ref_doctype, d.get(ref_fieldname), "status")
449 if status in ("Closed", "On Hold"):
450 frappe.throw(_("{0} {1} is {2}").format(ref_doctype,d.get(ref_fieldname), status))
451
Saurabhe29248b2016-04-04 11:55:52 +0530452 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait07e53762018-01-05 18:19:59 +0530453 self.update_ordered_and_reserved_qty()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530454
Saurabhe29248b2016-04-04 11:55:52 +0530455 sl_entries = []
456 stock_items = self.get_stock_items()
457
458 for d in self.get('items'):
459 if d.item_code in stock_items and d.warehouse:
460 pr_qty = flt(d.qty) * flt(d.conversion_factor)
461
462 if pr_qty:
Saurabhe29248b2016-04-04 11:55:52 +0530463 sle = self.get_sl_entries(d, {
464 "actual_qty": flt(pr_qty),
465 "serial_no": cstr(d.serial_no).strip()
466 })
467 if self.is_return:
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530468 original_incoming_rate = frappe.db.get_value("Stock Ledger Entry",
469 {"voucher_type": "Purchase Receipt", "voucher_no": self.return_against,
Nabin Haitb81ed452016-05-11 12:52:31 +0530470 "item_code": d.item_code}, "incoming_rate")
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530471
Saurabhe29248b2016-04-04 11:55:52 +0530472 sle.update({
Nabin Haitb81ed452016-05-11 12:52:31 +0530473 "outgoing_rate": original_incoming_rate
Saurabhe29248b2016-04-04 11:55:52 +0530474 })
475 else:
Nabin Haitb81ed452016-05-11 12:52:31 +0530476 val_rate_db_precision = 6 if cint(self.precision("valuation_rate", d)) <= 6 else 9
477 incoming_rate = flt(d.valuation_rate, val_rate_db_precision)
Saurabhe29248b2016-04-04 11:55:52 +0530478 sle.update({
Nabin Haitb81ed452016-05-11 12:52:31 +0530479 "incoming_rate": incoming_rate
Saurabhe29248b2016-04-04 11:55:52 +0530480 })
481 sl_entries.append(sle)
482
Rohit Waghchaure560ba392016-08-29 18:19:32 +0530483 if flt(d.rejected_qty) != 0:
Saurabhe29248b2016-04-04 11:55:52 +0530484 sl_entries.append(self.get_sl_entries(d, {
485 "warehouse": d.rejected_warehouse,
486 "actual_qty": flt(d.rejected_qty) * flt(d.conversion_factor),
487 "serial_no": cstr(d.rejected_serial_no).strip(),
488 "incoming_rate": 0.0
489 }))
490
491 self.make_sl_entries_for_supplier_warehouse(sl_entries)
492 self.make_sl_entries(sl_entries, allow_negative_stock=allow_negative_stock,
493 via_landed_cost_voucher=via_landed_cost_voucher)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530494
Nabin Hait07e53762018-01-05 18:19:59 +0530495 def update_ordered_and_reserved_qty(self):
Nabin Hait14aa9c52016-04-18 15:54:01 +0530496 po_map = {}
497 for d in self.get("items"):
498 if self.doctype=="Purchase Receipt" \
Rohit Waghchaurea71d9d32016-07-05 00:34:00 +0530499 and d.purchase_order:
500 po_map.setdefault(d.purchase_order, []).append(d.purchase_order_item)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530501
Nabin Hait14aa9c52016-04-18 15:54:01 +0530502 elif self.doctype=="Purchase Invoice" and d.purchase_order and d.po_detail:
503 po_map.setdefault(d.purchase_order, []).append(d.po_detail)
504
505 for po, po_item_rows in po_map.items():
506 if po and po_item_rows:
507 po_obj = frappe.get_doc("Purchase Order", po)
508
509 if po_obj.status in ["Closed", "Cancelled"]:
510 frappe.throw(_("{0} {1} is cancelled or closed").format(_("Purchase Order"), po),
511 frappe.InvalidStatusError)
512
513 po_obj.update_ordered_qty(po_item_rows)
Nabin Hait07e53762018-01-05 18:19:59 +0530514 if self.is_subcontracted:
515 po_obj.update_reserved_qty_for_subcontract()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530516
Saurabhe29248b2016-04-04 11:55:52 +0530517 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
518 if hasattr(self, 'supplied_items'):
519 for d in self.get('supplied_items'):
520 # negative quantity is passed, as raw material qty has to be decreased
521 # when PR is submitted and it has to be increased when PR is cancelled
522 sl_entries.append(self.get_sl_entries(d, {
523 "item_code": d.rm_item_code,
524 "warehouse": self.supplier_warehouse,
525 "actual_qty": -1*flt(d.consumed_qty),
526 }))
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530527
rohitwaghchaurefe226862017-12-28 16:11:27 +0530528 def on_submit(self):
529 if self.get('is_return'):
530 return
531
Rohit Waghchaureab842542018-04-26 19:18:29 +0530532 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530533 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
534
535 self.process_fixed_asset()
536 self.update_fixed_asset(field)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530537
rohitwaghchaurefe226862017-12-28 16:11:27 +0530538 update_last_purchase_rate(self, is_submit = 1)
539
540 def on_cancel(self):
Rohit Waghchaure5fa9a7a2019-04-01 00:40:38 +0530541 super(BuyingController, self).on_cancel()
542
rohitwaghchaurefe226862017-12-28 16:11:27 +0530543 if self.get('is_return'):
544 return
545
546 update_last_purchase_rate(self, is_submit = 0)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530547 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530548 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
549
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530550 self.delete_linked_asset()
551 self.update_fixed_asset(field, delete_asset=True)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530552
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530553 def validate_budget(self):
554 if self.docstatus == 1:
555 for data in self.get('items'):
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530556 args = data.as_dict()
557 args.update({
558 'doctype': self.doctype,
rohitwaghchaure34c18772018-06-25 10:31:08 +0530559 'company': self.company,
560 'posting_date': (self.schedule_date
561 if self.doctype == 'Material Request' else self.transaction_date)
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530562 })
563
564 validate_expense_against_budget(args)
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530565
Rohit Waghchaureab842542018-04-26 19:18:29 +0530566 def process_fixed_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530567 if self.doctype == 'Purchase Invoice' and not self.update_stock:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530568 return
569
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530570 asset_items = self.get_asset_items()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530571 if asset_items:
572 self.make_serial_nos_for_asset(asset_items)
573
574 def make_serial_nos_for_asset(self, asset_items):
575 items_data = get_asset_item_details(asset_items)
576
577 for d in self.items:
578 if d.is_fixed_asset:
579 item_data = items_data.get(d.item_code)
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530580 if not d.asset:
581 asset = self.make_asset(d)
582 d.db_set('asset', asset)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530583
584 if item_data.get('has_serial_no'):
585 # If item has serial no
586 if item_data.get('serial_no_series') and not d.serial_no:
587 serial_nos = get_auto_serial_nos(item_data.get('serial_no_series'), d.qty)
588 elif d.serial_no:
589 serial_nos = d.serial_no
590 elif not d.serial_no:
591 frappe.throw(_("Serial no is mandatory for the item {0}").format(d.item_code))
592
593 auto_make_serial_nos({
594 'serial_no': serial_nos,
595 'item_code': d.item_code,
596 'via_stock_ledger': False,
597 'company': self.company,
598 'actual_qty': d.qty,
599 'purchase_document_type': self.doctype,
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530600 'purchase_document_no': self.name,
Rohit Waghchaure647d5952018-06-11 18:53:55 +0530601 'asset': d.asset,
602 'location': d.asset_location
Rohit Waghchaureab842542018-04-26 19:18:29 +0530603 })
604 d.db_set('serial_no', serial_nos)
605
Rohit Waghchaureab842542018-04-26 19:18:29 +0530606 if d.asset:
607 self.make_asset_movement(d)
608
609 def make_asset(self, row):
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530610 if not row.asset_location:
611 frappe.throw(_("Row {0}: Enter location for the asset item {1}").format(row.idx, row.item_code))
612
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530613 item_data = frappe.db.get_value('Item',
614 row.item_code, ['asset_naming_series', 'asset_category'], as_dict=1)
615
Rohit Waghchaure16bc8532018-05-12 12:06:00 +0530616 purchase_amount = flt(row.base_net_amount + row.item_tax_amount)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530617 asset = frappe.get_doc({
618 'doctype': 'Asset',
619 'item_code': row.item_code,
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530620 'asset_name': row.item_name,
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530621 'naming_series': item_data.get('asset_naming_series') or 'AST',
622 'asset_category': item_data.get('asset_category'),
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530623 'location': row.asset_location,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530624 'company': self.company,
625 'purchase_date': self.posting_date,
Rohit Waghchaure0ea6fe42018-05-08 23:31:58 +0530626 'calculate_depreciation': 1,
Rohit Waghchaure16bc8532018-05-12 12:06:00 +0530627 'purchase_receipt_amount': purchase_amount,
628 'gross_purchase_amount': purchase_amount,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530629 'purchase_receipt': self.name if self.doctype == 'Purchase Receipt' else None,
630 'purchase_invoice': self.name if self.doctype == 'Purchase Invoice' else None
631 })
632
633 asset.flags.ignore_validate = True
634 asset.flags.ignore_mandatory = True
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530635 asset.set_missing_values()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530636 asset.insert()
637
638 frappe.msgprint(_("Asset {0} created").format(asset.name))
639 return asset.name
640
641 def make_asset_movement(self, row):
642 asset_movement = frappe.get_doc({
643 'doctype': 'Asset Movement',
644 'asset': row.asset,
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530645 'target_location': row.asset_location,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530646 'purpose': 'Receipt',
647 'serial_no': row.serial_no,
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530648 'quantity': len(get_serial_nos(row.serial_no)),
Rohit Waghchaureab842542018-04-26 19:18:29 +0530649 'company': self.company,
650 'transaction_date': self.posting_date,
651 'reference_doctype': self.doctype,
652 'reference_name': self.name
653 }).insert()
654
655 return asset_movement.name
656
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530657 def update_fixed_asset(self, field, delete_asset = False):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530658 for d in self.get("items"):
659 if d.is_fixed_asset and d.asset:
660 asset = frappe.get_doc("Asset", d.asset)
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530661
662 if delete_asset and asset.docstatus == 0:
663 frappe.delete_doc("Asset", asset.name)
664 d.db_set('asset', None)
665 continue
666
Rohit Waghchaureab842542018-04-26 19:18:29 +0530667 if self.docstatus in [0, 1] and not asset.get(field):
668 asset.set(field, self.name)
669 asset.purchase_date = self.posting_date
670 asset.supplier = self.supplier
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530671 elif self.docstatus == 2:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530672 asset.set(field, None)
673 asset.supplier = None
674
675 asset.flags.ignore_validate_update_after_submit = True
Rohit Waghchaurea02640e2018-05-16 10:49:12 +0530676 asset.flags.ignore_mandatory = True
Rohit Waghchaureab842542018-04-26 19:18:29 +0530677 if asset.docstatus == 0:
678 asset.flags.ignore_validate = True
679
680 asset.save()
681
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530682 def delete_linked_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530683 if self.doctype == 'Purchase Invoice' and not self.get('update_stock'):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530684 return
685
Nabin Hait1e7c32b2018-09-26 18:01:00 +0530686 frappe.db.sql("delete from `tabAsset Movement` where reference_name=%s", self.name)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530687 frappe.db.sql("delete from `tabSerial No` where purchase_document_no=%s", self.name)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530688
Nabin Hait5a834202017-10-05 19:51:10 +0530689 def validate_schedule_date(self):
Sahil Khan34766c02018-12-20 18:50:24 +0530690 if not self.get("items"):
691 return
692 if not self.schedule_date:
Nabin Hait5a834202017-10-05 19:51:10 +0530693 self.schedule_date = min([d.schedule_date for d in self.get("items")])
694
695 if self.schedule_date:
696 for d in self.get('items'):
697 if not d.schedule_date:
698 d.schedule_date = self.schedule_date
699
Prateeksha Singhcbd06fd2018-01-05 21:28:01 +0530700 if (d.schedule_date and self.transaction_date and
701 getdate(d.schedule_date) < getdate(self.transaction_date)):
Nabin Hait96b264b2018-01-02 11:50:29 +0530702 frappe.throw(_("Row #{0}: Reqd by Date cannot be before Transaction Date").format(d.idx))
Nabin Hait5a834202017-10-05 19:51:10 +0530703 else:
Nabin Hait96b264b2018-01-02 11:50:29 +0530704 frappe.throw(_("Please enter Reqd by Date"))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530705
Zarrarfc03a042018-06-04 12:52:52 +0530706 def validate_items(self):
707 # validate items to see if they have is_purchase_item or is_subcontracted_item enabled
Nabin Hait0bef91c2018-06-18 16:33:48 +0530708 if self.doctype=="Material Request": return
Zarrarfc03a042018-06-04 12:52:52 +0530709
rohitwaghchaure50d8c4a2018-06-05 13:08:10 +0530710 if hasattr(self, "is_subcontracted") and self.is_subcontracted == 'Yes':
Zarrarfc03a042018-06-04 12:52:52 +0530711 validate_item_type(self, "is_sub_contracted_item", "subcontracted")
712 else:
713 validate_item_type(self, "is_purchase_item", "purchase")
714
rohitwaghchaurebbd9b712018-03-07 15:39:40 +0530715def get_items_from_bom(item_code, bom, exploded_item=1):
716 doctype = "BOM Item" if not exploded_item else "BOM Explosion Item"
717
718 bom_items = frappe.db.sql("""select t2.item_code, t2.name,
719 t2.rate, t2.stock_uom, t2.source_warehouse, t2.description,
720 t2.stock_qty / ifnull(t1.quantity, 1) as qty_consumed_per_unit
721 from
722 `tabBOM` t1, `tab{0}` t2, tabItem t3
723 where
724 t2.parent = t1.name and t1.item = %s
725 and t1.docstatus = 1 and t1.is_active = 1 and t1.name = %s
726 and t2.item_code = t3.name and t3.is_stock_item = 1""".format(doctype),
727 (item_code, bom), as_dict=1)
728
729 if not bom_items:
730 msgprint(_("Specified BOM {0} does not exist for Item {1}").format(bom, item_code), raise_exception=1)
731
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530732 return bom_items
Rohit Waghchaureab842542018-04-26 19:18:29 +0530733
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530734def get_subcontracted_raw_materials_from_se(purchase_orders):
735 return frappe.db.sql("""
736 select
737 sed.item_name, sed.item_code, sum(sed.qty) as qty, sed.description,
738 sed.stock_uom, sed.subcontracted_item as main_item_code, sed.serial_no, sed.batch_no
739 from `tabStock Entry` se,`tabStock Entry Detail` sed
740 where
Rohit Waghchaure5816fc22019-03-26 12:39:28 +0530741 se.name = sed.parent and se.docstatus=1 and se.purpose='Send to Subcontractor'
Rohit Waghchaureed71c362018-06-28 18:36:35 +0530742 and se.purchase_order in (%s) and ifnull(sed.t_warehouse, '') != ''
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530743 group by sed.item_code, sed.t_warehouse
744 """ % (','.join(['%s'] * len(purchase_orders))), tuple(purchase_orders), as_dict=1)
745
746def get_backflushed_subcontracted_raw_materials_from_se(purchase_orders, purchase_receipt):
747 return frappe._dict(frappe.db.sql("""
748 select
749 prsi.rm_item_code as item_code, sum(prsi.consumed_qty) as qty
750 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pri, `tabPurchase Receipt Item Supplied` prsi
751 where
Rohit Waghchaureed71c362018-06-28 18:36:35 +0530752 pr.name = pri.parent and pr.name = prsi.parent and pri.purchase_order in (%s)
rohitwaghchaure01fe4a32018-07-01 16:41:39 +0530753 and pri.item_code = prsi.main_item_code and pr.name != '%s' and pr.docstatus = 1
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530754 group by prsi.rm_item_code
755 """ % (','.join(['%s'] * len(purchase_orders)), purchase_receipt), tuple(purchase_orders)))
756
Rohit Waghchaureab842542018-04-26 19:18:29 +0530757def get_asset_item_details(asset_items):
758 asset_items_data = {}
759 for d in frappe.get_all('Item', fields = ["name", "has_serial_no", "serial_no_series"],
760 filters = {'name': ('in', asset_items)}):
761 asset_items_data.setdefault(d.name, d)
762
763 return asset_items_data
Ameya Shenoy873e28d2018-06-06 05:53:19 +0000764
Zarrarfc03a042018-06-04 12:52:52 +0530765def validate_item_type(doc, fieldname, message):
766 # iterate through items and check if they are valid sales or purchase items
Zarrar7c088ff2018-06-05 10:32:09 +0530767 items = [d.item_code for d in doc.items if d.item_code]
768
769 # No validation check inase of creating transaction using 'Opening Invoice Creation Tool'
770 if not items:
771 return
772
Suraj Shettybfc195d2018-09-21 10:20:52 +0530773 item_list = ", ".join(["%s" % frappe.db.escape(d) for d in items])
Zarrarfc03a042018-06-04 12:52:52 +0530774
775 invalid_items = [d[0] for d in frappe.db.sql("""
776 select item_code from tabItem where name in ({0}) and {1}=0
777 """.format(item_list, fieldname), as_list=True)]
778
779 if invalid_items:
Faris Ansari2ab6e0e2018-09-19 13:13:59 +0530780 items = ", ".join([d for d in invalid_items])
781
782 if len(invalid_items) > 1:
783 error_message = _("Following items {0} are not marked as {1} item. You can enable them as {1} item from its Item master".format(items, message))
784 else:
785 error_message = _("Following item {0} is not marked as {1} item. You can enable them as {1} item from its Item master".format(items, message))
786
787 frappe.throw(error_message)