blob: 70a07733a7e9b613bf0f9530aada8e30c1ebb3f2 [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
Anand Doshi756dca72013-01-15 18:39:21 +053015
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +053016from erpnext.accounts.doctype.budget.budget import validate_expense_against_budget
Rushabh Mehta1f847992013-12-12 19:12:19 +053017from erpnext.controllers.stock_controller import StockController
Nabin Haitbf495c92013-01-30 12:49:08 +053018
Nabin Hait89a94d82013-03-19 12:01:46 +053019class BuyingController(StockController):
Rushabh Mehta5b51cc82014-07-21 18:25:45 +053020 def __setup__(self):
Nabin Haitde9c8a92015-02-23 01:06:00 +053021 if hasattr(self, "taxes"):
Nabin Hait45dce892017-09-14 15:17:38 +053022 self.flags.print_taxes_with_zero_amount = cint(frappe.db.get_single_value("Print Settings",
23 "print_taxes_with_zero_amount"))
rohitwaghchaurebf4c1142018-01-08 15:20:15 +053024 self.flags.show_inclusive_tax_in_print = self.is_inclusive_tax()
25
Rushabh Mehtac567e8e2015-02-03 17:55:52 +053026 self.print_templates = {
rohitwaghchaurebf4c1142018-01-08 15:20:15 +053027 "total": "templates/print_formats/includes/total.html",
Rushabh Mehtac567e8e2015-02-03 17:55:52 +053028 "taxes": "templates/print_formats/includes/taxes.html"
Rushabh Mehta5b51cc82014-07-21 18:25:45 +053029 }
30
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053031 def get_feed(self):
rohitwaghchaurea1064a62016-03-03 14:00:35 +053032 if self.get("supplier_name"):
33 return _("From {0} | {1} {2}").format(self.supplier_name, self.currency,
34 self.grand_total)
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053035
Saurabh6f753182013-03-20 12:55:28 +053036 def validate(self):
37 super(BuyingController, self).validate()
Nabin Hait365ae272014-04-03 17:38:54 +053038 if getattr(self, "supplier", None) and not self.supplier_name:
Nabin Hait1d218422015-07-17 15:19:02 +053039 self.supplier_name = frappe.db.get_value("Supplier", self.supplier, "supplier_name")
Rushabh Mehtaea0ff232016-07-07 14:02:26 +053040
Zarrarfc03a042018-06-04 12:52:52 +053041 self.validate_items()
nabinhait614fb752014-07-14 10:47:50 +053042 self.set_qty_as_per_stock_uom()
Nabin Hait205f7ce2013-04-26 13:35:06 +053043 self.validate_stock_or_nonstock_items()
Anand Doshi373680b2013-10-10 16:04:40 +053044 self.validate_warehouse()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053045
Nabin Hait14aa9c52016-04-18 15:54:01 +053046 if self.doctype=="Purchase Invoice":
47 self.validate_purchase_receipt_if_update_stock()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053048
Nabin Hait14aa9c52016-04-18 15:54:01 +053049 if self.doctype=="Purchase Receipt" or (self.doctype=="Purchase Invoice" and self.update_stock):
Rohit Waghchaure560ba392016-08-29 18:19:32 +053050 # self.validate_purchase_return()
Saurabhfbb342c2016-04-07 16:41:31 +053051 self.validate_rejected_warehouse()
52 self.validate_accepted_rejected_qty()
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053053 validate_for_items(self)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053054
Saurabhfbb342c2016-04-07 16:41:31 +053055 #sub-contracting
56 self.validate_for_subcontracting()
57 self.create_raw_materials_supplied("supplied_items")
58 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"):
Saurabhfbb342c2016-04-07 16:41:31 +053061 self.update_valuation_rate("items")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053062
Anand Doshi3543f302013-05-24 19:25:01 +053063 def set_missing_values(self, for_validate=False):
Anand Doshiabc10032013-06-14 17:44:03 +053064 super(BuyingController, self).set_missing_values(for_validate)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053065
Rushabh Mehta0b995402013-08-09 15:29:59 +053066 self.set_supplier_from_item_default()
Nabin Hait096d3632013-10-17 17:01:14 +053067 self.set_price_list_currency("Buying")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053068
Anand Doshi3543f302013-05-24 19:25:01 +053069 # set contact and address details for supplier, if they are not mentioned
Nabin Hait365ae272014-04-03 17:38:54 +053070 if getattr(self, "supplier", None):
Nabin Hait7eba1a32017-10-02 15:59:27 +053071 self.update_if_missing(get_party_details(self.supplier, party_type="Supplier", ignore_permissions=self.flags.ignore_permissions, doctype=self.doctype, company=self.company))
Rushabh Mehta886c9ef2013-07-08 12:08:06 +053072
Nabin Haitcccc45e2016-10-05 17:15:43 +053073 self.set_missing_item_details(for_validate)
Rushabh Mehta436467a2013-07-08 12:37:59 +053074
Rushabh Mehta0b995402013-08-09 15:29:59 +053075 def set_supplier_from_item_default(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +053076 if self.meta.get_field("supplier") and not self.supplier:
Nabin Haitdd38a262014-12-26 13:15:21 +053077 for d in self.get("items"):
Nabin Hait33df0b42018-05-26 09:09:02 +053078 supplier = frappe.db.get_value("Item Default",
79 {"parent": d.item_code, "company": self.company}, "default_supplier")
Rushabh Mehta0b995402013-08-09 15:29:59 +053080 if supplier:
Anand Doshif78d1ae2014-03-28 13:55:00 +053081 self.supplier = supplier
Shreya Shah3c9839f2018-07-17 18:01:44 +053082 else:
83 item_group = frappe.db.get_value("Item", d.item_code, "item_group")
84 supplier = frappe.db.get_value("Item Default",
85 {"parent": item_group, "company": self.company}, "default_supplier")
86 if supplier:
87 self.supplier = supplier
Rushabh Mehta0b995402013-08-09 15:29:59 +053088 break
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053089
Nabin Hait205f7ce2013-04-26 13:35:06 +053090 def validate_stock_or_nonstock_items(self):
Rohit Waghchaureaf059952018-05-07 18:46:53 +053091 if self.meta.get_field("taxes") and not self.get_stock_items() and not self.get_asset_items():
tundebabzy9a346202017-06-16 11:00:14 +010092 tax_for_valuation = [d for d in self.get("taxes")
Nabin Hait205f7ce2013-04-26 13:35:06 +053093 if d.category in ["Valuation", "Valuation and Total"]]
tundebabzy9a346202017-06-16 11:00:14 +010094
Nabin Hait205f7ce2013-04-26 13:35:06 +053095 if tax_for_valuation:
tundebabzy9a346202017-06-16 11:00:14 +010096 for d in tax_for_valuation:
97 d.category = 'Total'
98 msgprint(_('Tax Category has been changed to "Total" because all the Items are non-stock items'))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053099
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530100 def get_asset_items(self):
Rohit Waghchaured644e6d2018-05-12 15:27:18 +0530101 if self.doctype not in ['Purchase Invoice', 'Purchase Receipt']:
102 return []
103
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530104 return [d.item_code for d in self.items if d.is_fixed_asset]
105
Saurabhfbb342c2016-04-07 16:41:31 +0530106 def set_landed_cost_voucher_amount(self):
107 for d in self.get("items"):
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530108 lc_voucher_data = frappe.db.sql("""select sum(applicable_charges), cost_center
Saurabhfbb342c2016-04-07 16:41:31 +0530109 from `tabLanded Cost Item`
110 where docstatus = 1 and purchase_receipt_item = %s""", d.name)
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530111 d.landed_cost_voucher_amount = lc_voucher_data[0][0] if lc_voucher_data else 0.0
112 if not d.cost_center and lc_voucher_data and lc_voucher_data[0][1]:
113 d.db_set('cost_center', lc_voucher_data[0][1])
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530114
Nabin Haitd3b62502013-01-21 17:24:31 +0530115 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530116 from frappe.utils import money_in_words
Nabin Hait5690be12015-02-12 16:09:11 +0530117 if self.meta.get_field("base_in_words"):
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530118 self.base_in_words = money_in_words(self.base_grand_total, self.company_currency)
Nabin Hait5b4c2942013-01-22 11:12:02 +0530119 if self.meta.get_field("in_words"):
Nabin Hait188f69a2015-02-12 17:55:50 +0530120 self.in_words = money_in_words(self.grand_total, self.currency)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530121
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530122 # update valuation rate
123 def update_valuation_rate(self, parentfield):
Anand Doshi8595fcf2013-02-08 19:28:14 +0530124 """
125 item_tax_amount is the total tax amount applied on that item
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530126 stored for valuation
127
Anand Doshi8595fcf2013-02-08 19:28:14 +0530128 TODO: rename item_tax_amount to valuation_tax_amount
129 """
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530130 stock_items = self.get_stock_items() + self.get_asset_items()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530131
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530132 stock_items_qty, stock_items_amount = 0, 0
133 last_stock_item_idx = 1
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530134 for d in self.get(parentfield):
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530135 if d.item_code and d.item_code in stock_items:
136 stock_items_qty += flt(d.qty)
Nabin Hait82e3e252015-02-23 16:58:30 +0530137 stock_items_amount += flt(d.base_net_amount)
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530138 last_stock_item_idx = d.idx
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530139
Nabin Hait82e3e252015-02-23 16:58:30 +0530140 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 +0530141 if d.category in ["Valuation", "Valuation and Total"]])
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530142
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530143 valuation_amount_adjustment = total_valuation_amount
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530144 for i, item in enumerate(self.get(parentfield)):
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530145 if item.item_code and item.qty and item.item_code in stock_items:
Nabin Hait82e3e252015-02-23 16:58:30 +0530146 item_proportion = flt(item.base_net_amount) / stock_items_amount if stock_items_amount \
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530147 else flt(item.qty) / stock_items_qty
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530148 if i == (last_stock_item_idx - 1):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530149 item.item_tax_amount = flt(valuation_amount_adjustment,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530150 self.precision("item_tax_amount", item))
151 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530152 item.item_tax_amount = flt(item_proportion * total_valuation_amount,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530153 self.precision("item_tax_amount", item))
154 valuation_amount_adjustment -= item.item_tax_amount
155
Anand Doshi39384d32013-05-11 19:39:53 +0530156 self.round_floats_in(item)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530157 if flt(item.conversion_factor)==0.0:
bobzz-zoneb4c7bad2015-08-05 11:30:12 +0700158 item.conversion_factor = get_conversion_factor(item.item_code, item.uom).get("conversion_factor") or 1.0
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530159
Rushabh Mehta54047782013-12-26 11:07:46 +0530160 qty_in_stock_uom = flt(item.qty * item.conversion_factor)
Saurabhfbb342c2016-04-07 16:41:31 +0530161 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 +0530162
nabinhait87f24012014-07-16 19:48:29 +0530163 landed_cost_voucher_amount = flt(item.landed_cost_voucher_amount) \
Saurabhfbb342c2016-04-07 16:41:31 +0530164 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] else 0.0
Nabin Hait14b8af22014-08-28 12:42:28 +0530165
Nabin Hait82e3e252015-02-23 16:58:30 +0530166 item.valuation_rate = ((item.base_net_amount + item.item_tax_amount + rm_supp_cost
nabinhait87f24012014-07-16 19:48:29 +0530167 + landed_cost_voucher_amount) / qty_in_stock_uom)
Anand Doshi4a7248e2013-02-27 18:10:30 +0530168 else:
Anand Doshi5af812a2013-05-10 19:23:02 +0530169 item.valuation_rate = 0.0
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530170
Nabin Hait54d209f2013-03-01 18:51:10 +0530171 def validate_for_subcontracting(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530172 if not self.is_subcontracted and self.sub_contracted_items:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530173 frappe.throw(_("Please enter 'Is Subcontracted' as Yes or No"))
174
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530175 if self.is_subcontracted == "Yes":
Saurabhfbb342c2016-04-07 16:41:31 +0530176 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] and not self.supplier_warehouse:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530177 frappe.throw(_("Supplier Warehouse mandatory for sub-contracted Purchase Receipt"))
178
Nabin Haitdd38a262014-12-26 13:15:21 +0530179 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530180 if item in self.sub_contracted_items and not item.bom:
181 frappe.throw(_("Please select BOM in BOM field for Item {0}").format(item.item_code))
182
Nabin Hait07e53762018-01-05 18:19:59 +0530183 if self.doctype == "Purchase Order":
184 for supplied_item in self.get("supplied_items"):
185 if not supplied_item.reserve_warehouse:
186 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 +0530187
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530188 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530189 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530190 if item.bom:
191 item.bom = None
192
Nabin Hait344f4432014-05-08 19:08:20 +0530193 def create_raw_materials_supplied(self, raw_material_table):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530194 if self.is_subcontracted=="Yes":
Nabin Hait344f4432014-05-08 19:08:20 +0530195 parent_items = []
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530196 backflush_raw_materials_based_on = frappe.db.get_single_value("Buying Settings",
197 "backflush_raw_materials_of_subcontract_based_on")
198 if (self.doctype == 'Purchase Receipt' and
199 backflush_raw_materials_based_on != 'BOM'):
200 self.update_raw_materials_supplied_based_on_stock_entries(raw_material_table)
201 else:
202 for item in self.get("items"):
203 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
204 item.rm_supp_cost = 0.0
205 if item.bom and item.item_code in self.sub_contracted_items:
206 self.update_raw_materials_supplied_based_on_bom(item, raw_material_table)
Nabin Hait344f4432014-05-08 19:08:20 +0530207
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530208 if [item.item_code, item.name] not in parent_items:
209 parent_items.append([item.item_code, item.name])
Nabin Hait344f4432014-05-08 19:08:20 +0530210
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530211 self.cleanup_raw_materials_supplied(parent_items, raw_material_table)
Nabin Hait54d209f2013-03-01 18:51:10 +0530212
Saurabhfbb342c2016-04-07 16:41:31 +0530213 elif self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Haitdd38a262014-12-26 13:15:21 +0530214 for item in self.get("items"):
Nabin Haita0c239d2014-04-01 18:54:38 +0530215 item.rm_supp_cost = 0.0
216
Rohit Waghchaure4b9d2f22017-02-16 15:53:40 +0530217 if self.is_subcontracted == "No" and self.get("supplied_items"):
218 self.set('supplied_items', [])
219
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530220 def update_raw_materials_supplied_based_on_stock_entries(self, raw_material_table):
221 self.set(raw_material_table, [])
222 purchase_orders = [d.purchase_order for d in self.items]
223 if purchase_orders:
224 items = get_subcontracted_raw_materials_from_se(purchase_orders)
225 backflushed_raw_materials = get_backflushed_subcontracted_raw_materials_from_se(purchase_orders, self.name)
226
227 for d in items:
228 qty = d.qty - backflushed_raw_materials.get(d.item_code, 0)
229 rm = self.append(raw_material_table, {})
230 rm.rm_item_code = d.item_code
231 rm.item_name = d.item_name
232 rm.main_item_code = d.main_item_code
233 rm.description = d.description
234 rm.stock_uom = d.stock_uom
235 rm.required_qty = qty
236 rm.consumed_qty = qty
237 rm.serial_no = d.serial_no
238 rm.batch_no = d.batch_no
239
240 # get raw materials rate
241 from erpnext.stock.utils import get_incoming_rate
242 rm.rate = get_incoming_rate({
243 "item_code": d.item_code,
244 "warehouse": self.supplier_warehouse,
245 "posting_date": self.posting_date,
246 "posting_time": self.posting_time,
247 "qty": -1 * qty,
248 "serial_no": rm.serial_no
249 })
250 if not rm.rate:
251 rm.rate = get_valuation_rate(d.item_code, self.supplier_warehouse,
252 self.doctype, self.name, currency=self.company_currency, company = self.company)
253
254 rm.amount = qty * flt(rm.rate)
255
256 def update_raw_materials_supplied_based_on_bom(self, item, raw_material_table):
rohitwaghchaurebbd9b712018-03-07 15:39:40 +0530257 exploded_item = 1
258 if hasattr(item, 'include_exploded_items'):
259 exploded_item = item.get('include_exploded_items')
260
261 bom_items = get_items_from_bom(item.item_code, item.bom, exploded_item)
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530262
263 used_alternative_items = []
264 if self.doctype == 'Purchase Receipt' and item.purchase_order:
265 used_alternative_items = get_used_alternative_items(purchase_order = item.purchase_order)
266
Nabin Hait54d209f2013-03-01 18:51:10 +0530267 raw_materials_cost = 0
pawan2ff844e2017-11-30 18:14:55 +0530268 items = list(set([d.item_code for d in bom_items]))
Manas Solanki087a2252018-05-04 16:02:38 +0530269 item_wh = frappe._dict(frappe.db.sql("""select i.item_code, id.default_warehouse
Nabin Hait5f861752018-05-23 19:37:06 +0530270 from `tabItem` i, `tabItem Default` id
271 where id.parent=i.name and id.company=%s and i.name in ({0})"""
Manas Solanki087a2252018-05-04 16:02:38 +0530272 .format(", ".join(["%s"] * len(items))), [self.company] + items))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530273
Nabin Hait344f4432014-05-08 19:08:20 +0530274 for bom_item in bom_items:
Nabin Hait07e53762018-01-05 18:19:59 +0530275 if self.doctype == "Purchase Order":
276 reserve_warehouse = bom_item.source_warehouse or item_wh.get(bom_item.item_code)
277 if frappe.db.get_value("Warehouse", reserve_warehouse, "company") != self.company:
278 reserve_warehouse = None
279
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530280 conversion_factor = item.conversion_factor
281 if (self.doctype == 'Purchase Receipt' and item.purchase_order and
282 bom_item.item_code in used_alternative_items):
283 alternative_item_data = used_alternative_items.get(bom_item.item_code)
284 bom_item.item_code = alternative_item_data.item_code
285 bom_item.item_name = alternative_item_data.item_name
286 bom_item.stock_uom = alternative_item_data.stock_uom
287 conversion_factor = alternative_item_data.conversion_factor
288 bom_item.description = alternative_item_data.description
289
Nabin Hait344f4432014-05-08 19:08:20 +0530290 # check if exists
291 exists = 0
292 for d in self.get(raw_material_table):
293 if d.main_item_code == item.item_code and d.rm_item_code == bom_item.item_code \
294 and d.reference_name == item.name:
295 rm, exists = d, 1
296 break
297
298 if not exists:
299 rm = self.append(raw_material_table, {})
300
Fahim Ali Zain TP277935b2018-02-12 11:59:07 +0530301 required_qty = flt(flt(bom_item.qty_consumed_per_unit) * (flt(item.qty) + getattr(item, 'rejected_qty', 0)) *
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530302 flt(conversion_factor), rm.precision("required_qty"))
Nabin Hait344f4432014-05-08 19:08:20 +0530303 rm.reference_name = item.name
304 rm.bom_detail_no = bom_item.name
305 rm.main_item_code = item.item_code
306 rm.rm_item_code = bom_item.item_code
307 rm.stock_uom = bom_item.stock_uom
308 rm.required_qty = required_qty
Nabin Hait07e53762018-01-05 18:19:59 +0530309 if self.doctype == "Purchase Order" and not rm.reserve_warehouse:
310 rm.reserve_warehouse = reserve_warehouse
Nabin Hait344f4432014-05-08 19:08:20 +0530311
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530312 rm.conversion_factor = conversion_factor
Nabin Hait344f4432014-05-08 19:08:20 +0530313
Saurabhfbb342c2016-04-07 16:41:31 +0530314 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Hait344f4432014-05-08 19:08:20 +0530315 rm.consumed_qty = required_qty
316 rm.description = bom_item.description
317 if item.batch_no and not rm.batch_no:
318 rm.batch_no = item.batch_no
319
Nabin Haite96e83d2014-10-08 18:06:14 +0530320 # get raw materials rate
Nabin Haitfce28812014-10-08 18:38:27 +0530321 if self.doctype == "Purchase Receipt":
322 from erpnext.stock.utils import get_incoming_rate
Nabin Haitfb6e4342014-10-15 11:34:40 +0530323 rm.rate = get_incoming_rate({
Nabin Haitfce28812014-10-08 18:38:27 +0530324 "item_code": bom_item.item_code,
325 "warehouse": self.supplier_warehouse,
326 "posting_date": self.posting_date,
327 "posting_time": self.posting_time,
328 "qty": -1 * required_qty,
329 "serial_no": rm.serial_no
330 })
Nabin Haitfb6e4342014-10-15 11:34:40 +0530331 if not rm.rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530332 rm.rate = get_valuation_rate(bom_item.item_code, self.supplier_warehouse,
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530333 self.doctype, self.name, currency=self.company_currency, company = self.company)
Nabin Haitfce28812014-10-08 18:38:27 +0530334 else:
335 rm.rate = bom_item.rate
Nabin Haite96e83d2014-10-08 18:06:14 +0530336
Nabin Haitfce28812014-10-08 18:38:27 +0530337 rm.amount = required_qty * flt(rm.rate)
Nabin Haite96e83d2014-10-08 18:06:14 +0530338 raw_materials_cost += flt(rm.amount)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530339
Nabin Hait14aa9c52016-04-18 15:54:01 +0530340 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Nabin Hait344f4432014-05-08 19:08:20 +0530341 item.rm_supp_cost = raw_materials_cost
342
343 def cleanup_raw_materials_supplied(self, parent_items, raw_material_table):
344 """Remove all those child items which are no longer present in main item table"""
345 delete_list = []
346 for d in self.get(raw_material_table):
347 if [d.main_item_code, d.reference_name] not in parent_items:
348 # mark for deletion from doclist
Nabin Haitc3d1d6a2014-06-04 16:41:22 +0530349 delete_list.append(d)
Nabin Hait344f4432014-05-08 19:08:20 +0530350
351 # delete from doclist
352 if delete_list:
353 rm_supplied_details = self.get(raw_material_table)
354 self.set(raw_material_table, [])
355 for d in rm_supplied_details:
356 if d not in delete_list:
357 self.append(raw_material_table, d)
Nabin Hait54d209f2013-03-01 18:51:10 +0530358
Nabin Hait5418d712013-02-27 18:11:17 +0530359 @property
360 def sub_contracted_items(self):
361 if not hasattr(self, "_sub_contracted_items"):
Nabin Haitebd51442013-04-23 15:36:26 +0530362 self._sub_contracted_items = []
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530363 item_codes = list(set(item.item_code for item in
Nabin Haitdd38a262014-12-26 13:15:21 +0530364 self.get("items")))
Nabin Haitebd51442013-04-23 15:36:26 +0530365 if item_codes:
Anand Doshie9baaa62014-02-26 12:35:33 +0530366 self._sub_contracted_items = [r[0] for r in frappe.db.sql("""select name
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530367 from `tabItem` where name in (%s) and is_sub_contracted_item=1""" % \
Nabin Haitebd51442013-04-23 15:36:26 +0530368 (", ".join((["%s"]*len(item_codes))),), item_codes)]
Nabin Hait5418d712013-02-27 18:11:17 +0530369
370 return self._sub_contracted_items
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530371
nabinhait614fb752014-07-14 10:47:50 +0530372 def set_qty_as_per_stock_uom(self):
Nabin Haitdd38a262014-12-26 13:15:21 +0530373 for d in self.get("items"):
Nabin Haitfd4bcd82015-05-22 16:55:40 +0530374 if d.meta.get_field("stock_qty"):
nabinhait614fb752014-07-14 10:47:50 +0530375 if not d.conversion_factor:
Nabin Haite6e456b2015-05-13 17:21:44 +0530376 frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
Rushabh Mehta5b51cc82014-07-21 18:25:45 +0530377 d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530378
Saurabh130c57b2016-04-04 15:49:36 +0530379 def validate_purchase_return(self):
380 for d in self.get("items"):
381 if self.is_return and flt(d.rejected_qty) != 0:
382 frappe.throw(_("Row #{0}: Rejected Qty can not be entered in Purchase Return").format(d.idx))
383
384 # validate rate with ref PR
385
386 def validate_rejected_warehouse(self):
387 for d in self.get("items"):
388 if flt(d.rejected_qty) and not d.rejected_warehouse:
Saurabhfbb342c2016-04-07 16:41:31 +0530389 if self.rejected_warehouse:
390 d.rejected_warehouse = self.rejected_warehouse
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530391
Saurabh130c57b2016-04-04 15:49:36 +0530392 if not d.rejected_warehouse:
393 frappe.throw(_("Row #{0}: Rejected Warehouse is mandatory against rejected Item {1}").format(d.idx, d.item_code))
394
395 # validate accepted and rejected qty
396 def validate_accepted_rejected_qty(self):
397 for d in self.get("items"):
Saurabh4f4d0a82017-03-13 14:31:48 +0530398 self.validate_negative_quantity(d, ["received_qty","qty", "rejected_qty"])
Saurabh130c57b2016-04-04 15:49:36 +0530399 if not flt(d.received_qty) and flt(d.qty):
400 d.received_qty = flt(d.qty) - flt(d.rejected_qty)
401
402 elif not flt(d.qty) and flt(d.rejected_qty):
403 d.qty = flt(d.received_qty) - flt(d.rejected_qty)
404
405 elif not flt(d.rejected_qty):
406 d.rejected_qty = flt(d.received_qty) - flt(d.qty)
407
408 # Check Received Qty = Accepted Qty + Rejected Qty
409 if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)):
410 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 +0530411
Saurabh4f4d0a82017-03-13 14:31:48 +0530412 def validate_negative_quantity(self, item_row, field_list):
413 if self.is_return:
414 return
415
416 item_row = item_row.as_dict()
417 for fieldname in field_list:
418 if flt(item_row[fieldname]) < 0:
419 frappe.throw(_("Row #{0}: {1} can not be negative for item {2}".format(item_row['idx'],
420 frappe.get_meta(item_row.doctype).get_label(fieldname), item_row['item_code'])))
421
Saurabhe29248b2016-04-04 11:55:52 +0530422 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait07e53762018-01-05 18:19:59 +0530423 self.update_ordered_and_reserved_qty()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530424
Saurabhe29248b2016-04-04 11:55:52 +0530425 sl_entries = []
426 stock_items = self.get_stock_items()
427
428 for d in self.get('items'):
429 if d.item_code in stock_items and d.warehouse:
430 pr_qty = flt(d.qty) * flt(d.conversion_factor)
431
432 if pr_qty:
Saurabhe29248b2016-04-04 11:55:52 +0530433 sle = self.get_sl_entries(d, {
434 "actual_qty": flt(pr_qty),
435 "serial_no": cstr(d.serial_no).strip()
436 })
437 if self.is_return:
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530438 original_incoming_rate = frappe.db.get_value("Stock Ledger Entry",
439 {"voucher_type": "Purchase Receipt", "voucher_no": self.return_against,
Nabin Haitb81ed452016-05-11 12:52:31 +0530440 "item_code": d.item_code}, "incoming_rate")
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530441
Saurabhe29248b2016-04-04 11:55:52 +0530442 sle.update({
Nabin Haitb81ed452016-05-11 12:52:31 +0530443 "outgoing_rate": original_incoming_rate
Saurabhe29248b2016-04-04 11:55:52 +0530444 })
445 else:
Nabin Haitb81ed452016-05-11 12:52:31 +0530446 val_rate_db_precision = 6 if cint(self.precision("valuation_rate", d)) <= 6 else 9
447 incoming_rate = flt(d.valuation_rate, val_rate_db_precision)
Saurabhe29248b2016-04-04 11:55:52 +0530448 sle.update({
Nabin Haitb81ed452016-05-11 12:52:31 +0530449 "incoming_rate": incoming_rate
Saurabhe29248b2016-04-04 11:55:52 +0530450 })
451 sl_entries.append(sle)
452
Rohit Waghchaure560ba392016-08-29 18:19:32 +0530453 if flt(d.rejected_qty) != 0:
Saurabhe29248b2016-04-04 11:55:52 +0530454 sl_entries.append(self.get_sl_entries(d, {
455 "warehouse": d.rejected_warehouse,
456 "actual_qty": flt(d.rejected_qty) * flt(d.conversion_factor),
457 "serial_no": cstr(d.rejected_serial_no).strip(),
458 "incoming_rate": 0.0
459 }))
460
461 self.make_sl_entries_for_supplier_warehouse(sl_entries)
462 self.make_sl_entries(sl_entries, allow_negative_stock=allow_negative_stock,
463 via_landed_cost_voucher=via_landed_cost_voucher)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530464
Nabin Hait07e53762018-01-05 18:19:59 +0530465 def update_ordered_and_reserved_qty(self):
Nabin Hait14aa9c52016-04-18 15:54:01 +0530466 po_map = {}
467 for d in self.get("items"):
468 if self.doctype=="Purchase Receipt" \
Rohit Waghchaurea71d9d32016-07-05 00:34:00 +0530469 and d.purchase_order:
470 po_map.setdefault(d.purchase_order, []).append(d.purchase_order_item)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530471
Nabin Hait14aa9c52016-04-18 15:54:01 +0530472 elif self.doctype=="Purchase Invoice" and d.purchase_order and d.po_detail:
473 po_map.setdefault(d.purchase_order, []).append(d.po_detail)
474
475 for po, po_item_rows in po_map.items():
476 if po and po_item_rows:
477 po_obj = frappe.get_doc("Purchase Order", po)
478
479 if po_obj.status in ["Closed", "Cancelled"]:
480 frappe.throw(_("{0} {1} is cancelled or closed").format(_("Purchase Order"), po),
481 frappe.InvalidStatusError)
482
483 po_obj.update_ordered_qty(po_item_rows)
Nabin Hait07e53762018-01-05 18:19:59 +0530484 if self.is_subcontracted:
485 po_obj.update_reserved_qty_for_subcontract()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530486
Saurabhe29248b2016-04-04 11:55:52 +0530487 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
488 if hasattr(self, 'supplied_items'):
489 for d in self.get('supplied_items'):
490 # negative quantity is passed, as raw material qty has to be decreased
491 # when PR is submitted and it has to be increased when PR is cancelled
492 sl_entries.append(self.get_sl_entries(d, {
493 "item_code": d.rm_item_code,
494 "warehouse": self.supplier_warehouse,
495 "actual_qty": -1*flt(d.consumed_qty),
496 }))
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530497
rohitwaghchaurefe226862017-12-28 16:11:27 +0530498 def on_submit(self):
499 if self.get('is_return'):
500 return
501
Rohit Waghchaureab842542018-04-26 19:18:29 +0530502 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530503 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
504
505 self.process_fixed_asset()
506 self.update_fixed_asset(field)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530507
rohitwaghchaurefe226862017-12-28 16:11:27 +0530508 update_last_purchase_rate(self, is_submit = 1)
509
510 def on_cancel(self):
511 if self.get('is_return'):
512 return
513
514 update_last_purchase_rate(self, is_submit = 0)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530515 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530516 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
517
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530518 self.delete_linked_asset()
519 self.update_fixed_asset(field, delete_asset=True)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530520
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530521 def validate_budget(self):
522 if self.docstatus == 1:
523 for data in self.get('items'):
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530524 args = data.as_dict()
525 args.update({
526 'doctype': self.doctype,
rohitwaghchaure34c18772018-06-25 10:31:08 +0530527 'company': self.company,
528 'posting_date': (self.schedule_date
529 if self.doctype == 'Material Request' else self.transaction_date)
rohitwaghchaure77a45b42018-06-15 18:03:31 +0530530 })
531
532 validate_expense_against_budget(args)
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530533
Rohit Waghchaureab842542018-04-26 19:18:29 +0530534 def process_fixed_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530535 if self.doctype == 'Purchase Invoice' and not self.update_stock:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530536 return
537
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530538 asset_items = self.get_asset_items()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530539 if asset_items:
540 self.make_serial_nos_for_asset(asset_items)
541
542 def make_serial_nos_for_asset(self, asset_items):
543 items_data = get_asset_item_details(asset_items)
544
545 for d in self.items:
546 if d.is_fixed_asset:
547 item_data = items_data.get(d.item_code)
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530548 if not d.asset:
549 asset = self.make_asset(d)
550 d.db_set('asset', asset)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530551
552 if item_data.get('has_serial_no'):
553 # If item has serial no
554 if item_data.get('serial_no_series') and not d.serial_no:
555 serial_nos = get_auto_serial_nos(item_data.get('serial_no_series'), d.qty)
556 elif d.serial_no:
557 serial_nos = d.serial_no
558 elif not d.serial_no:
559 frappe.throw(_("Serial no is mandatory for the item {0}").format(d.item_code))
560
561 auto_make_serial_nos({
562 'serial_no': serial_nos,
563 'item_code': d.item_code,
564 'via_stock_ledger': False,
565 'company': self.company,
566 'actual_qty': d.qty,
567 'purchase_document_type': self.doctype,
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530568 'purchase_document_no': self.name,
Rohit Waghchaure647d5952018-06-11 18:53:55 +0530569 'asset': d.asset,
570 'location': d.asset_location
Rohit Waghchaureab842542018-04-26 19:18:29 +0530571 })
572 d.db_set('serial_no', serial_nos)
573
Rohit Waghchaureab842542018-04-26 19:18:29 +0530574 if d.asset:
575 self.make_asset_movement(d)
576
577 def make_asset(self, row):
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530578 if not row.asset_location:
579 frappe.throw(_("Row {0}: Enter location for the asset item {1}").format(row.idx, row.item_code))
580
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530581 item_data = frappe.db.get_value('Item',
582 row.item_code, ['asset_naming_series', 'asset_category'], as_dict=1)
583
Rohit Waghchaure16bc8532018-05-12 12:06:00 +0530584 purchase_amount = flt(row.base_net_amount + row.item_tax_amount)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530585 asset = frappe.get_doc({
586 'doctype': 'Asset',
587 'item_code': row.item_code,
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530588 'asset_name': row.item_name,
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530589 'naming_series': item_data.get('asset_naming_series') or 'AST',
590 'asset_category': item_data.get('asset_category'),
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530591 'location': row.asset_location,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530592 'company': self.company,
593 'purchase_date': self.posting_date,
Rohit Waghchaure0ea6fe42018-05-08 23:31:58 +0530594 'calculate_depreciation': 1,
Rohit Waghchaure16bc8532018-05-12 12:06:00 +0530595 'purchase_receipt_amount': purchase_amount,
596 'gross_purchase_amount': purchase_amount,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530597 'purchase_receipt': self.name if self.doctype == 'Purchase Receipt' else None,
598 'purchase_invoice': self.name if self.doctype == 'Purchase Invoice' else None
599 })
600
601 asset.flags.ignore_validate = True
602 asset.flags.ignore_mandatory = True
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530603 asset.set_missing_values()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530604 asset.insert()
605
606 frappe.msgprint(_("Asset {0} created").format(asset.name))
607 return asset.name
608
609 def make_asset_movement(self, row):
610 asset_movement = frappe.get_doc({
611 'doctype': 'Asset Movement',
612 'asset': row.asset,
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530613 'target_location': row.asset_location,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530614 'purpose': 'Receipt',
615 'serial_no': row.serial_no,
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530616 'quantity': len(get_serial_nos(row.serial_no)),
Rohit Waghchaureab842542018-04-26 19:18:29 +0530617 'company': self.company,
618 'transaction_date': self.posting_date,
619 'reference_doctype': self.doctype,
620 'reference_name': self.name
621 }).insert()
622
623 return asset_movement.name
624
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530625 def update_fixed_asset(self, field, delete_asset = False):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530626 for d in self.get("items"):
627 if d.is_fixed_asset and d.asset:
628 asset = frappe.get_doc("Asset", d.asset)
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530629
630 if delete_asset and asset.docstatus == 0:
631 frappe.delete_doc("Asset", asset.name)
632 d.db_set('asset', None)
633 continue
634
Rohit Waghchaureab842542018-04-26 19:18:29 +0530635 if self.docstatus in [0, 1] and not asset.get(field):
636 asset.set(field, self.name)
637 asset.purchase_date = self.posting_date
638 asset.supplier = self.supplier
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530639 elif self.docstatus == 2:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530640 asset.set(field, None)
641 asset.supplier = None
642
643 asset.flags.ignore_validate_update_after_submit = True
Rohit Waghchaurea02640e2018-05-16 10:49:12 +0530644 asset.flags.ignore_mandatory = True
Rohit Waghchaureab842542018-04-26 19:18:29 +0530645 if asset.docstatus == 0:
646 asset.flags.ignore_validate = True
647
648 asset.save()
649
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530650 def delete_linked_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530651 if self.doctype == 'Purchase Invoice' and not self.get('update_stock'):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530652 return
653
Rohit Waghchaureab842542018-04-26 19:18:29 +0530654 frappe.db.sql("delete from `tabAsset Movement` where reference_name=%s and docstatus = 0", self.name)
655 frappe.db.sql("delete from `tabSerial No` where purchase_document_no=%s", self.name)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530656
Nabin Hait5a834202017-10-05 19:51:10 +0530657 def validate_schedule_date(self):
658 if not self.schedule_date:
659 self.schedule_date = min([d.schedule_date for d in self.get("items")])
660
661 if self.schedule_date:
662 for d in self.get('items'):
663 if not d.schedule_date:
664 d.schedule_date = self.schedule_date
665
Prateeksha Singhcbd06fd2018-01-05 21:28:01 +0530666 if (d.schedule_date and self.transaction_date and
667 getdate(d.schedule_date) < getdate(self.transaction_date)):
Nabin Hait96b264b2018-01-02 11:50:29 +0530668 frappe.throw(_("Row #{0}: Reqd by Date cannot be before Transaction Date").format(d.idx))
Nabin Hait5a834202017-10-05 19:51:10 +0530669 else:
Nabin Hait96b264b2018-01-02 11:50:29 +0530670 frappe.throw(_("Please enter Reqd by Date"))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530671
Zarrarfc03a042018-06-04 12:52:52 +0530672 def validate_items(self):
673 # validate items to see if they have is_purchase_item or is_subcontracted_item enabled
Nabin Hait0bef91c2018-06-18 16:33:48 +0530674 if self.doctype=="Material Request": return
Zarrarfc03a042018-06-04 12:52:52 +0530675
rohitwaghchaure50d8c4a2018-06-05 13:08:10 +0530676 if hasattr(self, "is_subcontracted") and self.is_subcontracted == 'Yes':
Zarrarfc03a042018-06-04 12:52:52 +0530677 validate_item_type(self, "is_sub_contracted_item", "subcontracted")
678 else:
679 validate_item_type(self, "is_purchase_item", "purchase")
680
rohitwaghchaurebbd9b712018-03-07 15:39:40 +0530681def get_items_from_bom(item_code, bom, exploded_item=1):
682 doctype = "BOM Item" if not exploded_item else "BOM Explosion Item"
683
684 bom_items = frappe.db.sql("""select t2.item_code, t2.name,
685 t2.rate, t2.stock_uom, t2.source_warehouse, t2.description,
686 t2.stock_qty / ifnull(t1.quantity, 1) as qty_consumed_per_unit
687 from
688 `tabBOM` t1, `tab{0}` t2, tabItem t3
689 where
690 t2.parent = t1.name and t1.item = %s
691 and t1.docstatus = 1 and t1.is_active = 1 and t1.name = %s
692 and t2.item_code = t3.name and t3.is_stock_item = 1""".format(doctype),
693 (item_code, bom), as_dict=1)
694
695 if not bom_items:
696 msgprint(_("Specified BOM {0} does not exist for Item {1}").format(bom, item_code), raise_exception=1)
697
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530698 return bom_items
Rohit Waghchaureab842542018-04-26 19:18:29 +0530699
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530700def get_subcontracted_raw_materials_from_se(purchase_orders):
701 return frappe.db.sql("""
702 select
703 sed.item_name, sed.item_code, sum(sed.qty) as qty, sed.description,
704 sed.stock_uom, sed.subcontracted_item as main_item_code, sed.serial_no, sed.batch_no
705 from `tabStock Entry` se,`tabStock Entry Detail` sed
706 where
707 se.name = sed.parent and se.docstatus=1 and se.purpose='Subcontract'
Rohit Waghchaureed71c362018-06-28 18:36:35 +0530708 and se.purchase_order in (%s) and ifnull(sed.t_warehouse, '') != ''
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530709 group by sed.item_code, sed.t_warehouse
710 """ % (','.join(['%s'] * len(purchase_orders))), tuple(purchase_orders), as_dict=1)
711
712def get_backflushed_subcontracted_raw_materials_from_se(purchase_orders, purchase_receipt):
713 return frappe._dict(frappe.db.sql("""
714 select
715 prsi.rm_item_code as item_code, sum(prsi.consumed_qty) as qty
716 from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pri, `tabPurchase Receipt Item Supplied` prsi
717 where
Rohit Waghchaureed71c362018-06-28 18:36:35 +0530718 pr.name = pri.parent and pr.name = prsi.parent and pri.purchase_order in (%s)
rohitwaghchaure01fe4a32018-07-01 16:41:39 +0530719 and pri.item_code = prsi.main_item_code and pr.name != '%s' and pr.docstatus = 1
rohitwaghchaure2da6b3d2018-06-05 13:06:52 +0530720 group by prsi.rm_item_code
721 """ % (','.join(['%s'] * len(purchase_orders)), purchase_receipt), tuple(purchase_orders)))
722
Rohit Waghchaureab842542018-04-26 19:18:29 +0530723def get_asset_item_details(asset_items):
724 asset_items_data = {}
725 for d in frappe.get_all('Item', fields = ["name", "has_serial_no", "serial_no_series"],
726 filters = {'name': ('in', asset_items)}):
727 asset_items_data.setdefault(d.name, d)
728
729 return asset_items_data
Ameya Shenoy873e28d2018-06-06 05:53:19 +0000730
Zarrarfc03a042018-06-04 12:52:52 +0530731def validate_item_type(doc, fieldname, message):
732 # iterate through items and check if they are valid sales or purchase items
Zarrar7c088ff2018-06-05 10:32:09 +0530733 items = [d.item_code for d in doc.items if d.item_code]
734
735 # No validation check inase of creating transaction using 'Opening Invoice Creation Tool'
736 if not items:
737 return
738
Zarrarfc03a042018-06-04 12:52:52 +0530739 item_list = ", ".join(["'%s'" % frappe.db.escape(d) for d in items])
740
741 invalid_items = [d[0] for d in frappe.db.sql("""
742 select item_code from tabItem where name in ({0}) and {1}=0
743 """.format(item_list, fieldname), as_list=True)]
744
745 if invalid_items:
Charles-Henri Decultot6d97ab62018-07-03 07:02:53 +0200746 frappe.throw(_("Following item {items} {verb} marked as {message} item.\
Zarrarfc03a042018-06-04 12:52:52 +0530747 You can enable them as {message} item from its Item master".format(
748 items = ", ".join([d for d in invalid_items]),
Charles-Henri Decultot6d97ab62018-07-03 07:02:53 +0200749 verb = _("are not") if len(invalid_items) > 1 else _("is not"),
Zarrarfc03a042018-06-04 12:52:52 +0530750 message = message)))