blob: 4099392243639dc5053e43875bc8fabe0206f004 [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
nabinhait614fb752014-07-14 10:47:50 +053041 self.set_qty_as_per_stock_uom()
Nabin Hait205f7ce2013-04-26 13:35:06 +053042 self.validate_stock_or_nonstock_items()
Anand Doshi373680b2013-10-10 16:04:40 +053043 self.validate_warehouse()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053044
Nabin Hait14aa9c52016-04-18 15:54:01 +053045 if self.doctype=="Purchase Invoice":
46 self.validate_purchase_receipt_if_update_stock()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053047
Nabin Hait14aa9c52016-04-18 15:54:01 +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
Saurabhfbb342c2016-04-07 16:41:31 +053054 #sub-contracting
55 self.validate_for_subcontracting()
56 self.create_raw_materials_supplied("supplied_items")
57 self.set_landed_cost_voucher_amount()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053058
Nabin Hait14aa9c52016-04-18 15:54:01 +053059 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Saurabhfbb342c2016-04-07 16:41:31 +053060 self.update_valuation_rate("items")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053061
Anand Doshi3543f302013-05-24 19:25:01 +053062 def set_missing_values(self, for_validate=False):
Anand Doshiabc10032013-06-14 17:44:03 +053063 super(BuyingController, self).set_missing_values(for_validate)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053064
Rushabh Mehta0b995402013-08-09 15:29:59 +053065 self.set_supplier_from_item_default()
Nabin Hait096d3632013-10-17 17:01:14 +053066 self.set_price_list_currency("Buying")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053067
Anand Doshi3543f302013-05-24 19:25:01 +053068 # set contact and address details for supplier, if they are not mentioned
Nabin Hait365ae272014-04-03 17:38:54 +053069 if getattr(self, "supplier", None):
Nabin Hait7eba1a32017-10-02 15:59:27 +053070 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 +053071
Nabin Haitcccc45e2016-10-05 17:15:43 +053072 self.set_missing_item_details(for_validate)
Rushabh Mehta436467a2013-07-08 12:37:59 +053073
Rushabh Mehta0b995402013-08-09 15:29:59 +053074 def set_supplier_from_item_default(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +053075 if self.meta.get_field("supplier") and not self.supplier:
Nabin Haitdd38a262014-12-26 13:15:21 +053076 for d in self.get("items"):
Nabin Hait33df0b42018-05-26 09:09:02 +053077 supplier = frappe.db.get_value("Item Default",
78 {"parent": d.item_code, "company": self.company}, "default_supplier")
Rushabh Mehta0b995402013-08-09 15:29:59 +053079 if supplier:
Anand Doshif78d1ae2014-03-28 13:55:00 +053080 self.supplier = supplier
Rushabh Mehta0b995402013-08-09 15:29:59 +053081 break
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053082
Nabin Hait205f7ce2013-04-26 13:35:06 +053083 def validate_stock_or_nonstock_items(self):
Rohit Waghchaureaf059952018-05-07 18:46:53 +053084 if self.meta.get_field("taxes") and not self.get_stock_items() and not self.get_asset_items():
tundebabzy9a346202017-06-16 11:00:14 +010085 tax_for_valuation = [d for d in self.get("taxes")
Nabin Hait205f7ce2013-04-26 13:35:06 +053086 if d.category in ["Valuation", "Valuation and Total"]]
tundebabzy9a346202017-06-16 11:00:14 +010087
Nabin Hait205f7ce2013-04-26 13:35:06 +053088 if tax_for_valuation:
tundebabzy9a346202017-06-16 11:00:14 +010089 for d in tax_for_valuation:
90 d.category = 'Total'
91 msgprint(_('Tax Category has been changed to "Total" because all the Items are non-stock items'))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053092
Rohit Waghchaureaf059952018-05-07 18:46:53 +053093 def get_asset_items(self):
Rohit Waghchaured644e6d2018-05-12 15:27:18 +053094 if self.doctype not in ['Purchase Invoice', 'Purchase Receipt']:
95 return []
96
Rohit Waghchaureaf059952018-05-07 18:46:53 +053097 return [d.item_code for d in self.items if d.is_fixed_asset]
98
Saurabhfbb342c2016-04-07 16:41:31 +053099 def set_landed_cost_voucher_amount(self):
100 for d in self.get("items"):
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530101 lc_voucher_data = frappe.db.sql("""select sum(applicable_charges), cost_center
Saurabhfbb342c2016-04-07 16:41:31 +0530102 from `tabLanded Cost Item`
103 where docstatus = 1 and purchase_receipt_item = %s""", d.name)
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530104 d.landed_cost_voucher_amount = lc_voucher_data[0][0] if lc_voucher_data else 0.0
105 if not d.cost_center and lc_voucher_data and lc_voucher_data[0][1]:
106 d.db_set('cost_center', lc_voucher_data[0][1])
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530107
Nabin Haitd3b62502013-01-21 17:24:31 +0530108 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530109 from frappe.utils import money_in_words
Nabin Hait5690be12015-02-12 16:09:11 +0530110 if self.meta.get_field("base_in_words"):
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530111 self.base_in_words = money_in_words(self.base_grand_total, self.company_currency)
Nabin Hait5b4c2942013-01-22 11:12:02 +0530112 if self.meta.get_field("in_words"):
Nabin Hait188f69a2015-02-12 17:55:50 +0530113 self.in_words = money_in_words(self.grand_total, self.currency)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530114
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530115 # update valuation rate
116 def update_valuation_rate(self, parentfield):
Anand Doshi8595fcf2013-02-08 19:28:14 +0530117 """
118 item_tax_amount is the total tax amount applied on that item
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530119 stored for valuation
120
Anand Doshi8595fcf2013-02-08 19:28:14 +0530121 TODO: rename item_tax_amount to valuation_tax_amount
122 """
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530123 stock_items = self.get_stock_items() + self.get_asset_items()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530124
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530125 stock_items_qty, stock_items_amount = 0, 0
126 last_stock_item_idx = 1
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530127 for d in self.get(parentfield):
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530128 if d.item_code and d.item_code in stock_items:
129 stock_items_qty += flt(d.qty)
Nabin Hait82e3e252015-02-23 16:58:30 +0530130 stock_items_amount += flt(d.base_net_amount)
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530131 last_stock_item_idx = d.idx
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530132
Nabin Hait82e3e252015-02-23 16:58:30 +0530133 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 +0530134 if d.category in ["Valuation", "Valuation and Total"]])
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530135
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530136 valuation_amount_adjustment = total_valuation_amount
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530137 for i, item in enumerate(self.get(parentfield)):
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530138 if item.item_code and item.qty and item.item_code in stock_items:
Nabin Hait82e3e252015-02-23 16:58:30 +0530139 item_proportion = flt(item.base_net_amount) / stock_items_amount if stock_items_amount \
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530140 else flt(item.qty) / stock_items_qty
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530141 if i == (last_stock_item_idx - 1):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530142 item.item_tax_amount = flt(valuation_amount_adjustment,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530143 self.precision("item_tax_amount", item))
144 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530145 item.item_tax_amount = flt(item_proportion * total_valuation_amount,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530146 self.precision("item_tax_amount", item))
147 valuation_amount_adjustment -= item.item_tax_amount
148
Anand Doshi39384d32013-05-11 19:39:53 +0530149 self.round_floats_in(item)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530150 if flt(item.conversion_factor)==0.0:
bobzz-zoneb4c7bad2015-08-05 11:30:12 +0700151 item.conversion_factor = get_conversion_factor(item.item_code, item.uom).get("conversion_factor") or 1.0
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530152
Rushabh Mehta54047782013-12-26 11:07:46 +0530153 qty_in_stock_uom = flt(item.qty * item.conversion_factor)
Saurabhfbb342c2016-04-07 16:41:31 +0530154 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 +0530155
nabinhait87f24012014-07-16 19:48:29 +0530156 landed_cost_voucher_amount = flt(item.landed_cost_voucher_amount) \
Saurabhfbb342c2016-04-07 16:41:31 +0530157 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] else 0.0
Nabin Hait14b8af22014-08-28 12:42:28 +0530158
Nabin Hait82e3e252015-02-23 16:58:30 +0530159 item.valuation_rate = ((item.base_net_amount + item.item_tax_amount + rm_supp_cost
nabinhait87f24012014-07-16 19:48:29 +0530160 + landed_cost_voucher_amount) / qty_in_stock_uom)
Anand Doshi4a7248e2013-02-27 18:10:30 +0530161 else:
Anand Doshi5af812a2013-05-10 19:23:02 +0530162 item.valuation_rate = 0.0
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530163
Nabin Hait54d209f2013-03-01 18:51:10 +0530164 def validate_for_subcontracting(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530165 if not self.is_subcontracted and self.sub_contracted_items:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530166 frappe.throw(_("Please enter 'Is Subcontracted' as Yes or No"))
167
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530168 if self.is_subcontracted == "Yes":
Saurabhfbb342c2016-04-07 16:41:31 +0530169 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] and not self.supplier_warehouse:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530170 frappe.throw(_("Supplier Warehouse mandatory for sub-contracted Purchase Receipt"))
171
Nabin Haitdd38a262014-12-26 13:15:21 +0530172 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530173 if item in self.sub_contracted_items and not item.bom:
174 frappe.throw(_("Please select BOM in BOM field for Item {0}").format(item.item_code))
175
Nabin Hait07e53762018-01-05 18:19:59 +0530176 if self.doctype == "Purchase Order":
177 for supplied_item in self.get("supplied_items"):
178 if not supplied_item.reserve_warehouse:
179 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 +0530180
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530181 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530182 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530183 if item.bom:
184 item.bom = None
185
Nabin Hait344f4432014-05-08 19:08:20 +0530186 def create_raw_materials_supplied(self, raw_material_table):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530187 if self.is_subcontracted=="Yes":
Nabin Hait344f4432014-05-08 19:08:20 +0530188 parent_items = []
Nabin Haitdd38a262014-12-26 13:15:21 +0530189 for item in self.get("items"):
Saurabhfbb342c2016-04-07 16:41:31 +0530190 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Haita0c239d2014-04-01 18:54:38 +0530191 item.rm_supp_cost = 0.0
rohitwaghchaure4dc5f0e2017-11-22 15:21:47 +0530192 if item.bom and item.item_code in self.sub_contracted_items:
Rushabh Mehtae693f792015-03-03 15:50:03 +0530193 self.update_raw_materials_supplied(item, raw_material_table)
Nabin Hait344f4432014-05-08 19:08:20 +0530194
195 if [item.item_code, item.name] not in parent_items:
196 parent_items.append([item.item_code, item.name])
197
198 self.cleanup_raw_materials_supplied(parent_items, raw_material_table)
Nabin Hait54d209f2013-03-01 18:51:10 +0530199
Saurabhfbb342c2016-04-07 16:41:31 +0530200 elif self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Haitdd38a262014-12-26 13:15:21 +0530201 for item in self.get("items"):
Nabin Haita0c239d2014-04-01 18:54:38 +0530202 item.rm_supp_cost = 0.0
203
Rohit Waghchaure4b9d2f22017-02-16 15:53:40 +0530204 if self.is_subcontracted == "No" and self.get("supplied_items"):
205 self.set('supplied_items', [])
206
Rushabh Mehtae693f792015-03-03 15:50:03 +0530207 def update_raw_materials_supplied(self, item, raw_material_table):
rohitwaghchaurebbd9b712018-03-07 15:39:40 +0530208 exploded_item = 1
209 if hasattr(item, 'include_exploded_items'):
210 exploded_item = item.get('include_exploded_items')
211
212 bom_items = get_items_from_bom(item.item_code, item.bom, exploded_item)
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530213
214 used_alternative_items = []
215 if self.doctype == 'Purchase Receipt' and item.purchase_order:
216 used_alternative_items = get_used_alternative_items(purchase_order = item.purchase_order)
217
Nabin Hait54d209f2013-03-01 18:51:10 +0530218 raw_materials_cost = 0
pawan2ff844e2017-11-30 18:14:55 +0530219 items = list(set([d.item_code for d in bom_items]))
Manas Solanki087a2252018-05-04 16:02:38 +0530220 item_wh = frappe._dict(frappe.db.sql("""select i.item_code, id.default_warehouse
Nabin Hait5f861752018-05-23 19:37:06 +0530221 from `tabItem` i, `tabItem Default` id
222 where id.parent=i.name and id.company=%s and i.name in ({0})"""
Manas Solanki087a2252018-05-04 16:02:38 +0530223 .format(", ".join(["%s"] * len(items))), [self.company] + items))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530224
Nabin Hait344f4432014-05-08 19:08:20 +0530225 for bom_item in bom_items:
Nabin Hait07e53762018-01-05 18:19:59 +0530226 if self.doctype == "Purchase Order":
227 reserve_warehouse = bom_item.source_warehouse or item_wh.get(bom_item.item_code)
228 if frappe.db.get_value("Warehouse", reserve_warehouse, "company") != self.company:
229 reserve_warehouse = None
230
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530231 conversion_factor = item.conversion_factor
232 if (self.doctype == 'Purchase Receipt' and item.purchase_order and
233 bom_item.item_code in used_alternative_items):
234 alternative_item_data = used_alternative_items.get(bom_item.item_code)
235 bom_item.item_code = alternative_item_data.item_code
236 bom_item.item_name = alternative_item_data.item_name
237 bom_item.stock_uom = alternative_item_data.stock_uom
238 conversion_factor = alternative_item_data.conversion_factor
239 bom_item.description = alternative_item_data.description
240
Nabin Hait344f4432014-05-08 19:08:20 +0530241 # check if exists
242 exists = 0
243 for d in self.get(raw_material_table):
244 if d.main_item_code == item.item_code and d.rm_item_code == bom_item.item_code \
245 and d.reference_name == item.name:
246 rm, exists = d, 1
247 break
248
249 if not exists:
250 rm = self.append(raw_material_table, {})
251
Fahim Ali Zain TP277935b2018-02-12 11:59:07 +0530252 required_qty = flt(flt(bom_item.qty_consumed_per_unit) * (flt(item.qty) + getattr(item, 'rejected_qty', 0)) *
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530253 flt(conversion_factor), rm.precision("required_qty"))
Nabin Hait344f4432014-05-08 19:08:20 +0530254 rm.reference_name = item.name
255 rm.bom_detail_no = bom_item.name
256 rm.main_item_code = item.item_code
257 rm.rm_item_code = bom_item.item_code
258 rm.stock_uom = bom_item.stock_uom
259 rm.required_qty = required_qty
Nabin Hait07e53762018-01-05 18:19:59 +0530260 if self.doctype == "Purchase Order" and not rm.reserve_warehouse:
261 rm.reserve_warehouse = reserve_warehouse
Nabin Hait344f4432014-05-08 19:08:20 +0530262
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530263 rm.conversion_factor = conversion_factor
Nabin Hait344f4432014-05-08 19:08:20 +0530264
Saurabhfbb342c2016-04-07 16:41:31 +0530265 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Hait344f4432014-05-08 19:08:20 +0530266 rm.consumed_qty = required_qty
267 rm.description = bom_item.description
268 if item.batch_no and not rm.batch_no:
269 rm.batch_no = item.batch_no
270
Nabin Haite96e83d2014-10-08 18:06:14 +0530271 # get raw materials rate
Nabin Haitfce28812014-10-08 18:38:27 +0530272 if self.doctype == "Purchase Receipt":
273 from erpnext.stock.utils import get_incoming_rate
Nabin Haitfb6e4342014-10-15 11:34:40 +0530274 rm.rate = get_incoming_rate({
Nabin Haitfce28812014-10-08 18:38:27 +0530275 "item_code": bom_item.item_code,
276 "warehouse": self.supplier_warehouse,
277 "posting_date": self.posting_date,
278 "posting_time": self.posting_time,
279 "qty": -1 * required_qty,
280 "serial_no": rm.serial_no
281 })
Nabin Haitfb6e4342014-10-15 11:34:40 +0530282 if not rm.rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530283 rm.rate = get_valuation_rate(bom_item.item_code, self.supplier_warehouse,
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530284 self.doctype, self.name, currency=self.company_currency, company = self.company)
Nabin Haitfce28812014-10-08 18:38:27 +0530285 else:
286 rm.rate = bom_item.rate
Nabin Haite96e83d2014-10-08 18:06:14 +0530287
Nabin Haitfce28812014-10-08 18:38:27 +0530288 rm.amount = required_qty * flt(rm.rate)
Nabin Haite96e83d2014-10-08 18:06:14 +0530289 raw_materials_cost += flt(rm.amount)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530290
Nabin Hait14aa9c52016-04-18 15:54:01 +0530291 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Nabin Hait344f4432014-05-08 19:08:20 +0530292 item.rm_supp_cost = raw_materials_cost
293
294 def cleanup_raw_materials_supplied(self, parent_items, raw_material_table):
295 """Remove all those child items which are no longer present in main item table"""
296 delete_list = []
297 for d in self.get(raw_material_table):
298 if [d.main_item_code, d.reference_name] not in parent_items:
299 # mark for deletion from doclist
Nabin Haitc3d1d6a2014-06-04 16:41:22 +0530300 delete_list.append(d)
Nabin Hait344f4432014-05-08 19:08:20 +0530301
302 # delete from doclist
303 if delete_list:
304 rm_supplied_details = self.get(raw_material_table)
305 self.set(raw_material_table, [])
306 for d in rm_supplied_details:
307 if d not in delete_list:
308 self.append(raw_material_table, d)
Nabin Hait54d209f2013-03-01 18:51:10 +0530309
Nabin Hait5418d712013-02-27 18:11:17 +0530310 @property
311 def sub_contracted_items(self):
312 if not hasattr(self, "_sub_contracted_items"):
Nabin Haitebd51442013-04-23 15:36:26 +0530313 self._sub_contracted_items = []
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530314 item_codes = list(set(item.item_code for item in
Nabin Haitdd38a262014-12-26 13:15:21 +0530315 self.get("items")))
Nabin Haitebd51442013-04-23 15:36:26 +0530316 if item_codes:
Anand Doshie9baaa62014-02-26 12:35:33 +0530317 self._sub_contracted_items = [r[0] for r in frappe.db.sql("""select name
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530318 from `tabItem` where name in (%s) and is_sub_contracted_item=1""" % \
Nabin Haitebd51442013-04-23 15:36:26 +0530319 (", ".join((["%s"]*len(item_codes))),), item_codes)]
Nabin Hait5418d712013-02-27 18:11:17 +0530320
321 return self._sub_contracted_items
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530322
nabinhait614fb752014-07-14 10:47:50 +0530323 def set_qty_as_per_stock_uom(self):
Nabin Haitdd38a262014-12-26 13:15:21 +0530324 for d in self.get("items"):
Nabin Haitfd4bcd82015-05-22 16:55:40 +0530325 if d.meta.get_field("stock_qty"):
nabinhait614fb752014-07-14 10:47:50 +0530326 if not d.conversion_factor:
Nabin Haite6e456b2015-05-13 17:21:44 +0530327 frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
Rushabh Mehta5b51cc82014-07-21 18:25:45 +0530328 d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530329
Saurabh130c57b2016-04-04 15:49:36 +0530330 def validate_purchase_return(self):
331 for d in self.get("items"):
332 if self.is_return and flt(d.rejected_qty) != 0:
333 frappe.throw(_("Row #{0}: Rejected Qty can not be entered in Purchase Return").format(d.idx))
334
335 # validate rate with ref PR
336
337 def validate_rejected_warehouse(self):
338 for d in self.get("items"):
339 if flt(d.rejected_qty) and not d.rejected_warehouse:
Saurabhfbb342c2016-04-07 16:41:31 +0530340 if self.rejected_warehouse:
341 d.rejected_warehouse = self.rejected_warehouse
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530342
Saurabh130c57b2016-04-04 15:49:36 +0530343 if not d.rejected_warehouse:
344 frappe.throw(_("Row #{0}: Rejected Warehouse is mandatory against rejected Item {1}").format(d.idx, d.item_code))
345
346 # validate accepted and rejected qty
347 def validate_accepted_rejected_qty(self):
348 for d in self.get("items"):
Saurabh4f4d0a82017-03-13 14:31:48 +0530349 self.validate_negative_quantity(d, ["received_qty","qty", "rejected_qty"])
Saurabh130c57b2016-04-04 15:49:36 +0530350 if not flt(d.received_qty) and flt(d.qty):
351 d.received_qty = flt(d.qty) - flt(d.rejected_qty)
352
353 elif not flt(d.qty) and flt(d.rejected_qty):
354 d.qty = flt(d.received_qty) - flt(d.rejected_qty)
355
356 elif not flt(d.rejected_qty):
357 d.rejected_qty = flt(d.received_qty) - flt(d.qty)
358
359 # Check Received Qty = Accepted Qty + Rejected Qty
360 if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)):
361 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 +0530362
Saurabh4f4d0a82017-03-13 14:31:48 +0530363 def validate_negative_quantity(self, item_row, field_list):
364 if self.is_return:
365 return
366
367 item_row = item_row.as_dict()
368 for fieldname in field_list:
369 if flt(item_row[fieldname]) < 0:
370 frappe.throw(_("Row #{0}: {1} can not be negative for item {2}".format(item_row['idx'],
371 frappe.get_meta(item_row.doctype).get_label(fieldname), item_row['item_code'])))
372
Saurabhe29248b2016-04-04 11:55:52 +0530373 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait07e53762018-01-05 18:19:59 +0530374 self.update_ordered_and_reserved_qty()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530375
Saurabhe29248b2016-04-04 11:55:52 +0530376 sl_entries = []
377 stock_items = self.get_stock_items()
378
379 for d in self.get('items'):
380 if d.item_code in stock_items and d.warehouse:
381 pr_qty = flt(d.qty) * flt(d.conversion_factor)
382
383 if pr_qty:
Saurabhe29248b2016-04-04 11:55:52 +0530384 sle = self.get_sl_entries(d, {
385 "actual_qty": flt(pr_qty),
386 "serial_no": cstr(d.serial_no).strip()
387 })
388 if self.is_return:
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530389 original_incoming_rate = frappe.db.get_value("Stock Ledger Entry",
390 {"voucher_type": "Purchase Receipt", "voucher_no": self.return_against,
Nabin Haitb81ed452016-05-11 12:52:31 +0530391 "item_code": d.item_code}, "incoming_rate")
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530392
Saurabhe29248b2016-04-04 11:55:52 +0530393 sle.update({
Nabin Haitb81ed452016-05-11 12:52:31 +0530394 "outgoing_rate": original_incoming_rate
Saurabhe29248b2016-04-04 11:55:52 +0530395 })
396 else:
Nabin Haitb81ed452016-05-11 12:52:31 +0530397 val_rate_db_precision = 6 if cint(self.precision("valuation_rate", d)) <= 6 else 9
398 incoming_rate = flt(d.valuation_rate, val_rate_db_precision)
Saurabhe29248b2016-04-04 11:55:52 +0530399 sle.update({
Nabin Haitb81ed452016-05-11 12:52:31 +0530400 "incoming_rate": incoming_rate
Saurabhe29248b2016-04-04 11:55:52 +0530401 })
402 sl_entries.append(sle)
403
Rohit Waghchaure560ba392016-08-29 18:19:32 +0530404 if flt(d.rejected_qty) != 0:
Saurabhe29248b2016-04-04 11:55:52 +0530405 sl_entries.append(self.get_sl_entries(d, {
406 "warehouse": d.rejected_warehouse,
407 "actual_qty": flt(d.rejected_qty) * flt(d.conversion_factor),
408 "serial_no": cstr(d.rejected_serial_no).strip(),
409 "incoming_rate": 0.0
410 }))
411
412 self.make_sl_entries_for_supplier_warehouse(sl_entries)
413 self.make_sl_entries(sl_entries, allow_negative_stock=allow_negative_stock,
414 via_landed_cost_voucher=via_landed_cost_voucher)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530415
Nabin Hait07e53762018-01-05 18:19:59 +0530416 def update_ordered_and_reserved_qty(self):
Nabin Hait14aa9c52016-04-18 15:54:01 +0530417 po_map = {}
418 for d in self.get("items"):
419 if self.doctype=="Purchase Receipt" \
Rohit Waghchaurea71d9d32016-07-05 00:34:00 +0530420 and d.purchase_order:
421 po_map.setdefault(d.purchase_order, []).append(d.purchase_order_item)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530422
Nabin Hait14aa9c52016-04-18 15:54:01 +0530423 elif self.doctype=="Purchase Invoice" and d.purchase_order and d.po_detail:
424 po_map.setdefault(d.purchase_order, []).append(d.po_detail)
425
426 for po, po_item_rows in po_map.items():
427 if po and po_item_rows:
428 po_obj = frappe.get_doc("Purchase Order", po)
429
430 if po_obj.status in ["Closed", "Cancelled"]:
431 frappe.throw(_("{0} {1} is cancelled or closed").format(_("Purchase Order"), po),
432 frappe.InvalidStatusError)
433
434 po_obj.update_ordered_qty(po_item_rows)
Nabin Hait07e53762018-01-05 18:19:59 +0530435 if self.is_subcontracted:
436 po_obj.update_reserved_qty_for_subcontract()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530437
Saurabhe29248b2016-04-04 11:55:52 +0530438 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
439 if hasattr(self, 'supplied_items'):
440 for d in self.get('supplied_items'):
441 # negative quantity is passed, as raw material qty has to be decreased
442 # when PR is submitted and it has to be increased when PR is cancelled
443 sl_entries.append(self.get_sl_entries(d, {
444 "item_code": d.rm_item_code,
445 "warehouse": self.supplier_warehouse,
446 "actual_qty": -1*flt(d.consumed_qty),
447 }))
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530448
rohitwaghchaurefe226862017-12-28 16:11:27 +0530449 def on_submit(self):
450 if self.get('is_return'):
451 return
452
Rohit Waghchaureab842542018-04-26 19:18:29 +0530453 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530454 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
455
456 self.process_fixed_asset()
457 self.update_fixed_asset(field)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530458
rohitwaghchaurefe226862017-12-28 16:11:27 +0530459 update_last_purchase_rate(self, is_submit = 1)
460
461 def on_cancel(self):
462 if self.get('is_return'):
463 return
464
465 update_last_purchase_rate(self, is_submit = 0)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530466 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530467 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
468
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530469 self.delete_linked_asset()
470 self.update_fixed_asset(field, delete_asset=True)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530471
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530472 def validate_budget(self):
473 if self.docstatus == 1:
474 for data in self.get('items'):
475 validate_expense_against_budget({
476 'item_code': data.item_code,
477 'item_group': data.item_group,
478 'posting_date': data.schedule_date,
Rohit Waghchaure144e9b12018-05-16 12:15:57 +0530479 'project': data.project,
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530480 'doctype': self.doctype
481 }, self.company)
482
Rohit Waghchaureab842542018-04-26 19:18:29 +0530483 def process_fixed_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530484 if self.doctype == 'Purchase Invoice' and not self.update_stock:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530485 return
486
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530487 asset_items = self.get_asset_items()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530488 if asset_items:
489 self.make_serial_nos_for_asset(asset_items)
490
491 def make_serial_nos_for_asset(self, asset_items):
492 items_data = get_asset_item_details(asset_items)
493
494 for d in self.items:
495 if d.is_fixed_asset:
496 item_data = items_data.get(d.item_code)
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530497 if not d.asset:
498 asset = self.make_asset(d)
499 d.db_set('asset', asset)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530500
501 if item_data.get('has_serial_no'):
502 # If item has serial no
503 if item_data.get('serial_no_series') and not d.serial_no:
504 serial_nos = get_auto_serial_nos(item_data.get('serial_no_series'), d.qty)
505 elif d.serial_no:
506 serial_nos = d.serial_no
507 elif not d.serial_no:
508 frappe.throw(_("Serial no is mandatory for the item {0}").format(d.item_code))
509
510 auto_make_serial_nos({
511 'serial_no': serial_nos,
512 'item_code': d.item_code,
513 'via_stock_ledger': False,
514 'company': self.company,
515 'actual_qty': d.qty,
516 'purchase_document_type': self.doctype,
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530517 'purchase_document_no': self.name,
518 'asset': d.asset
Rohit Waghchaureab842542018-04-26 19:18:29 +0530519 })
520 d.db_set('serial_no', serial_nos)
521
Rohit Waghchaureab842542018-04-26 19:18:29 +0530522 if d.asset:
523 self.make_asset_movement(d)
524
525 def make_asset(self, row):
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530526 if not row.asset_location:
527 frappe.throw(_("Row {0}: Enter location for the asset item {1}").format(row.idx, row.item_code))
528
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530529 item_data = frappe.db.get_value('Item',
530 row.item_code, ['asset_naming_series', 'asset_category'], as_dict=1)
531
Rohit Waghchaure16bc8532018-05-12 12:06:00 +0530532 purchase_amount = flt(row.base_net_amount + row.item_tax_amount)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530533 asset = frappe.get_doc({
534 'doctype': 'Asset',
535 'item_code': row.item_code,
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530536 'asset_name': row.item_name,
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530537 'status': 'Receipt',
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530538 'naming_series': item_data.get('asset_naming_series') or 'AST',
539 'asset_category': item_data.get('asset_category'),
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530540 'location': row.asset_location,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530541 'company': self.company,
542 'purchase_date': self.posting_date,
Rohit Waghchaure0ea6fe42018-05-08 23:31:58 +0530543 'calculate_depreciation': 1,
Rohit Waghchaure16bc8532018-05-12 12:06:00 +0530544 'purchase_receipt_amount': purchase_amount,
545 'gross_purchase_amount': purchase_amount,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530546 'purchase_receipt': self.name if self.doctype == 'Purchase Receipt' else None,
547 'purchase_invoice': self.name if self.doctype == 'Purchase Invoice' else None
548 })
549
550 asset.flags.ignore_validate = True
551 asset.flags.ignore_mandatory = True
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530552 asset.set_missing_values()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530553 asset.insert()
554
555 frappe.msgprint(_("Asset {0} created").format(asset.name))
556 return asset.name
557
558 def make_asset_movement(self, row):
559 asset_movement = frappe.get_doc({
560 'doctype': 'Asset Movement',
561 'asset': row.asset,
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530562 'target_location': row.asset_location,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530563 'purpose': 'Receipt',
564 'serial_no': row.serial_no,
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530565 'quantity': len(get_serial_nos(row.serial_no)),
Rohit Waghchaureab842542018-04-26 19:18:29 +0530566 'company': self.company,
567 'transaction_date': self.posting_date,
568 'reference_doctype': self.doctype,
569 'reference_name': self.name
570 }).insert()
571
572 return asset_movement.name
573
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530574 def update_fixed_asset(self, field, delete_asset = False):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530575 for d in self.get("items"):
576 if d.is_fixed_asset and d.asset:
577 asset = frappe.get_doc("Asset", d.asset)
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530578
579 if delete_asset and asset.docstatus == 0:
580 frappe.delete_doc("Asset", asset.name)
581 d.db_set('asset', None)
582 continue
583
Rohit Waghchaureab842542018-04-26 19:18:29 +0530584 if self.docstatus in [0, 1] and not asset.get(field):
585 asset.set(field, self.name)
586 asset.purchase_date = self.posting_date
587 asset.supplier = self.supplier
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530588 elif self.docstatus == 2:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530589 asset.set(field, None)
590 asset.supplier = None
591
592 asset.flags.ignore_validate_update_after_submit = True
Rohit Waghchaurea02640e2018-05-16 10:49:12 +0530593 asset.flags.ignore_mandatory = True
Rohit Waghchaureab842542018-04-26 19:18:29 +0530594 if asset.docstatus == 0:
595 asset.flags.ignore_validate = True
596
597 asset.save()
598
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530599 def delete_linked_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530600 if self.doctype == 'Purchase Invoice' and not self.get('update_stock'):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530601 return
602
Rohit Waghchaureab842542018-04-26 19:18:29 +0530603 frappe.db.sql("delete from `tabAsset Movement` where reference_name=%s and docstatus = 0", self.name)
604 frappe.db.sql("delete from `tabSerial No` where purchase_document_no=%s", self.name)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530605
Nabin Hait5a834202017-10-05 19:51:10 +0530606 def validate_schedule_date(self):
607 if not self.schedule_date:
608 self.schedule_date = min([d.schedule_date for d in self.get("items")])
609
610 if self.schedule_date:
611 for d in self.get('items'):
612 if not d.schedule_date:
613 d.schedule_date = self.schedule_date
614
Prateeksha Singhcbd06fd2018-01-05 21:28:01 +0530615 if (d.schedule_date and self.transaction_date and
616 getdate(d.schedule_date) < getdate(self.transaction_date)):
Nabin Hait96b264b2018-01-02 11:50:29 +0530617 frappe.throw(_("Row #{0}: Reqd by Date cannot be before Transaction Date").format(d.idx))
Nabin Hait5a834202017-10-05 19:51:10 +0530618 else:
Nabin Hait96b264b2018-01-02 11:50:29 +0530619 frappe.throw(_("Please enter Reqd by Date"))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530620
rohitwaghchaurebbd9b712018-03-07 15:39:40 +0530621def get_items_from_bom(item_code, bom, exploded_item=1):
622 doctype = "BOM Item" if not exploded_item else "BOM Explosion Item"
623
624 bom_items = frappe.db.sql("""select t2.item_code, t2.name,
625 t2.rate, t2.stock_uom, t2.source_warehouse, t2.description,
626 t2.stock_qty / ifnull(t1.quantity, 1) as qty_consumed_per_unit
627 from
628 `tabBOM` t1, `tab{0}` t2, tabItem t3
629 where
630 t2.parent = t1.name and t1.item = %s
631 and t1.docstatus = 1 and t1.is_active = 1 and t1.name = %s
632 and t2.item_code = t3.name and t3.is_stock_item = 1""".format(doctype),
633 (item_code, bom), as_dict=1)
634
635 if not bom_items:
636 msgprint(_("Specified BOM {0} does not exist for Item {1}").format(bom, item_code), raise_exception=1)
637
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530638 return bom_items
Rohit Waghchaureab842542018-04-26 19:18:29 +0530639
640def get_asset_item_details(asset_items):
641 asset_items_data = {}
642 for d in frappe.get_all('Item', fields = ["name", "has_serial_no", "serial_no_series"],
643 filters = {'name': ('in', asset_items)}):
644 asset_items_data.setdefault(d.name, d)
645
646 return asset_items_data