blob: 85fb3f0a66ed643054ebfff7151ea62a1aa1e500 [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
Rushabh Mehta1f847992013-12-12 19:12:19 +053016from erpnext.controllers.stock_controller import StockController
Nabin Haitbf495c92013-01-30 12:49:08 +053017
Nabin Hait89a94d82013-03-19 12:01:46 +053018class BuyingController(StockController):
Rushabh Mehta5b51cc82014-07-21 18:25:45 +053019 def __setup__(self):
Nabin Haitde9c8a92015-02-23 01:06:00 +053020 if hasattr(self, "taxes"):
Nabin Hait45dce892017-09-14 15:17:38 +053021 self.flags.print_taxes_with_zero_amount = cint(frappe.db.get_single_value("Print Settings",
22 "print_taxes_with_zero_amount"))
rohitwaghchaurebf4c1142018-01-08 15:20:15 +053023 self.flags.show_inclusive_tax_in_print = self.is_inclusive_tax()
24
Rushabh Mehtac567e8e2015-02-03 17:55:52 +053025 self.print_templates = {
rohitwaghchaurebf4c1142018-01-08 15:20:15 +053026 "total": "templates/print_formats/includes/total.html",
Rushabh Mehtac567e8e2015-02-03 17:55:52 +053027 "taxes": "templates/print_formats/includes/taxes.html"
Rushabh Mehta5b51cc82014-07-21 18:25:45 +053028 }
29
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053030 def get_feed(self):
rohitwaghchaurea1064a62016-03-03 14:00:35 +053031 if self.get("supplier_name"):
32 return _("From {0} | {1} {2}").format(self.supplier_name, self.currency,
33 self.grand_total)
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053034
Saurabh6f753182013-03-20 12:55:28 +053035 def validate(self):
36 super(BuyingController, self).validate()
Nabin Hait365ae272014-04-03 17:38:54 +053037 if getattr(self, "supplier", None) and not self.supplier_name:
Nabin Hait1d218422015-07-17 15:19:02 +053038 self.supplier_name = frappe.db.get_value("Supplier", self.supplier, "supplier_name")
Rushabh Mehtaea0ff232016-07-07 14:02:26 +053039
nabinhait614fb752014-07-14 10:47:50 +053040 self.set_qty_as_per_stock_uom()
Nabin Hait205f7ce2013-04-26 13:35:06 +053041 self.validate_stock_or_nonstock_items()
Anand Doshi373680b2013-10-10 16:04:40 +053042 self.validate_warehouse()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053043
Nabin Hait14aa9c52016-04-18 15:54:01 +053044 if self.doctype=="Purchase Invoice":
45 self.validate_purchase_receipt_if_update_stock()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053046
Nabin Hait14aa9c52016-04-18 15:54:01 +053047 if self.doctype=="Purchase Receipt" or (self.doctype=="Purchase Invoice" and self.update_stock):
Rohit Waghchaure560ba392016-08-29 18:19:32 +053048 # self.validate_purchase_return()
Saurabhfbb342c2016-04-07 16:41:31 +053049 self.validate_rejected_warehouse()
50 self.validate_accepted_rejected_qty()
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +053051 validate_for_items(self)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053052
Saurabhfbb342c2016-04-07 16:41:31 +053053 #sub-contracting
54 self.validate_for_subcontracting()
55 self.create_raw_materials_supplied("supplied_items")
56 self.set_landed_cost_voucher_amount()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053057
Nabin Hait14aa9c52016-04-18 15:54:01 +053058 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Saurabhfbb342c2016-04-07 16:41:31 +053059 self.update_valuation_rate("items")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053060
Anand Doshi3543f302013-05-24 19:25:01 +053061 def set_missing_values(self, for_validate=False):
Anand Doshiabc10032013-06-14 17:44:03 +053062 super(BuyingController, self).set_missing_values(for_validate)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +053063
Rushabh Mehta0b995402013-08-09 15:29:59 +053064 self.set_supplier_from_item_default()
Nabin Hait096d3632013-10-17 17:01:14 +053065 self.set_price_list_currency("Buying")
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053066
Anand Doshi3543f302013-05-24 19:25:01 +053067 # set contact and address details for supplier, if they are not mentioned
Nabin Hait365ae272014-04-03 17:38:54 +053068 if getattr(self, "supplier", None):
Nabin Hait7eba1a32017-10-02 15:59:27 +053069 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 +053070
Nabin Haitcccc45e2016-10-05 17:15:43 +053071 self.set_missing_item_details(for_validate)
Rushabh Mehta436467a2013-07-08 12:37:59 +053072
Rushabh Mehta0b995402013-08-09 15:29:59 +053073 def set_supplier_from_item_default(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +053074 if self.meta.get_field("supplier") and not self.supplier:
Nabin Haitdd38a262014-12-26 13:15:21 +053075 for d in self.get("items"):
Anand Doshie9baaa62014-02-26 12:35:33 +053076 supplier = frappe.db.get_value("Item", d.item_code, "default_supplier")
Rushabh Mehta0b995402013-08-09 15:29:59 +053077 if supplier:
Anand Doshif78d1ae2014-03-28 13:55:00 +053078 self.supplier = supplier
Rushabh Mehta0b995402013-08-09 15:29:59 +053079 break
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053080
Nabin Hait205f7ce2013-04-26 13:35:06 +053081 def validate_stock_or_nonstock_items(self):
Rohit Waghchaureaf059952018-05-07 18:46:53 +053082 if self.meta.get_field("taxes") and not self.get_stock_items() and not self.get_asset_items():
tundebabzy9a346202017-06-16 11:00:14 +010083 tax_for_valuation = [d for d in self.get("taxes")
Nabin Hait205f7ce2013-04-26 13:35:06 +053084 if d.category in ["Valuation", "Valuation and Total"]]
tundebabzy9a346202017-06-16 11:00:14 +010085
Nabin Hait205f7ce2013-04-26 13:35:06 +053086 if tax_for_valuation:
tundebabzy9a346202017-06-16 11:00:14 +010087 for d in tax_for_valuation:
88 d.category = 'Total'
89 msgprint(_('Tax Category has been changed to "Total" because all the Items are non-stock items'))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053090
Rohit Waghchaureaf059952018-05-07 18:46:53 +053091 def get_asset_items(self):
Rohit Waghchaured644e6d2018-05-12 15:27:18 +053092 if self.doctype not in ['Purchase Invoice', 'Purchase Receipt']:
93 return []
94
Rohit Waghchaureaf059952018-05-07 18:46:53 +053095 return [d.item_code for d in self.items if d.is_fixed_asset]
96
Saurabhfbb342c2016-04-07 16:41:31 +053097 def set_landed_cost_voucher_amount(self):
98 for d in self.get("items"):
rohitwaghchaure2e8232e2017-08-10 11:32:59 +053099 lc_voucher_data = frappe.db.sql("""select sum(applicable_charges), cost_center
Saurabhfbb342c2016-04-07 16:41:31 +0530100 from `tabLanded Cost Item`
101 where docstatus = 1 and purchase_receipt_item = %s""", d.name)
rohitwaghchaure2e8232e2017-08-10 11:32:59 +0530102 d.landed_cost_voucher_amount = lc_voucher_data[0][0] if lc_voucher_data else 0.0
103 if not d.cost_center and lc_voucher_data and lc_voucher_data[0][1]:
104 d.db_set('cost_center', lc_voucher_data[0][1])
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530105
Nabin Haitd3b62502013-01-21 17:24:31 +0530106 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530107 from frappe.utils import money_in_words
Nabin Hait5690be12015-02-12 16:09:11 +0530108 if self.meta.get_field("base_in_words"):
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530109 self.base_in_words = money_in_words(self.base_grand_total, self.company_currency)
Nabin Hait5b4c2942013-01-22 11:12:02 +0530110 if self.meta.get_field("in_words"):
Nabin Hait188f69a2015-02-12 17:55:50 +0530111 self.in_words = money_in_words(self.grand_total, self.currency)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530112
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530113 # update valuation rate
114 def update_valuation_rate(self, parentfield):
Anand Doshi8595fcf2013-02-08 19:28:14 +0530115 """
116 item_tax_amount is the total tax amount applied on that item
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530117 stored for valuation
118
Anand Doshi8595fcf2013-02-08 19:28:14 +0530119 TODO: rename item_tax_amount to valuation_tax_amount
120 """
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530121 stock_items = self.get_stock_items() + self.get_asset_items()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530122
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530123 stock_items_qty, stock_items_amount = 0, 0
124 last_stock_item_idx = 1
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530125 for d in self.get(parentfield):
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530126 if d.item_code and d.item_code in stock_items:
127 stock_items_qty += flt(d.qty)
Nabin Hait82e3e252015-02-23 16:58:30 +0530128 stock_items_amount += flt(d.base_net_amount)
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530129 last_stock_item_idx = d.idx
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530130
Nabin Hait82e3e252015-02-23 16:58:30 +0530131 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 +0530132 if d.category in ["Valuation", "Valuation and Total"]])
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530133
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530134 valuation_amount_adjustment = total_valuation_amount
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530135 for i, item in enumerate(self.get(parentfield)):
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530136 if item.item_code and item.qty and item.item_code in stock_items:
Nabin Hait82e3e252015-02-23 16:58:30 +0530137 item_proportion = flt(item.base_net_amount) / stock_items_amount if stock_items_amount \
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530138 else flt(item.qty) / stock_items_qty
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530139 if i == (last_stock_item_idx - 1):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530140 item.item_tax_amount = flt(valuation_amount_adjustment,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530141 self.precision("item_tax_amount", item))
142 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530143 item.item_tax_amount = flt(item_proportion * total_valuation_amount,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530144 self.precision("item_tax_amount", item))
145 valuation_amount_adjustment -= item.item_tax_amount
146
Anand Doshi39384d32013-05-11 19:39:53 +0530147 self.round_floats_in(item)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530148 if flt(item.conversion_factor)==0.0:
bobzz-zoneb4c7bad2015-08-05 11:30:12 +0700149 item.conversion_factor = get_conversion_factor(item.item_code, item.uom).get("conversion_factor") or 1.0
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530150
Rushabh Mehta54047782013-12-26 11:07:46 +0530151 qty_in_stock_uom = flt(item.qty * item.conversion_factor)
Saurabhfbb342c2016-04-07 16:41:31 +0530152 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 +0530153
nabinhait87f24012014-07-16 19:48:29 +0530154 landed_cost_voucher_amount = flt(item.landed_cost_voucher_amount) \
Saurabhfbb342c2016-04-07 16:41:31 +0530155 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] else 0.0
Nabin Hait14b8af22014-08-28 12:42:28 +0530156
Nabin Hait82e3e252015-02-23 16:58:30 +0530157 item.valuation_rate = ((item.base_net_amount + item.item_tax_amount + rm_supp_cost
nabinhait87f24012014-07-16 19:48:29 +0530158 + landed_cost_voucher_amount) / qty_in_stock_uom)
Anand Doshi4a7248e2013-02-27 18:10:30 +0530159 else:
Anand Doshi5af812a2013-05-10 19:23:02 +0530160 item.valuation_rate = 0.0
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530161
Nabin Hait54d209f2013-03-01 18:51:10 +0530162 def validate_for_subcontracting(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530163 if not self.is_subcontracted and self.sub_contracted_items:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530164 frappe.throw(_("Please enter 'Is Subcontracted' as Yes or No"))
165
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530166 if self.is_subcontracted == "Yes":
Saurabhfbb342c2016-04-07 16:41:31 +0530167 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] and not self.supplier_warehouse:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530168 frappe.throw(_("Supplier Warehouse mandatory for sub-contracted Purchase Receipt"))
169
Nabin Haitdd38a262014-12-26 13:15:21 +0530170 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530171 if item in self.sub_contracted_items and not item.bom:
172 frappe.throw(_("Please select BOM in BOM field for Item {0}").format(item.item_code))
173
Nabin Hait07e53762018-01-05 18:19:59 +0530174 if self.doctype == "Purchase Order":
175 for supplied_item in self.get("supplied_items"):
176 if not supplied_item.reserve_warehouse:
177 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 +0530178
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530179 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530180 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530181 if item.bom:
182 item.bom = None
183
Nabin Hait344f4432014-05-08 19:08:20 +0530184 def create_raw_materials_supplied(self, raw_material_table):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530185 if self.is_subcontracted=="Yes":
Nabin Hait344f4432014-05-08 19:08:20 +0530186 parent_items = []
Nabin Haitdd38a262014-12-26 13:15:21 +0530187 for item in self.get("items"):
Saurabhfbb342c2016-04-07 16:41:31 +0530188 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Haita0c239d2014-04-01 18:54:38 +0530189 item.rm_supp_cost = 0.0
rohitwaghchaure4dc5f0e2017-11-22 15:21:47 +0530190 if item.bom and item.item_code in self.sub_contracted_items:
Rushabh Mehtae693f792015-03-03 15:50:03 +0530191 self.update_raw_materials_supplied(item, raw_material_table)
Nabin Hait344f4432014-05-08 19:08:20 +0530192
193 if [item.item_code, item.name] not in parent_items:
194 parent_items.append([item.item_code, item.name])
195
196 self.cleanup_raw_materials_supplied(parent_items, raw_material_table)
Nabin Hait54d209f2013-03-01 18:51:10 +0530197
Saurabhfbb342c2016-04-07 16:41:31 +0530198 elif self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Haitdd38a262014-12-26 13:15:21 +0530199 for item in self.get("items"):
Nabin Haita0c239d2014-04-01 18:54:38 +0530200 item.rm_supp_cost = 0.0
201
Rohit Waghchaure4b9d2f22017-02-16 15:53:40 +0530202 if self.is_subcontracted == "No" and self.get("supplied_items"):
203 self.set('supplied_items', [])
204
Rushabh Mehtae693f792015-03-03 15:50:03 +0530205 def update_raw_materials_supplied(self, item, raw_material_table):
rohitwaghchaurebbd9b712018-03-07 15:39:40 +0530206 exploded_item = 1
207 if hasattr(item, 'include_exploded_items'):
208 exploded_item = item.get('include_exploded_items')
209
210 bom_items = get_items_from_bom(item.item_code, item.bom, exploded_item)
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530211
212 used_alternative_items = []
213 if self.doctype == 'Purchase Receipt' and item.purchase_order:
214 used_alternative_items = get_used_alternative_items(purchase_order = item.purchase_order)
215
Nabin Hait54d209f2013-03-01 18:51:10 +0530216 raw_materials_cost = 0
pawan2ff844e2017-11-30 18:14:55 +0530217 items = list(set([d.item_code for d in bom_items]))
218 item_wh = frappe._dict(frappe.db.sql("""select item_code, default_warehouse
Nabin Hait07e53762018-01-05 18:19:59 +0530219 from `tabItem` where name in ({0})""".format(", ".join(["%s"] * len(items))), items))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530220
Nabin Hait344f4432014-05-08 19:08:20 +0530221 for bom_item in bom_items:
Nabin Hait07e53762018-01-05 18:19:59 +0530222 if self.doctype == "Purchase Order":
223 reserve_warehouse = bom_item.source_warehouse or item_wh.get(bom_item.item_code)
224 if frappe.db.get_value("Warehouse", reserve_warehouse, "company") != self.company:
225 reserve_warehouse = None
226
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530227 conversion_factor = item.conversion_factor
228 if (self.doctype == 'Purchase Receipt' and item.purchase_order and
229 bom_item.item_code in used_alternative_items):
230 alternative_item_data = used_alternative_items.get(bom_item.item_code)
231 bom_item.item_code = alternative_item_data.item_code
232 bom_item.item_name = alternative_item_data.item_name
233 bom_item.stock_uom = alternative_item_data.stock_uom
234 conversion_factor = alternative_item_data.conversion_factor
235 bom_item.description = alternative_item_data.description
236
Nabin Hait344f4432014-05-08 19:08:20 +0530237 # check if exists
238 exists = 0
239 for d in self.get(raw_material_table):
240 if d.main_item_code == item.item_code and d.rm_item_code == bom_item.item_code \
241 and d.reference_name == item.name:
242 rm, exists = d, 1
243 break
244
245 if not exists:
246 rm = self.append(raw_material_table, {})
247
Fahim Ali Zain TP277935b2018-02-12 11:59:07 +0530248 required_qty = flt(flt(bom_item.qty_consumed_per_unit) * (flt(item.qty) + getattr(item, 'rejected_qty', 0)) *
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530249 flt(conversion_factor), rm.precision("required_qty"))
Nabin Hait344f4432014-05-08 19:08:20 +0530250 rm.reference_name = item.name
251 rm.bom_detail_no = bom_item.name
252 rm.main_item_code = item.item_code
253 rm.rm_item_code = bom_item.item_code
254 rm.stock_uom = bom_item.stock_uom
255 rm.required_qty = required_qty
Nabin Hait07e53762018-01-05 18:19:59 +0530256 if self.doctype == "Purchase Order" and not rm.reserve_warehouse:
257 rm.reserve_warehouse = reserve_warehouse
Nabin Hait344f4432014-05-08 19:08:20 +0530258
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530259 rm.conversion_factor = conversion_factor
Nabin Hait344f4432014-05-08 19:08:20 +0530260
Saurabhfbb342c2016-04-07 16:41:31 +0530261 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Hait344f4432014-05-08 19:08:20 +0530262 rm.consumed_qty = required_qty
263 rm.description = bom_item.description
264 if item.batch_no and not rm.batch_no:
265 rm.batch_no = item.batch_no
266
Nabin Haite96e83d2014-10-08 18:06:14 +0530267 # get raw materials rate
Nabin Haitfce28812014-10-08 18:38:27 +0530268 if self.doctype == "Purchase Receipt":
269 from erpnext.stock.utils import get_incoming_rate
Nabin Haitfb6e4342014-10-15 11:34:40 +0530270 rm.rate = get_incoming_rate({
Nabin Haitfce28812014-10-08 18:38:27 +0530271 "item_code": bom_item.item_code,
272 "warehouse": self.supplier_warehouse,
273 "posting_date": self.posting_date,
274 "posting_time": self.posting_time,
275 "qty": -1 * required_qty,
276 "serial_no": rm.serial_no
277 })
Nabin Haitfb6e4342014-10-15 11:34:40 +0530278 if not rm.rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530279 rm.rate = get_valuation_rate(bom_item.item_code, self.supplier_warehouse,
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530280 self.doctype, self.name, currency=self.company_currency, company = self.company)
Nabin Haitfce28812014-10-08 18:38:27 +0530281 else:
282 rm.rate = bom_item.rate
Nabin Haite96e83d2014-10-08 18:06:14 +0530283
Nabin Haitfce28812014-10-08 18:38:27 +0530284 rm.amount = required_qty * flt(rm.rate)
Nabin Haite96e83d2014-10-08 18:06:14 +0530285 raw_materials_cost += flt(rm.amount)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530286
Nabin Hait14aa9c52016-04-18 15:54:01 +0530287 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Nabin Hait344f4432014-05-08 19:08:20 +0530288 item.rm_supp_cost = raw_materials_cost
289
290 def cleanup_raw_materials_supplied(self, parent_items, raw_material_table):
291 """Remove all those child items which are no longer present in main item table"""
292 delete_list = []
293 for d in self.get(raw_material_table):
294 if [d.main_item_code, d.reference_name] not in parent_items:
295 # mark for deletion from doclist
Nabin Haitc3d1d6a2014-06-04 16:41:22 +0530296 delete_list.append(d)
Nabin Hait344f4432014-05-08 19:08:20 +0530297
298 # delete from doclist
299 if delete_list:
300 rm_supplied_details = self.get(raw_material_table)
301 self.set(raw_material_table, [])
302 for d in rm_supplied_details:
303 if d not in delete_list:
304 self.append(raw_material_table, d)
Nabin Hait54d209f2013-03-01 18:51:10 +0530305
Nabin Hait5418d712013-02-27 18:11:17 +0530306 @property
307 def sub_contracted_items(self):
308 if not hasattr(self, "_sub_contracted_items"):
Nabin Haitebd51442013-04-23 15:36:26 +0530309 self._sub_contracted_items = []
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530310 item_codes = list(set(item.item_code for item in
Nabin Haitdd38a262014-12-26 13:15:21 +0530311 self.get("items")))
Nabin Haitebd51442013-04-23 15:36:26 +0530312 if item_codes:
Anand Doshie9baaa62014-02-26 12:35:33 +0530313 self._sub_contracted_items = [r[0] for r in frappe.db.sql("""select name
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530314 from `tabItem` where name in (%s) and is_sub_contracted_item=1""" % \
Nabin Haitebd51442013-04-23 15:36:26 +0530315 (", ".join((["%s"]*len(item_codes))),), item_codes)]
Nabin Hait5418d712013-02-27 18:11:17 +0530316
317 return self._sub_contracted_items
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530318
nabinhait614fb752014-07-14 10:47:50 +0530319 def set_qty_as_per_stock_uom(self):
Nabin Haitdd38a262014-12-26 13:15:21 +0530320 for d in self.get("items"):
Nabin Haitfd4bcd82015-05-22 16:55:40 +0530321 if d.meta.get_field("stock_qty"):
nabinhait614fb752014-07-14 10:47:50 +0530322 if not d.conversion_factor:
Nabin Haite6e456b2015-05-13 17:21:44 +0530323 frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
Rushabh Mehta5b51cc82014-07-21 18:25:45 +0530324 d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530325
Saurabh130c57b2016-04-04 15:49:36 +0530326 def validate_purchase_return(self):
327 for d in self.get("items"):
328 if self.is_return and flt(d.rejected_qty) != 0:
329 frappe.throw(_("Row #{0}: Rejected Qty can not be entered in Purchase Return").format(d.idx))
330
331 # validate rate with ref PR
332
333 def validate_rejected_warehouse(self):
334 for d in self.get("items"):
335 if flt(d.rejected_qty) and not d.rejected_warehouse:
Saurabhfbb342c2016-04-07 16:41:31 +0530336 if self.rejected_warehouse:
337 d.rejected_warehouse = self.rejected_warehouse
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530338
Saurabh130c57b2016-04-04 15:49:36 +0530339 if not d.rejected_warehouse:
340 frappe.throw(_("Row #{0}: Rejected Warehouse is mandatory against rejected Item {1}").format(d.idx, d.item_code))
341
342 # validate accepted and rejected qty
343 def validate_accepted_rejected_qty(self):
344 for d in self.get("items"):
Saurabh4f4d0a82017-03-13 14:31:48 +0530345 self.validate_negative_quantity(d, ["received_qty","qty", "rejected_qty"])
Saurabh130c57b2016-04-04 15:49:36 +0530346 if not flt(d.received_qty) and flt(d.qty):
347 d.received_qty = flt(d.qty) - flt(d.rejected_qty)
348
349 elif not flt(d.qty) and flt(d.rejected_qty):
350 d.qty = flt(d.received_qty) - flt(d.rejected_qty)
351
352 elif not flt(d.rejected_qty):
353 d.rejected_qty = flt(d.received_qty) - flt(d.qty)
354
355 # Check Received Qty = Accepted Qty + Rejected Qty
356 if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)):
357 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 +0530358
Saurabh4f4d0a82017-03-13 14:31:48 +0530359 def validate_negative_quantity(self, item_row, field_list):
360 if self.is_return:
361 return
362
363 item_row = item_row.as_dict()
364 for fieldname in field_list:
365 if flt(item_row[fieldname]) < 0:
366 frappe.throw(_("Row #{0}: {1} can not be negative for item {2}".format(item_row['idx'],
367 frappe.get_meta(item_row.doctype).get_label(fieldname), item_row['item_code'])))
368
Saurabhe29248b2016-04-04 11:55:52 +0530369 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait07e53762018-01-05 18:19:59 +0530370 self.update_ordered_and_reserved_qty()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530371
Saurabhe29248b2016-04-04 11:55:52 +0530372 sl_entries = []
373 stock_items = self.get_stock_items()
374
375 for d in self.get('items'):
376 if d.item_code in stock_items and d.warehouse:
377 pr_qty = flt(d.qty) * flt(d.conversion_factor)
378
379 if pr_qty:
Saurabhe29248b2016-04-04 11:55:52 +0530380 sle = self.get_sl_entries(d, {
381 "actual_qty": flt(pr_qty),
382 "serial_no": cstr(d.serial_no).strip()
383 })
384 if self.is_return:
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530385 original_incoming_rate = frappe.db.get_value("Stock Ledger Entry",
386 {"voucher_type": "Purchase Receipt", "voucher_no": self.return_against,
Nabin Haitb81ed452016-05-11 12:52:31 +0530387 "item_code": d.item_code}, "incoming_rate")
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530388
Saurabhe29248b2016-04-04 11:55:52 +0530389 sle.update({
Nabin Haitb81ed452016-05-11 12:52:31 +0530390 "outgoing_rate": original_incoming_rate
Saurabhe29248b2016-04-04 11:55:52 +0530391 })
392 else:
Nabin Haitb81ed452016-05-11 12:52:31 +0530393 val_rate_db_precision = 6 if cint(self.precision("valuation_rate", d)) <= 6 else 9
394 incoming_rate = flt(d.valuation_rate, val_rate_db_precision)
Saurabhe29248b2016-04-04 11:55:52 +0530395 sle.update({
Nabin Haitb81ed452016-05-11 12:52:31 +0530396 "incoming_rate": incoming_rate
Saurabhe29248b2016-04-04 11:55:52 +0530397 })
398 sl_entries.append(sle)
399
Rohit Waghchaure560ba392016-08-29 18:19:32 +0530400 if flt(d.rejected_qty) != 0:
Saurabhe29248b2016-04-04 11:55:52 +0530401 sl_entries.append(self.get_sl_entries(d, {
402 "warehouse": d.rejected_warehouse,
403 "actual_qty": flt(d.rejected_qty) * flt(d.conversion_factor),
404 "serial_no": cstr(d.rejected_serial_no).strip(),
405 "incoming_rate": 0.0
406 }))
407
408 self.make_sl_entries_for_supplier_warehouse(sl_entries)
409 self.make_sl_entries(sl_entries, allow_negative_stock=allow_negative_stock,
410 via_landed_cost_voucher=via_landed_cost_voucher)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530411
Nabin Hait07e53762018-01-05 18:19:59 +0530412 def update_ordered_and_reserved_qty(self):
Nabin Hait14aa9c52016-04-18 15:54:01 +0530413 po_map = {}
414 for d in self.get("items"):
415 if self.doctype=="Purchase Receipt" \
Rohit Waghchaurea71d9d32016-07-05 00:34:00 +0530416 and d.purchase_order:
417 po_map.setdefault(d.purchase_order, []).append(d.purchase_order_item)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530418
Nabin Hait14aa9c52016-04-18 15:54:01 +0530419 elif self.doctype=="Purchase Invoice" and d.purchase_order and d.po_detail:
420 po_map.setdefault(d.purchase_order, []).append(d.po_detail)
421
422 for po, po_item_rows in po_map.items():
423 if po and po_item_rows:
424 po_obj = frappe.get_doc("Purchase Order", po)
425
426 if po_obj.status in ["Closed", "Cancelled"]:
427 frappe.throw(_("{0} {1} is cancelled or closed").format(_("Purchase Order"), po),
428 frappe.InvalidStatusError)
429
430 po_obj.update_ordered_qty(po_item_rows)
Nabin Hait07e53762018-01-05 18:19:59 +0530431 if self.is_subcontracted:
432 po_obj.update_reserved_qty_for_subcontract()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530433
Saurabhe29248b2016-04-04 11:55:52 +0530434 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
435 if hasattr(self, 'supplied_items'):
436 for d in self.get('supplied_items'):
437 # negative quantity is passed, as raw material qty has to be decreased
438 # when PR is submitted and it has to be increased when PR is cancelled
439 sl_entries.append(self.get_sl_entries(d, {
440 "item_code": d.rm_item_code,
441 "warehouse": self.supplier_warehouse,
442 "actual_qty": -1*flt(d.consumed_qty),
443 }))
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530444
rohitwaghchaurefe226862017-12-28 16:11:27 +0530445 def on_submit(self):
446 if self.get('is_return'):
447 return
448
Rohit Waghchaureab842542018-04-26 19:18:29 +0530449 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530450 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
451
452 self.process_fixed_asset()
453 self.update_fixed_asset(field)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530454
rohitwaghchaurefe226862017-12-28 16:11:27 +0530455 update_last_purchase_rate(self, is_submit = 1)
456
457 def on_cancel(self):
458 if self.get('is_return'):
459 return
460
461 update_last_purchase_rate(self, is_submit = 0)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530462 if self.doctype in ['Purchase Receipt', 'Purchase Invoice']:
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530463 field = 'purchase_invoice' if self.doctype == 'Purchase Invoice' else 'purchase_receipt'
464
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530465 self.delete_linked_asset()
466 self.update_fixed_asset(field, delete_asset=True)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530467
468 def process_fixed_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530469 if self.doctype == 'Purchase Invoice' and not self.update_stock:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530470 return
471
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530472 asset_items = self.get_asset_items()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530473 if asset_items:
474 self.make_serial_nos_for_asset(asset_items)
475
476 def make_serial_nos_for_asset(self, asset_items):
477 items_data = get_asset_item_details(asset_items)
478
479 for d in self.items:
480 if d.is_fixed_asset:
481 item_data = items_data.get(d.item_code)
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530482 if not d.asset:
483 asset = self.make_asset(d)
484 d.db_set('asset', asset)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530485
486 if item_data.get('has_serial_no'):
487 # If item has serial no
488 if item_data.get('serial_no_series') and not d.serial_no:
489 serial_nos = get_auto_serial_nos(item_data.get('serial_no_series'), d.qty)
490 elif d.serial_no:
491 serial_nos = d.serial_no
492 elif not d.serial_no:
493 frappe.throw(_("Serial no is mandatory for the item {0}").format(d.item_code))
494
495 auto_make_serial_nos({
496 'serial_no': serial_nos,
497 'item_code': d.item_code,
498 'via_stock_ledger': False,
499 'company': self.company,
500 'actual_qty': d.qty,
501 'purchase_document_type': self.doctype,
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530502 'purchase_document_no': self.name,
503 'asset': d.asset
Rohit Waghchaureab842542018-04-26 19:18:29 +0530504 })
505 d.db_set('serial_no', serial_nos)
506
Rohit Waghchaureab842542018-04-26 19:18:29 +0530507 if d.asset:
508 self.make_asset_movement(d)
509
510 def make_asset(self, row):
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530511 if not row.asset_location:
512 frappe.throw(_("Row {0}: Enter location for the asset item {1}").format(row.idx, row.item_code))
513
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530514 item_data = frappe.db.get_value('Item',
515 row.item_code, ['asset_naming_series', 'asset_category'], as_dict=1)
516
Rohit Waghchaure16bc8532018-05-12 12:06:00 +0530517 purchase_amount = flt(row.base_net_amount + row.item_tax_amount)
Rohit Waghchaureab842542018-04-26 19:18:29 +0530518 asset = frappe.get_doc({
519 'doctype': 'Asset',
520 'item_code': row.item_code,
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530521 'asset_name': row.item_name,
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530522 'status': 'Receipt',
Rohit Waghchauref2684ae2018-05-08 13:22:22 +0530523 'naming_series': item_data.get('asset_naming_series') or 'AST',
524 'asset_category': item_data.get('asset_category'),
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530525 'location': row.asset_location,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530526 'company': self.company,
527 'purchase_date': self.posting_date,
Rohit Waghchaure0ea6fe42018-05-08 23:31:58 +0530528 'calculate_depreciation': 1,
Rohit Waghchaure16bc8532018-05-12 12:06:00 +0530529 'purchase_receipt_amount': purchase_amount,
530 'gross_purchase_amount': purchase_amount,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530531 'purchase_receipt': self.name if self.doctype == 'Purchase Receipt' else None,
532 'purchase_invoice': self.name if self.doctype == 'Purchase Invoice' else None
533 })
534
535 asset.flags.ignore_validate = True
536 asset.flags.ignore_mandatory = True
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530537 asset.set_missing_values()
Rohit Waghchaureab842542018-04-26 19:18:29 +0530538 asset.insert()
539
540 frappe.msgprint(_("Asset {0} created").format(asset.name))
541 return asset.name
542
543 def make_asset_movement(self, row):
544 asset_movement = frappe.get_doc({
545 'doctype': 'Asset Movement',
546 'asset': row.asset,
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530547 'target_location': row.asset_location,
Rohit Waghchaureab842542018-04-26 19:18:29 +0530548 'purpose': 'Receipt',
549 'serial_no': row.serial_no,
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530550 'quantity': len(get_serial_nos(row.serial_no)),
Rohit Waghchaureab842542018-04-26 19:18:29 +0530551 'company': self.company,
552 'transaction_date': self.posting_date,
553 'reference_doctype': self.doctype,
554 'reference_name': self.name
555 }).insert()
556
557 return asset_movement.name
558
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530559 def update_fixed_asset(self, field, delete_asset = False):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530560 for d in self.get("items"):
561 if d.is_fixed_asset and d.asset:
562 asset = frappe.get_doc("Asset", d.asset)
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530563
564 if delete_asset and asset.docstatus == 0:
565 frappe.delete_doc("Asset", asset.name)
566 d.db_set('asset', None)
567 continue
568
Rohit Waghchaureab842542018-04-26 19:18:29 +0530569 if self.docstatus in [0, 1] and not asset.get(field):
570 asset.set(field, self.name)
571 asset.purchase_date = self.posting_date
572 asset.supplier = self.supplier
Rohit Waghchaureaa7b4342018-05-11 01:56:05 +0530573 elif self.docstatus == 2:
Rohit Waghchaureab842542018-04-26 19:18:29 +0530574 asset.set(field, None)
575 asset.supplier = None
576
577 asset.flags.ignore_validate_update_after_submit = True
578 if asset.docstatus == 0:
579 asset.flags.ignore_validate = True
580
581 asset.save()
582
Rohit Waghchaureaf059952018-05-07 18:46:53 +0530583 def delete_linked_asset(self):
Rohit Waghchaurec6deb132018-05-07 15:58:41 +0530584 if self.doctype == 'Purchase Invoice' and not self.get('update_stock'):
Rohit Waghchaureab842542018-04-26 19:18:29 +0530585 return
586
Rohit Waghchaureab842542018-04-26 19:18:29 +0530587 frappe.db.sql("delete from `tabAsset Movement` where reference_name=%s and docstatus = 0", self.name)
588 frappe.db.sql("delete from `tabSerial No` where purchase_document_no=%s", self.name)
rohitwaghchaurefe226862017-12-28 16:11:27 +0530589
Nabin Hait5a834202017-10-05 19:51:10 +0530590 def validate_schedule_date(self):
591 if not self.schedule_date:
592 self.schedule_date = min([d.schedule_date for d in self.get("items")])
593
594 if self.schedule_date:
595 for d in self.get('items'):
596 if not d.schedule_date:
597 d.schedule_date = self.schedule_date
598
Prateeksha Singhcbd06fd2018-01-05 21:28:01 +0530599 if (d.schedule_date and self.transaction_date and
600 getdate(d.schedule_date) < getdate(self.transaction_date)):
Nabin Hait96b264b2018-01-02 11:50:29 +0530601 frappe.throw(_("Row #{0}: Reqd by Date cannot be before Transaction Date").format(d.idx))
Nabin Hait5a834202017-10-05 19:51:10 +0530602 else:
Nabin Hait96b264b2018-01-02 11:50:29 +0530603 frappe.throw(_("Please enter Reqd by Date"))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530604
rohitwaghchaurebbd9b712018-03-07 15:39:40 +0530605def get_items_from_bom(item_code, bom, exploded_item=1):
606 doctype = "BOM Item" if not exploded_item else "BOM Explosion Item"
607
608 bom_items = frappe.db.sql("""select t2.item_code, t2.name,
609 t2.rate, t2.stock_uom, t2.source_warehouse, t2.description,
610 t2.stock_qty / ifnull(t1.quantity, 1) as qty_consumed_per_unit
611 from
612 `tabBOM` t1, `tab{0}` t2, tabItem t3
613 where
614 t2.parent = t1.name and t1.item = %s
615 and t1.docstatus = 1 and t1.is_active = 1 and t1.name = %s
616 and t2.item_code = t3.name and t3.is_stock_item = 1""".format(doctype),
617 (item_code, bom), as_dict=1)
618
619 if not bom_items:
620 msgprint(_("Specified BOM {0} does not exist for Item {1}").format(bom, item_code), raise_exception=1)
621
rohitwaghchaurea3c3dec2018-03-28 11:51:44 +0530622 return bom_items
Rohit Waghchaureab842542018-04-26 19:18:29 +0530623
624def get_asset_item_details(asset_items):
625 asset_items_data = {}
626 for d in frappe.get_all('Item', fields = ["name", "has_serial_no", "serial_no_series"],
627 filters = {'name': ('in', asset_items)}):
628 asset_items_data.setdefault(d.name, d)
629
630 return asset_items_data