blob: 0496ab21f4e7904cfe4486924caa5f0ba4ad331c [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
Rohit Waghchauref4dc7162018-11-15 17:04:02 +053013from frappe.contacts.doctype.address.address import get_address_display
Anand Doshi756dca72013-01-15 18:39:21 +053014
Rushabh Mehta1f847992013-12-12 19:12:19 +053015from erpnext.controllers.stock_controller import StockController
Nabin Haitbf495c92013-01-30 12:49:08 +053016
Nabin Hait89a94d82013-03-19 12:01:46 +053017class BuyingController(StockController):
Rushabh Mehta5b51cc82014-07-21 18:25:45 +053018 def __setup__(self):
Nabin Haitde9c8a92015-02-23 01:06:00 +053019 if hasattr(self, "taxes"):
Nabin Hait45dce892017-09-14 15:17:38 +053020 self.flags.print_taxes_with_zero_amount = cint(frappe.db.get_single_value("Print Settings",
21 "print_taxes_with_zero_amount"))
rohitwaghchaurebf4c1142018-01-08 15:20:15 +053022 self.flags.show_inclusive_tax_in_print = self.is_inclusive_tax()
23
Rushabh Mehtac567e8e2015-02-03 17:55:52 +053024 self.print_templates = {
rohitwaghchaurebf4c1142018-01-08 15:20:15 +053025 "total": "templates/print_formats/includes/total.html",
Rushabh Mehtac567e8e2015-02-03 17:55:52 +053026 "taxes": "templates/print_formats/includes/taxes.html"
Rushabh Mehta5b51cc82014-07-21 18:25:45 +053027 }
28
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053029 def get_feed(self):
rohitwaghchaurea1064a62016-03-03 14:00:35 +053030 if self.get("supplier_name"):
31 return _("From {0} | {1} {2}").format(self.supplier_name, self.currency,
32 self.grand_total)
Rushabh Mehtac0bb4532014-09-09 16:15:35 +053033
Saurabh6f753182013-03-20 12:55:28 +053034 def validate(self):
35 super(BuyingController, self).validate()
Nabin Hait365ae272014-04-03 17:38:54 +053036 if getattr(self, "supplier", None) and not self.supplier_name:
Nabin Hait1d218422015-07-17 15:19:02 +053037 self.supplier_name = frappe.db.get_value("Supplier", self.supplier, "supplier_name")
Rushabh Mehtaea0ff232016-07-07 14:02:26 +053038
Zarrarfc03a042018-06-04 12:52:52 +053039 self.validate_items()
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()
Rohit Waghchauref4dc7162018-11-15 17:04:02 +053043 self.set_supplier_address()
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"):
Anand Doshie9baaa62014-02-26 12:35:33 +053077 supplier = frappe.db.get_value("Item", d.item_code, "default_supplier")
Rushabh Mehta0b995402013-08-09 15:29:59 +053078 if supplier:
Anand Doshif78d1ae2014-03-28 13:55:00 +053079 self.supplier = supplier
Rushabh Mehta0b995402013-08-09 15:29:59 +053080 break
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053081
Nabin Hait205f7ce2013-04-26 13:35:06 +053082 def validate_stock_or_nonstock_items(self):
Nabin Haite7d15362014-12-25 16:01:55 +053083 if self.meta.get_field("taxes") and not self.get_stock_items():
tundebabzy9a346202017-06-16 11:00:14 +010084 tax_for_valuation = [d for d in self.get("taxes")
Nabin Hait205f7ce2013-04-26 13:35:06 +053085 if d.category in ["Valuation", "Valuation and Total"]]
tundebabzy9a346202017-06-16 11:00:14 +010086
Nabin Hait205f7ce2013-04-26 13:35:06 +053087 if tax_for_valuation:
tundebabzy9a346202017-06-16 11:00:14 +010088 for d in tax_for_valuation:
89 d.category = 'Total'
90 msgprint(_('Tax Category has been changed to "Total" because all the Items are non-stock items'))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +053091
Saurabhfbb342c2016-04-07 16:41:31 +053092 def set_landed_cost_voucher_amount(self):
93 for d in self.get("items"):
rohitwaghchaure2e8232e2017-08-10 11:32:59 +053094 lc_voucher_data = frappe.db.sql("""select sum(applicable_charges), cost_center
Saurabhfbb342c2016-04-07 16:41:31 +053095 from `tabLanded Cost Item`
96 where docstatus = 1 and purchase_receipt_item = %s""", d.name)
rohitwaghchaure2e8232e2017-08-10 11:32:59 +053097 d.landed_cost_voucher_amount = lc_voucher_data[0][0] if lc_voucher_data else 0.0
98 if not d.cost_center and lc_voucher_data and lc_voucher_data[0][1]:
99 d.db_set('cost_center', lc_voucher_data[0][1])
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530100
Rohit Waghchauref4dc7162018-11-15 17:04:02 +0530101 def set_supplier_address(self):
102 address_dict = {
103 'supplier_address': 'address_display',
104 'shipping_address': 'shipping_address_display'
105 }
106
107 for address_field, address_display_field in address_dict.items():
108 if self.get(address_field):
109 self.set(address_display_field, get_address_display(self.get(address_field)))
110
Nabin Haitd3b62502013-01-21 17:24:31 +0530111 def set_total_in_words(self):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530112 from frappe.utils import money_in_words
Nabin Hait5690be12015-02-12 16:09:11 +0530113 if self.meta.get_field("base_in_words"):
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530114 amount = (self.base_rounded_total
115 if not self.get("disable_rounded_total") else self.base_grand_total)
116
117 self.base_in_words = money_in_words(amount, self.company_currency)
118
Nabin Hait5b4c2942013-01-22 11:12:02 +0530119 if self.meta.get_field("in_words"):
rohitwaghchaureae4ff5a2018-08-01 18:09:51 +0530120 amount = (self.rounded_total
121 if not self.get("disable_rounded_total") else self.grand_total)
122
123 self.in_words = money_in_words(amount, self.currency)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530124
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530125 # update valuation rate
126 def update_valuation_rate(self, parentfield):
Anand Doshi8595fcf2013-02-08 19:28:14 +0530127 """
128 item_tax_amount is the total tax amount applied on that item
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530129 stored for valuation
130
Anand Doshi8595fcf2013-02-08 19:28:14 +0530131 TODO: rename item_tax_amount to valuation_tax_amount
132 """
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530133 stock_items = self.get_stock_items()
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530134
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530135 stock_items_qty, stock_items_amount = 0, 0
136 last_stock_item_idx = 1
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530137 for d in self.get(parentfield):
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530138 if d.item_code and d.item_code in stock_items:
139 stock_items_qty += flt(d.qty)
Nabin Hait82e3e252015-02-23 16:58:30 +0530140 stock_items_amount += flt(d.base_net_amount)
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530141 last_stock_item_idx = d.idx
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530142
Nabin Hait82e3e252015-02-23 16:58:30 +0530143 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 +0530144 if d.category in ["Valuation", "Valuation and Total"]])
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530145
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530146 valuation_amount_adjustment = total_valuation_amount
Rushabh Mehtad2b34dc2014-03-27 16:12:56 +0530147 for i, item in enumerate(self.get(parentfield)):
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530148 if item.item_code and item.qty and item.item_code in stock_items:
Nabin Hait82e3e252015-02-23 16:58:30 +0530149 item_proportion = flt(item.base_net_amount) / stock_items_amount if stock_items_amount \
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530150 else flt(item.qty) / stock_items_qty
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530151 if i == (last_stock_item_idx - 1):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530152 item.item_tax_amount = flt(valuation_amount_adjustment,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530153 self.precision("item_tax_amount", item))
154 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530155 item.item_tax_amount = flt(item_proportion * total_valuation_amount,
Nabin Haitdc15b4f2014-01-20 16:48:49 +0530156 self.precision("item_tax_amount", item))
157 valuation_amount_adjustment -= item.item_tax_amount
158
Anand Doshi39384d32013-05-11 19:39:53 +0530159 self.round_floats_in(item)
Rushabh Mehtaea0ff232016-07-07 14:02:26 +0530160 if flt(item.conversion_factor)==0.0:
bobzz-zoneb4c7bad2015-08-05 11:30:12 +0700161 item.conversion_factor = get_conversion_factor(item.item_code, item.uom).get("conversion_factor") or 1.0
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530162
Rushabh Mehta54047782013-12-26 11:07:46 +0530163 qty_in_stock_uom = flt(item.qty * item.conversion_factor)
Saurabhfbb342c2016-04-07 16:41:31 +0530164 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 +0530165
nabinhait87f24012014-07-16 19:48:29 +0530166 landed_cost_voucher_amount = flt(item.landed_cost_voucher_amount) \
Saurabhfbb342c2016-04-07 16:41:31 +0530167 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] else 0.0
Nabin Hait14b8af22014-08-28 12:42:28 +0530168
Nabin Hait82e3e252015-02-23 16:58:30 +0530169 item.valuation_rate = ((item.base_net_amount + item.item_tax_amount + rm_supp_cost
nabinhait87f24012014-07-16 19:48:29 +0530170 + landed_cost_voucher_amount) / qty_in_stock_uom)
Anand Doshi4a7248e2013-02-27 18:10:30 +0530171 else:
Anand Doshi5af812a2013-05-10 19:23:02 +0530172 item.valuation_rate = 0.0
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530173
Nabin Hait54d209f2013-03-01 18:51:10 +0530174 def validate_for_subcontracting(self):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530175 if not self.is_subcontracted and self.sub_contracted_items:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530176 frappe.throw(_("Please enter 'Is Subcontracted' as Yes or No"))
177
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530178 if self.is_subcontracted == "Yes":
Saurabhfbb342c2016-04-07 16:41:31 +0530179 if self.doctype in ["Purchase Receipt", "Purchase Invoice"] and not self.supplier_warehouse:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530180 frappe.throw(_("Supplier Warehouse mandatory for sub-contracted Purchase Receipt"))
181
Nabin Haitdd38a262014-12-26 13:15:21 +0530182 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530183 if item in self.sub_contracted_items and not item.bom:
184 frappe.throw(_("Please select BOM in BOM field for Item {0}").format(item.item_code))
185
Nabin Hait2c7a6e62018-03-12 14:12:12 +0530186 if self.doctype == "Purchase Order":
187 for supplied_item in self.get("supplied_items"):
188 if not supplied_item.reserve_warehouse:
189 frappe.throw(_("Reserved Warehouse is mandatory for Item {0} in Raw Materials supplied").format(frappe.bold(supplied_item.rm_item_code)))
190
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530191 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530192 for item in self.get("items"):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530193 if item.bom:
194 item.bom = None
195
Nabin Hait344f4432014-05-08 19:08:20 +0530196 def create_raw_materials_supplied(self, raw_material_table):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530197 if self.is_subcontracted=="Yes":
Nabin Hait344f4432014-05-08 19:08:20 +0530198 parent_items = []
Nabin Haitdd38a262014-12-26 13:15:21 +0530199 for item in self.get("items"):
Saurabhfbb342c2016-04-07 16:41:31 +0530200 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Haita0c239d2014-04-01 18:54:38 +0530201 item.rm_supp_cost = 0.0
rohitwaghchaure4dc5f0e2017-11-22 15:21:47 +0530202 if item.bom and item.item_code in self.sub_contracted_items:
Rushabh Mehtae693f792015-03-03 15:50:03 +0530203 self.update_raw_materials_supplied(item, raw_material_table)
Nabin Hait344f4432014-05-08 19:08:20 +0530204
205 if [item.item_code, item.name] not in parent_items:
206 parent_items.append([item.item_code, item.name])
207
208 self.cleanup_raw_materials_supplied(parent_items, raw_material_table)
Nabin Hait54d209f2013-03-01 18:51:10 +0530209
Saurabhfbb342c2016-04-07 16:41:31 +0530210 elif self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Haitdd38a262014-12-26 13:15:21 +0530211 for item in self.get("items"):
Nabin Haita0c239d2014-04-01 18:54:38 +0530212 item.rm_supp_cost = 0.0
213
Rohit Waghchaure4b9d2f22017-02-16 15:53:40 +0530214 if self.is_subcontracted == "No" and self.get("supplied_items"):
215 self.set('supplied_items', [])
216
Rushabh Mehtae693f792015-03-03 15:50:03 +0530217 def update_raw_materials_supplied(self, item, raw_material_table):
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530218 bom_items = self.get_items_from_bom(item.item_code, item.bom)
Nabin Hait54d209f2013-03-01 18:51:10 +0530219 raw_materials_cost = 0
Nabin Hait2c7a6e62018-03-12 14:12:12 +0530220 items = list(set([d.item_code for d in bom_items]))
221 item_wh = frappe._dict(frappe.db.sql("""select item_code, default_warehouse
222 from `tabItem` where name in ({0})""".format(", ".join(["%s"] * len(items))), items))
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530223
Nabin Hait344f4432014-05-08 19:08:20 +0530224 for bom_item in bom_items:
Nabin Hait2c7a6e62018-03-12 14:12:12 +0530225 if self.doctype == "Purchase Order":
226 reserve_warehouse = bom_item.source_warehouse or item_wh.get(bom_item.item_code)
227 if frappe.db.get_value("Warehouse", reserve_warehouse, "company") != self.company:
228 reserve_warehouse = None
229
Nabin Hait344f4432014-05-08 19:08:20 +0530230 # check if exists
231 exists = 0
232 for d in self.get(raw_material_table):
233 if d.main_item_code == item.item_code and d.rm_item_code == bom_item.item_code \
234 and d.reference_name == item.name:
235 rm, exists = d, 1
236 break
237
238 if not exists:
239 rm = self.append(raw_material_table, {})
240
Nabin Hait1b89be02017-11-30 15:59:56 +0530241 required_qty = flt(flt(bom_item.qty_consumed_per_unit) * flt(item.qty) *
242 flt(item.conversion_factor), rm.precision("required_qty"))
Nabin Hait344f4432014-05-08 19:08:20 +0530243 rm.reference_name = item.name
244 rm.bom_detail_no = bom_item.name
245 rm.main_item_code = item.item_code
246 rm.rm_item_code = bom_item.item_code
247 rm.stock_uom = bom_item.stock_uom
248 rm.required_qty = required_qty
Nabin Hait2c7a6e62018-03-12 14:12:12 +0530249 if self.doctype == "Purchase Order" and not rm.reserve_warehouse:
250 rm.reserve_warehouse = reserve_warehouse
Nabin Hait344f4432014-05-08 19:08:20 +0530251
252 rm.conversion_factor = item.conversion_factor
Nabin Hait344f4432014-05-08 19:08:20 +0530253
Saurabhfbb342c2016-04-07 16:41:31 +0530254 if self.doctype in ["Purchase Receipt", "Purchase Invoice"]:
Nabin Hait344f4432014-05-08 19:08:20 +0530255 rm.consumed_qty = required_qty
256 rm.description = bom_item.description
257 if item.batch_no and not rm.batch_no:
258 rm.batch_no = item.batch_no
259
Nabin Haite96e83d2014-10-08 18:06:14 +0530260 # get raw materials rate
Nabin Haitfce28812014-10-08 18:38:27 +0530261 if self.doctype == "Purchase Receipt":
262 from erpnext.stock.utils import get_incoming_rate
Nabin Haitfb6e4342014-10-15 11:34:40 +0530263 rm.rate = get_incoming_rate({
Nabin Haitfce28812014-10-08 18:38:27 +0530264 "item_code": bom_item.item_code,
265 "warehouse": self.supplier_warehouse,
266 "posting_date": self.posting_date,
267 "posting_time": self.posting_time,
268 "qty": -1 * required_qty,
269 "serial_no": rm.serial_no
270 })
Nabin Haitfb6e4342014-10-15 11:34:40 +0530271 if not rm.rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530272 rm.rate = get_valuation_rate(bom_item.item_code, self.supplier_warehouse,
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530273 self.doctype, self.name, currency=self.company_currency, company = self.company)
Nabin Haitfce28812014-10-08 18:38:27 +0530274 else:
275 rm.rate = bom_item.rate
Nabin Haite96e83d2014-10-08 18:06:14 +0530276
Nabin Haitfce28812014-10-08 18:38:27 +0530277 rm.amount = required_qty * flt(rm.rate)
Nabin Haite96e83d2014-10-08 18:06:14 +0530278 raw_materials_cost += flt(rm.amount)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530279
Nabin Hait14aa9c52016-04-18 15:54:01 +0530280 if self.doctype in ("Purchase Receipt", "Purchase Invoice"):
Nabin Hait344f4432014-05-08 19:08:20 +0530281 item.rm_supp_cost = raw_materials_cost
282
283 def cleanup_raw_materials_supplied(self, parent_items, raw_material_table):
284 """Remove all those child items which are no longer present in main item table"""
285 delete_list = []
286 for d in self.get(raw_material_table):
287 if [d.main_item_code, d.reference_name] not in parent_items:
288 # mark for deletion from doclist
Nabin Haitc3d1d6a2014-06-04 16:41:22 +0530289 delete_list.append(d)
Nabin Hait344f4432014-05-08 19:08:20 +0530290
291 # delete from doclist
292 if delete_list:
293 rm_supplied_details = self.get(raw_material_table)
294 self.set(raw_material_table, [])
295 for d in rm_supplied_details:
296 if d not in delete_list:
297 self.append(raw_material_table, d)
Nabin Hait54d209f2013-03-01 18:51:10 +0530298
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530299 def get_items_from_bom(self, item_code, bom):
Nabin Hait14b8af22014-08-28 12:42:28 +0530300 bom_items = frappe.db.sql("""select t2.item_code,
Ben Cornwell-Mott0f0b1212017-05-23 15:15:17 -0700301 t2.stock_qty / ifnull(t1.quantity, 1) as qty_consumed_per_unit,
Nabin Hait2c7a6e62018-03-12 14:12:12 +0530302 t2.rate, t2.stock_uom, t2.name, t2.description, t2.source_warehouse
Nabin Hait574d5ff2015-05-07 16:29:29 +0530303 from `tabBOM` t1, `tabBOM Item` t2, tabItem t3
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530304 where t2.parent = t1.name and t1.item = %s
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530305 and t1.docstatus = 1 and t1.is_active = 1 and t1.name = %s
306 and t2.item_code = t3.name and t3.is_stock_item = 1""", (item_code, bom), as_dict=1)
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530307
Nabin Hait54d209f2013-03-01 18:51:10 +0530308 if not bom_items:
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530309 msgprint(_("Specified BOM {0} does not exist for Item {1}").format(bom, item_code), raise_exception=1)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530310
Nabin Hait54d209f2013-03-01 18:51:10 +0530311 return bom_items
312
Nabin Hait5418d712013-02-27 18:11:17 +0530313 @property
314 def sub_contracted_items(self):
315 if not hasattr(self, "_sub_contracted_items"):
Nabin Haitebd51442013-04-23 15:36:26 +0530316 self._sub_contracted_items = []
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530317 item_codes = list(set(item.item_code for item in
Nabin Haitdd38a262014-12-26 13:15:21 +0530318 self.get("items")))
Nabin Haitebd51442013-04-23 15:36:26 +0530319 if item_codes:
Anand Doshie9baaa62014-02-26 12:35:33 +0530320 self._sub_contracted_items = [r[0] for r in frappe.db.sql("""select name
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530321 from `tabItem` where name in (%s) and is_sub_contracted_item=1""" % \
Nabin Haitebd51442013-04-23 15:36:26 +0530322 (", ".join((["%s"]*len(item_codes))),), item_codes)]
Nabin Hait5418d712013-02-27 18:11:17 +0530323
324 return self._sub_contracted_items
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530325
nabinhait614fb752014-07-14 10:47:50 +0530326 def set_qty_as_per_stock_uom(self):
Nabin Haitdd38a262014-12-26 13:15:21 +0530327 for d in self.get("items"):
Nabin Haitfd4bcd82015-05-22 16:55:40 +0530328 if d.meta.get_field("stock_qty"):
nabinhait614fb752014-07-14 10:47:50 +0530329 if not d.conversion_factor:
Nabin Haite6e456b2015-05-13 17:21:44 +0530330 frappe.throw(_("Row {0}: Conversion Factor is mandatory").format(d.idx))
Rushabh Mehta5b51cc82014-07-21 18:25:45 +0530331 d.stock_qty = flt(d.qty) * flt(d.conversion_factor)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530332
Saurabh130c57b2016-04-04 15:49:36 +0530333 def validate_purchase_return(self):
334 for d in self.get("items"):
335 if self.is_return and flt(d.rejected_qty) != 0:
336 frappe.throw(_("Row #{0}: Rejected Qty can not be entered in Purchase Return").format(d.idx))
337
338 # validate rate with ref PR
339
340 def validate_rejected_warehouse(self):
341 for d in self.get("items"):
342 if flt(d.rejected_qty) and not d.rejected_warehouse:
Saurabhfbb342c2016-04-07 16:41:31 +0530343 if self.rejected_warehouse:
344 d.rejected_warehouse = self.rejected_warehouse
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530345
Saurabh130c57b2016-04-04 15:49:36 +0530346 if not d.rejected_warehouse:
347 frappe.throw(_("Row #{0}: Rejected Warehouse is mandatory against rejected Item {1}").format(d.idx, d.item_code))
348
349 # validate accepted and rejected qty
350 def validate_accepted_rejected_qty(self):
351 for d in self.get("items"):
Saurabh4f4d0a82017-03-13 14:31:48 +0530352 self.validate_negative_quantity(d, ["received_qty","qty", "rejected_qty"])
Saurabh130c57b2016-04-04 15:49:36 +0530353 if not flt(d.received_qty) and flt(d.qty):
354 d.received_qty = flt(d.qty) - flt(d.rejected_qty)
355
356 elif not flt(d.qty) and flt(d.rejected_qty):
357 d.qty = flt(d.received_qty) - flt(d.rejected_qty)
358
359 elif not flt(d.rejected_qty):
360 d.rejected_qty = flt(d.received_qty) - flt(d.qty)
361
362 # Check Received Qty = Accepted Qty + Rejected Qty
363 if ((flt(d.qty) + flt(d.rejected_qty)) != flt(d.received_qty)):
364 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 +0530365
Saurabh4f4d0a82017-03-13 14:31:48 +0530366 def validate_negative_quantity(self, item_row, field_list):
367 if self.is_return:
368 return
369
370 item_row = item_row.as_dict()
371 for fieldname in field_list:
372 if flt(item_row[fieldname]) < 0:
373 frappe.throw(_("Row #{0}: {1} can not be negative for item {2}".format(item_row['idx'],
374 frappe.get_meta(item_row.doctype).get_label(fieldname), item_row['item_code'])))
375
Saurabhe29248b2016-04-04 11:55:52 +0530376 def update_stock_ledger(self, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait2c7a6e62018-03-12 14:12:12 +0530377 self.update_ordered_and_reserved_qty()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530378
Saurabhe29248b2016-04-04 11:55:52 +0530379 sl_entries = []
380 stock_items = self.get_stock_items()
381
382 for d in self.get('items'):
383 if d.item_code in stock_items and d.warehouse:
384 pr_qty = flt(d.qty) * flt(d.conversion_factor)
385
386 if pr_qty:
Saurabhe29248b2016-04-04 11:55:52 +0530387 sle = self.get_sl_entries(d, {
388 "actual_qty": flt(pr_qty),
389 "serial_no": cstr(d.serial_no).strip()
390 })
391 if self.is_return:
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530392 original_incoming_rate = frappe.db.get_value("Stock Ledger Entry",
393 {"voucher_type": "Purchase Receipt", "voucher_no": self.return_against,
Nabin Haitb81ed452016-05-11 12:52:31 +0530394 "item_code": d.item_code}, "incoming_rate")
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530395
Saurabhe29248b2016-04-04 11:55:52 +0530396 sle.update({
Nabin Haitb81ed452016-05-11 12:52:31 +0530397 "outgoing_rate": original_incoming_rate
Saurabhe29248b2016-04-04 11:55:52 +0530398 })
399 else:
Nabin Haitb81ed452016-05-11 12:52:31 +0530400 val_rate_db_precision = 6 if cint(self.precision("valuation_rate", d)) <= 6 else 9
401 incoming_rate = flt(d.valuation_rate, val_rate_db_precision)
Saurabhe29248b2016-04-04 11:55:52 +0530402 sle.update({
Nabin Haitb81ed452016-05-11 12:52:31 +0530403 "incoming_rate": incoming_rate
Saurabhe29248b2016-04-04 11:55:52 +0530404 })
405 sl_entries.append(sle)
406
Rohit Waghchaure560ba392016-08-29 18:19:32 +0530407 if flt(d.rejected_qty) != 0:
Saurabhe29248b2016-04-04 11:55:52 +0530408 sl_entries.append(self.get_sl_entries(d, {
409 "warehouse": d.rejected_warehouse,
410 "actual_qty": flt(d.rejected_qty) * flt(d.conversion_factor),
411 "serial_no": cstr(d.rejected_serial_no).strip(),
412 "incoming_rate": 0.0
413 }))
414
415 self.make_sl_entries_for_supplier_warehouse(sl_entries)
416 self.make_sl_entries(sl_entries, allow_negative_stock=allow_negative_stock,
417 via_landed_cost_voucher=via_landed_cost_voucher)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530418
Nabin Hait2c7a6e62018-03-12 14:12:12 +0530419 def update_ordered_and_reserved_qty(self):
Nabin Hait14aa9c52016-04-18 15:54:01 +0530420 po_map = {}
421 for d in self.get("items"):
422 if self.doctype=="Purchase Receipt" \
Rohit Waghchaurea71d9d32016-07-05 00:34:00 +0530423 and d.purchase_order:
424 po_map.setdefault(d.purchase_order, []).append(d.purchase_order_item)
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530425
Nabin Hait14aa9c52016-04-18 15:54:01 +0530426 elif self.doctype=="Purchase Invoice" and d.purchase_order and d.po_detail:
427 po_map.setdefault(d.purchase_order, []).append(d.po_detail)
428
429 for po, po_item_rows in po_map.items():
430 if po and po_item_rows:
431 po_obj = frappe.get_doc("Purchase Order", po)
432
433 if po_obj.status in ["Closed", "Cancelled"]:
434 frappe.throw(_("{0} {1} is cancelled or closed").format(_("Purchase Order"), po),
435 frappe.InvalidStatusError)
436
437 po_obj.update_ordered_qty(po_item_rows)
Nabin Hait2c7a6e62018-03-12 14:12:12 +0530438 if self.is_subcontracted:
439 po_obj.update_reserved_qty_for_subcontract()
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530440
Saurabhe29248b2016-04-04 11:55:52 +0530441 def make_sl_entries_for_supplier_warehouse(self, sl_entries):
442 if hasattr(self, 'supplied_items'):
443 for d in self.get('supplied_items'):
444 # negative quantity is passed, as raw material qty has to be decreased
445 # when PR is submitted and it has to be increased when PR is cancelled
446 sl_entries.append(self.get_sl_entries(d, {
447 "item_code": d.rm_item_code,
448 "warehouse": self.supplier_warehouse,
449 "actual_qty": -1*flt(d.consumed_qty),
450 }))
Rushabh Mehtab33df4a2016-07-04 11:38:37 +0530451
rohitwaghchaurefe226862017-12-28 16:11:27 +0530452 def on_submit(self):
453 if self.get('is_return'):
454 return
455
456 update_last_purchase_rate(self, is_submit = 1)
457
458 def on_cancel(self):
459 if self.get('is_return'):
460 return
461
462 update_last_purchase_rate(self, is_submit = 0)
463
Nabin Hait5a834202017-10-05 19:51:10 +0530464 def validate_schedule_date(self):
Shreya Shahd2b90932018-12-24 14:21:07 +0530465 if not self.schedule_date and self.get("items"):
Nabin Hait5a834202017-10-05 19:51:10 +0530466 self.schedule_date = min([d.schedule_date for d in self.get("items")])
467
468 if self.schedule_date:
469 for d in self.get('items'):
470 if not d.schedule_date:
471 d.schedule_date = self.schedule_date
472
Prateeksha Singh8b94f1b2018-01-08 16:46:39 +0530473 if (d.schedule_date and self.transaction_date and
474 getdate(d.schedule_date) < getdate(self.transaction_date)):
Nabin Hait96b264b2018-01-02 11:50:29 +0530475 frappe.throw(_("Row #{0}: Reqd by Date cannot be before Transaction Date").format(d.idx))
Nabin Hait5a834202017-10-05 19:51:10 +0530476 else:
Nabin Hait96b264b2018-01-02 11:50:29 +0530477 frappe.throw(_("Please enter Reqd by Date"))
Rushabh Mehta30dc9a12017-11-17 14:31:09 +0530478
Zarrarfc03a042018-06-04 12:52:52 +0530479 def validate_items(self):
480 # validate items to see if they have is_purchase_item or is_subcontracted_item enabled
Nabin Hait0bef91c2018-06-18 16:33:48 +0530481 if self.doctype=="Material Request": return
Zarrarfc03a042018-06-04 12:52:52 +0530482
rohitwaghchaure50d8c4a2018-06-05 13:08:10 +0530483 if hasattr(self, "is_subcontracted") and self.is_subcontracted == 'Yes':
Zarrarfc03a042018-06-04 12:52:52 +0530484 validate_item_type(self, "is_sub_contracted_item", "subcontracted")
485 else:
486 validate_item_type(self, "is_purchase_item", "purchase")
487
488def validate_item_type(doc, fieldname, message):
489 # iterate through items and check if they are valid sales or purchase items
Zarrar7c088ff2018-06-05 10:32:09 +0530490 items = [d.item_code for d in doc.items if d.item_code]
491
492 # No validation check inase of creating transaction using 'Opening Invoice Creation Tool'
493 if not items:
494 return
495
Zarrarfc03a042018-06-04 12:52:52 +0530496 item_list = ", ".join(["'%s'" % frappe.db.escape(d) for d in items])
497
498 invalid_items = [d[0] for d in frappe.db.sql("""
499 select item_code from tabItem where name in ({0}) and {1}=0
500 """.format(item_list, fieldname), as_list=True)]
501
502 if invalid_items:
503 frappe.throw(_("Following item {items} {verb} not marked as {message} item.\
504 You can enable them as {message} item from its Item master".format(
505 items = ", ".join([d for d in invalid_items]),
506 verb = "are" if len(invalid_items) > 1 else "is",
507 message = message)))