blob: c3cb437aacbe25020ba5eb5fc538140c16d9063f [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Nabin Hait436f5262014-02-10 14:47:54 +05302# License: GNU General Public License v3. See license.txt
3
4from __future__ import unicode_literals
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
6from frappe import _, throw
Manas Solanki03938482018-05-14 16:16:46 +05307from frappe.utils import flt, cint, add_days, cstr, add_months
Nabin Hait436f5262014-02-10 14:47:54 +05308import json
Nabin Hait34d28222016-01-19 15:45:49 +05309from erpnext.accounts.doctype.pricing_rule.pricing_rule import get_pricing_rule_for_item, set_transaction_type
Anand Doshidffec8f2014-07-01 17:45:15 +053010from erpnext.setup.utils import get_exchange_rate
Rushabh Mehta66e08e32014-09-29 12:17:03 +053011from frappe.model.meta import get_field_precision
Rushabh Mehta551406a2017-04-21 12:40:19 +053012from erpnext.stock.doctype.batch.batch import get_batch_no
tundebabzy6e90f492018-02-12 10:48:57 +010013from erpnext import get_company_currency
Manas Solankib16a4ec2018-05-04 16:49:33 +053014from erpnext.stock.doctype.item.item import get_item_defaults
Shreya Shah3c9839f2018-07-17 18:01:44 +053015from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults
Nabin Hait98c2a052014-05-05 18:41:41 +053016
Achilles Rasquinha714c7462018-02-15 11:28:55 +053017from six import string_types, iteritems
tundebabzyacccdb32017-11-23 08:35:15 +010018
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053019@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +053020def get_item_details(args):
21 """
22 args = {
23 "item_code": "",
24 "warehouse": None,
25 "customer": "",
26 "conversion_rate": 1.0,
27 "selling_price_list": None,
28 "price_list_currency": None,
Nabin Hait615d3422014-02-25 19:01:20 +053029 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +053030 "doctype": "",
31 "name": "",
Nabin Hait436f5262014-02-10 14:47:54 +053032 "supplier": None,
33 "transaction_date": None,
34 "conversion_rate": 1.0,
35 "buying_price_list": None,
36 "is_subcontracted": "Yes" / "No",
Nabin Hait444f9562014-06-20 15:59:49 +053037 "ignore_pricing_rule": 0/1
Neil Trini Lasrado6e343e22016-03-09 17:02:59 +053038 "project": ""
Nabin Hait436f5262014-02-10 14:47:54 +053039 }
40 """
Anand Doshidffec8f2014-07-01 17:45:15 +053041 args = process_args(args)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053042 item = frappe.get_cached_doc("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053043 validate_item_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053044
Rushabh Mehta1a763742014-10-03 16:36:43 +053045 out = get_basic_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053046
Rushabh Mehta708e47a2018-08-08 16:37:31 +053047 get_party_item_code(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053048
Rushabh Mehta708e47a2018-08-08 16:37:31 +053049 set_valuation_rate(out, args)
Anand Doshibd67e872014-04-11 16:51:27 +053050
Manas Solankie5e87f72018-05-28 20:07:08 +053051 update_party_blanket_order(args, out)
52
Rushabh Mehta708e47a2018-08-08 16:37:31 +053053 get_price_list_rate(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053054
Rushabh Mehtab46069d2016-01-15 16:59:26 +053055 if args.customer and cint(args.is_pos):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +053056 out.update(get_pos_profile_item_details(args.company, args))
Rushabh Mehta6b537922017-03-14 16:59:11 +053057
Nabin Hait0287d312017-01-11 10:31:33 +053058 if out.get("warehouse"):
59 out.update(get_bin_details(args.item_code, out.warehouse))
Anand Doshibd67e872014-04-11 16:51:27 +053060
Nabin Haita3dd72a2014-05-28 12:49:20 +053061 # update args with out, if key or value not exists
Achilles Rasquinha714c7462018-02-15 11:28:55 +053062 for key, value in iteritems(out):
Nabin Haita3dd72a2014-05-28 12:49:20 +053063 if args.get(key) is None:
64 args[key] = value
65
Nabin Hait444f9562014-06-20 15:59:49 +053066 out.update(get_pricing_rule_for_item(args))
Rushabh Mehta708e47a2018-08-08 16:37:31 +053067
68 update_stock(args, out)
69
70 if args.transaction_date and item.lead_time_days:
71 out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
72 item.lead_time_days)
73
74 if args.get("is_subcontracted") == "Yes":
75 out.bom = args.get('bom') or get_default_bom(args.item_code)
76
77 get_gross_profit(out)
78 if args.doctype == 'Material Request':
79 out.rate = args.rate or out.price_list_rate
80 out.amount = flt(args.qty * out.rate)
81
82 return out
83
84def update_stock(args, out):
pratu16x7577e4c42017-06-23 11:39:03 +053085 if (args.get("doctype") == "Delivery Note" or
Nabin Hait3ce41d62017-05-03 18:22:24 +053086 (args.get("doctype") == "Sales Invoice" and args.get('update_stock'))) \
87 and out.warehouse and out.stock_qty > 0:
pratu16x7577e4c42017-06-23 11:39:03 +053088
Nabin Hait8fac2ad2017-05-18 11:54:24 +053089 if out.has_batch_no and not args.get("batch_no"):
Rushabh Mehta551406a2017-04-21 12:40:19 +053090 out.batch_no = get_batch_no(out.item_code, out.warehouse, out.qty)
rohitwaghchaure2fb8cc52017-11-29 13:50:04 +053091 actual_batch_qty = get_batch_qty(out.batch_no, out.warehouse, out.item_code)
92 if actual_batch_qty:
93 out.update(actual_batch_qty)
Shreya14bd43d2018-04-27 16:24:05 +053094
95 if out.has_serial_no and args.get('batch_no'):
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +053096 reserved_so = get_so_reservation_for_item(args)
Shreya14bd43d2018-04-27 16:24:05 +053097 out.batch_no = args.get('batch_no')
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +053098 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Shreya14bd43d2018-04-27 16:24:05 +053099
100 elif out.has_serial_no:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530101 reserved_so = get_so_reservation_for_item(args)
102 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Rushabh Mehta551406a2017-04-21 12:40:19 +0530103
Anand Doshibd67e872014-04-11 16:51:27 +0530104
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530105def set_valuation_rate(out, args):
Nabin Hait50238c32018-08-08 18:43:04 +0530106 if frappe.db.exists("Product Bundle", args.item_code, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530107 valuation_rate = 0.0
108 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530109
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530110 for bundle_item in bundled_items.items:
111 valuation_rate += \
112 flt(get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get("valuation_rate") \
113 * bundle_item.qty)
Anand Doshi70f57eb2015-11-27 14:37:40 +0530114
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530115 out.update({
116 "valuation_rate": valuation_rate
117 })
118
119 else:
120 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
121
Nabin Hait436f5262014-02-10 14:47:54 +0530122
Anand Doshidffec8f2014-07-01 17:45:15 +0530123def process_args(args):
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530124 if isinstance(args, string_types):
Anand Doshidffec8f2014-07-01 17:45:15 +0530125 args = json.loads(args)
126
127 args = frappe._dict(args)
128
Anand Doshidffec8f2014-07-01 17:45:15 +0530129 if not args.get("price_list"):
130 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
131
132 if args.barcode:
133 args.item_code = get_item_code(barcode=args.barcode)
134 elif not args.item_code and args.serial_no:
135 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530136
mbauskar6f603392016-01-21 16:10:22 +0530137 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530138 return args
139
tundebabzyacccdb32017-11-23 08:35:15 +0100140
Neil Trini Lasrado4abda672015-02-25 17:34:27 +0530141@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530142def get_item_code(barcode=None, serial_no=None):
143 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100144 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530145 if not item_code:
146 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530147 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530148 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530149 if not item_code:
150 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530151
Nabin Hait436f5262014-02-10 14:47:54 +0530152 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530153
tundebabzyacccdb32017-11-23 08:35:15 +0100154
Nabin Hait436f5262014-02-10 14:47:54 +0530155def validate_item_details(args, item):
156 if not args.company:
157 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530158
Nabin Hait436f5262014-02-10 14:47:54 +0530159 from erpnext.stock.doctype.item.item import validate_end_of_life
Anand Doshi21e09a22015-10-29 12:21:41 +0530160 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530161
tundebabzyacccdb32017-11-23 08:35:15 +0100162 if args.transaction_type == "selling" and cint(item.has_variants):
Umair Sayyed72534de2016-04-15 12:52:12 +0530163 throw(_("Item {0} is a template, please select one of its variants").format(item.name))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530164
tundebabzyacccdb32017-11-23 08:35:15 +0100165 elif args.transaction_type == "buying" and args.doctype != "Material Request":
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530166 if args.get("is_subcontracted") == "Yes" and item.is_sub_contracted_item != 1:
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530167 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530168
tundebabzyacccdb32017-11-23 08:35:15 +0100169
Rushabh Mehta1a763742014-10-03 16:36:43 +0530170def get_basic_details(args, item):
tundebabzyacccdb32017-11-23 08:35:15 +0100171 """
172 :param args: {
173 "item_code": "",
174 "warehouse": None,
175 "customer": "",
176 "conversion_rate": 1.0,
177 "selling_price_list": None,
178 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530179 "price_list_uom_dependant": None,
tundebabzyacccdb32017-11-23 08:35:15 +0100180 "plc_conversion_rate": 1.0,
181 "doctype": "",
182 "name": "",
183 "supplier": None,
184 "transaction_date": None,
185 "conversion_rate": 1.0,
186 "buying_price_list": None,
187 "is_subcontracted": "Yes" / "No",
188 "ignore_pricing_rule": 0/1
189 "project": "",
190 barcode: "",
191 serial_no: "",
192 warehouse: "",
193 currency: "",
194 update_stock: "",
195 price_list: "",
196 company: "",
197 order_type: "",
198 is_pos: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100199 project: "",
200 qty: "",
201 stock_qty: "",
202 conversion_factor: ""
203 }
204 :param item: `item_code` of Item object
205 :return: frappe._dict
206 """
207
Rushabh Mehta1a763742014-10-03 16:36:43 +0530208 if not item:
209 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530210
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530211 if item.variant_of:
212 item.update_template_tables()
213
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530214 from frappe.defaults import get_user_default_as_list
Nabin Haitb6b56452015-12-23 16:37:00 +0530215 user_default_warehouse_list = get_user_default_as_list('Warehouse')
Nabin Hait436f5262014-02-10 14:47:54 +0530216 user_default_warehouse = user_default_warehouse_list[0] \
tundebabzyacccdb32017-11-23 08:35:15 +0100217 if len(user_default_warehouse_list) == 1 else ""
Manas Solanki64614372018-05-07 16:55:32 +0530218
Manas Solankib16a4ec2018-05-04 16:49:33 +0530219 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530220 item_group_defaults = get_item_group_defaults(item.name, args.company)
221
222 warehouse = user_default_warehouse or item_defaults.get("default_warehouse") or\
223 item_group_defaults.get("default_warehouse") or args.warehouse
Nabin Hait36028bf2014-02-12 19:09:28 +0530224
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530225 if args.get('doctype') == "Material Request" and not args.get('material_request_type'):
226 args['material_request_type'] = frappe.db.get_value('Material Request',
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530227 args.get('name'), 'material_request_type', cache=True)
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530228
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530229 #Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
230 if not args.uom:
231 if args.get('doctype') in ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']:
232 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530233 elif (args.get('doctype') in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']) or \
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530234 (args.get('doctype') == 'Material Request' and args.get('material_request_type') == 'Purchase'):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530235 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
236 else:
237 args.uom = item.stock_uom
238
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530239 out = frappe._dict({
Nabin Hait139dc7b2014-02-12 14:53:18 +0530240 "item_code": item.name,
241 "item_name": item.item_name,
Neil Trini Lasradoc48f06c2015-02-10 16:49:16 +0530242 "description": cstr(item.description).strip(),
243 "image": cstr(item.image).strip(),
Saurabhd3135532016-02-25 18:59:20 +0530244 "warehouse": warehouse,
Shreya Shah3c9839f2018-07-17 18:01:44 +0530245 "income_account": get_default_income_account(args, item_defaults, item_group_defaults),
246 "expense_account": get_default_expense_account(args, item_defaults, item_group_defaults),
247 "cost_center": get_default_cost_center(args, item_defaults, item_group_defaults),
Rushabh Mehta551406a2017-04-21 12:40:19 +0530248 'has_serial_no': item.has_serial_no,
249 'has_batch_no': item.has_batch_no,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530250 "batch_no": None,
Anand Doshibd67e872014-04-11 16:51:27 +0530251 "item_tax_rate": json.dumps(dict(([d.tax_type, d.tax_rate] for d in
Nabin Haite7d15362014-12-25 16:01:55 +0530252 item.get("taxes")))),
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530253 "uom": args.uom,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530254 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
Nabin Hait4a6c1782015-05-29 17:31:31 +0530255 "qty": args.qty or 1.0,
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530256 "stock_qty": args.qty or 1.0,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530257 "price_list_rate": 0.0,
258 "base_price_list_rate": 0.0,
259 "rate": 0.0,
260 "base_rate": 0.0,
261 "amount": 0.0,
262 "base_amount": 0.0,
Nabin Hait82e3e252015-02-23 16:58:30 +0530263 "net_rate": 0.0,
264 "net_amount": 0.0,
Saurabhc6dbe702015-10-19 14:17:52 +0530265 "discount_percentage": 0.0,
Shreya Shah3c9839f2018-07-17 18:01:44 +0530266 "supplier": get_default_supplier(args, item_defaults, item_group_defaults),
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530267 "update_stock": args.get("update_stock") if args.get('doctype') in ['Sales Invoice', 'Purchase Invoice'] else 0,
Rohit Waghchaurec858d522016-12-12 13:01:43 +0530268 "delivered_by_supplier": item.delivered_by_supplier if args.get("doctype") in ["Sales Order", "Sales Invoice"] else 0,
Vishal Dhayaguded42242d2017-11-29 16:09:59 +0530269 "is_fixed_asset": item.is_fixed_asset,
270 "weight_per_unit":item.weight_per_unit,
271 "weight_uom":item.weight_uom,
Nabin Haite45ec662018-08-01 17:44:34 +0530272 "last_purchase_rate": item.last_purchase_rate if args.get("doctype") in ["Purchase Order"] else 0,
273 "transaction_date": args.get("transaction_date")
Nabin Hait139dc7b2014-02-12 14:53:18 +0530274 })
Anand Doshibd67e872014-04-11 16:51:27 +0530275
Manas Solanki03938482018-05-14 16:16:46 +0530276 if item.enable_deferred_revenue:
Zlash6580f5cb02018-08-29 11:39:08 +0530277 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530278
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530279 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530280 if item.stock_uom == args.uom:
281 out.conversion_factor = 1.0
282 else:
283 out.conversion_factor = args.conversion_factor or \
tundebabzyacccdb32017-11-23 08:35:15 +0100284 get_conversion_factor(item.item_code, args.uom).get("conversion_factor") or 1.0
mbauskar287fe812017-04-10 19:15:57 +0530285
286 args.conversion_factor = out.conversion_factor
287 out.stock_qty = out.qty * out.conversion_factor
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530288
Shreya Shah44fa9a62018-01-08 14:58:20 +0530289 # calculate last purchase rate
290 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
291 out.last_purchase_rate = item_last_purchase_rate(args.name, args.conversion_rate, item.item_code, out.conversion_factor)
292
Nabin Haitb09ed412015-02-17 10:33:58 +0530293 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530294 for d in [
295 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530296 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530297 ["Cost Center", "cost_center", "cost_center"],
298 ["Warehouse", "warehouse", ""]]:
Nabin Hait33df0b42018-05-26 09:09:02 +0530299 if not out[d[1]]:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530300 out[d[1]] = frappe.get_cached_value('Company', args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530301
Giovanni2144e022017-12-10 17:27:09 +0100302 for fieldname in ("item_name", "item_group", "barcodes", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530303 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530304
Nabin Hait436f5262014-02-10 14:47:54 +0530305 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530306
Zlash6580f5cb02018-08-29 11:39:08 +0530307@frappe.whitelist()
308def calculate_service_end_date(args, item=None):
309 args = process_args(args)
310 if not item:
311 item = frappe.get_cached_doc("Item", args.item_code)
312
313 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
314 service_end_date = add_months(service_start_date, item.no_of_months)
315 deferred_detail = {
316 "enable_deferred_revenue": item.enable_deferred_revenue,
317 "deferred_revenue_account": get_default_deferred_revenue_account(args, item),
318 "service_start_date": service_start_date,
319 "service_end_date": service_end_date
320 }
321
322 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100323
Shreya Shah3c9839f2018-07-17 18:01:44 +0530324def get_default_income_account(args, item, item_group):
Manas Solanki38667ab2018-05-16 16:55:23 +0530325 return (item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530326 or item_group.get("income_account")
327 or args.income_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530328
Shreya Shah3c9839f2018-07-17 18:01:44 +0530329def get_default_expense_account(args, item, item_group):
Manas Solanki38667ab2018-05-16 16:55:23 +0530330 return (item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530331 or item_group.get("expense_account")
332 or args.expense_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530333
Manas Solanki03938482018-05-14 16:16:46 +0530334def get_default_deferred_revenue_account(args, item):
335 if item.enable_deferred_revenue:
336 return (item.deferred_revenue_account
337 or args.deferred_revenue_account
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530338 or frappe.get_cached_value('Company', args.company, "default_deferred_revenue_account"))
Manas Solanki03938482018-05-14 16:16:46 +0530339 else:
340 return None
341
Shreya Shah3c9839f2018-07-17 18:01:44 +0530342def get_default_cost_center(args, item, item_group):
Nabin Hait50238c32018-08-08 18:43:04 +0530343 cost_center = None
344 if args.get('project'):
345 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530346
Nabin Hait50238c32018-08-08 18:43:04 +0530347 if not cost_center:
348 if args.get('customer'):
349 cost_center = item.get('selling_cost_center') or item_group.get('selling_cost_center')
350 else:
351 cost_center = item.get('buying_cost_center') or item_group.get('buying_cost_center')
Rushabh Mehta49f97472018-08-30 18:50:48 +0530352
Nabin Hait50238c32018-08-08 18:43:04 +0530353 return cost_center or args.get("cost_center")
Rushabh Mehta1a763742014-10-03 16:36:43 +0530354
Shreya Shah3c9839f2018-07-17 18:01:44 +0530355def get_default_supplier(args, item, item_group):
356 return (item.get("default_supplier")
357 or item_group.get("default_supplier"))
358
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530359def get_price_list_rate(args, item_doc, out):
Anand Doshi39a28912016-02-15 11:42:18 +0530360 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530361
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530362 if meta.get_field("currency") or args.get('currency'):
Nabin Hait436f5262014-02-10 14:47:54 +0530363 validate_price_list(args)
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530364 if meta.get_field("currency") and args.price_list:
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530365 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530366
Nabin Haite45ec662018-08-01 17:44:34 +0530367 price_list_rate = get_price_list_rate_for(args, item_doc.name) or 0
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530368
369 # insert in database
Rushabh Mehta1a763742014-10-03 16:36:43 +0530370 if not price_list_rate:
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530371 if args.price_list and args.rate:
372 insert_item_price(args)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530373 return {}
Anand Doshibd67e872014-04-11 16:51:27 +0530374
Nabin Haite45ec662018-08-01 17:44:34 +0530375 # variant
376 if not price_list_rate and item_doc.variant_of:
377 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
378
Nabin Hait436f5262014-02-10 14:47:54 +0530379 out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) \
380 / flt(args.conversion_rate)
mbauskar287fe812017-04-10 19:15:57 +0530381
Nabin Hait34d28222016-01-19 15:45:49 +0530382 if not out.price_list_rate and args.transaction_type=="buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530383 from erpnext.stock.doctype.item.item import get_last_purchase_details
Anand Doshibd67e872014-04-11 16:51:27 +0530384 out.update(get_last_purchase_details(item_doc.name,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530385 args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530386
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530387def insert_item_price(args):
388 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530389 if frappe.db.get_value("Price List", args.price_list, "currency", cache=True) == args.currency \
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530390 and cint(frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")):
391 if frappe.has_permission("Item Price", "write"):
Nabin Haite45ec662018-08-01 17:44:34 +0530392 price_list_rate = (args.rate / args.get('conversion_factor')
393 if args.get("conversion_factor") else args.rate)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530394
Nabin Haitb479a872018-09-07 13:17:11 +0530395 item_price = frappe.db.get_value('Item Price',
396 {'item_code': args.item_code, 'price_list': args.price_list, 'currency': args.currency},
397 ['name', 'price_list_rate'], as_dict=1)
398 if item_price and item_price.name:
399 if item_price.price_list_rate != price_list_rate:
400 frappe.db.set_value('Item Price', item_price.name, "price_list_rate", price_list_rate)
401 frappe.msgprint(_("Item Price updated for {0} in Price List {1}").format(args.item_code,
402 args.price_list), alert=True)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530403 else:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530404 item_price = frappe.get_doc({
405 "doctype": "Item Price",
406 "price_list": args.price_list,
407 "item_code": args.item_code,
408 "currency": args.currency,
409 "price_list_rate": price_list_rate
410 })
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530411 item_price.insert()
412 frappe.msgprint(_("Item Price added for {0} in Price List {1}").format(args.item_code,
Rushabh Mehta49f97472018-08-30 18:50:48 +0530413 args.price_list), alert=True)
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530414
Nabin Haite45ec662018-08-01 17:44:34 +0530415def get_item_price(args, item_code):
416 """
417 Get name, price_list_rate from Item Price based on conditions
418 Check if the Derised qty is within the increment of the packing list.
419 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
420 optional fields min_qty, transaction_date, customer, supplier
421 :param item_code: str, Item Doctype field item_code
422 """
423
424 args['item_code'] = item_code
425 conditions = "where (customer is null or customer = '') and (supplier is null or supplier = '')"
426 if args.get("customer"):
427 conditions = "where customer=%(customer)s"
428
429 if args.get("supplier"):
430 conditions = "where supplier=%(supplier)s"
431
432 conditions += """ and item_code=%(item_code)s
433 and price_list=%(price_list)s
434 and ifnull(uom, '') in ('', %(uom)s)"""
435
436 if args.get('min_qty'):
437 conditions += " and ifnull(min_qty, 0) <= %(min_qty)s"
438
439 if args.get('transaction_date'):
440 conditions += """ and %(transaction_date)s between
441 ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
442
443 return frappe.db.sql(""" select name, price_list_rate, uom
444 from `tabItem Price` {conditions}
445 order by uom desc, min_qty desc """.format(conditions=conditions), args)
446
447def get_price_list_rate_for(args, item_code):
448 """
449 Return Price Rate based on min_qty of each Item Price Rate.\
450 For example, desired qty is 10 and Item Price Rates exists
451 for min_qty 9 and min_qty 20. It returns Item Price Rate for qty 9 as
452 the best fit in the range of avaliable min_qtyies
453
454 :param customer: link to Customer DocType
455 :param supplier: link to Supplier DocType
456 :param price_list: str (Standard Buying or Standard Selling)
457 :param item_code: str, Item Doctype field item_code
458 :param qty: Derised Qty
459 :param transaction_date: Date of the price
460 """
461 item_price_args = {
462 "item_code": item_code,
463 "price_list": args.get('price_list'),
464 "customer": args.get('customer'),
465 "supplier": args.get('supplier'),
466 "uom": args.get('uom'),
467 "min_qty": args.get('qty'),
468 "transaction_date": args.get('transaction_date'),
469 }
470
471 item_price_data = 0
472 price_list_rate = get_item_price(item_price_args, item_code)
473 if price_list_rate:
474 desired_qty = args.get("qty")
475 if check_packing_list(price_list_rate[0][0], desired_qty, item_code):
476 item_price_data = price_list_rate
477 else:
478 for field in ["customer", "supplier", "min_qty"]:
479 del item_price_args[field]
480
481 general_price_list_rate = get_item_price(item_price_args, item_code)
482 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
483 item_price_args["args"] = args.get("stock_uom")
484 general_price_list_rate = get_item_price(item_price_args, item_code)
485
486 if general_price_list_rate:
487 item_price_data = general_price_list_rate
488
489 if item_price_data:
490 if item_price_data[0][2] == args.get("uom"):
491 return item_price_data[0][1]
492 elif not args.get('price_list_uom_dependant'):
493 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
494 else:
495 return item_price_data[0][1]
496
497def check_packing_list(price_list_rate_name, desired_qty, item_code):
498 """
499 Check if the Derised qty is within the increment of the packing list.
500 :param price_list_rate_name: Name of Item Price
501 :param desired_qty: Derised Qt
502 :param item_code: str, Item Doctype field item_code
503 :param qty: Derised Qt
504 """
505
506 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Nabin Hait9983d412018-08-30 19:10:24 +0530507 if desired_qty and item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +0530508 packing_increment = desired_qty % item_price.packing_unit
509
510 if packing_increment == 0:
511 return True
Rushabh Mehta1a763742014-10-03 16:36:43 +0530512
Nabin Hait436f5262014-02-10 14:47:54 +0530513def validate_price_list(args):
514 if args.get("price_list"):
Anand Doshibd67e872014-04-11 16:51:27 +0530515 if not frappe.db.get_value("Price List",
Nabin Hait34d28222016-01-19 15:45:49 +0530516 {"name": args.price_list, args.transaction_type: 1, "enabled": 1}):
Rushabh Mehta985cb822016-12-30 15:06:54 +0530517 throw(_("Price List {0} is disabled or does not exist").format(args.price_list))
mbauskar0b665ac2017-04-11 02:49:24 -0400518 elif not args.get("supplier"):
Nabin Hait436f5262014-02-10 14:47:54 +0530519 throw(_("Price List not selected"))
Anand Doshibd67e872014-04-11 16:51:27 +0530520
Nabin Hait436f5262014-02-10 14:47:54 +0530521def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +0530522 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +0530523
Anand Doshife13bfe2015-08-25 12:49:40 +0530524 if (not args.conversion_rate
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530525 and args.currency==frappe.get_cached_value('Company', args.company, "default_currency")):
Anand Doshife13bfe2015-08-25 12:49:40 +0530526 args.conversion_rate = 1.0
527
Nabin Hait436f5262014-02-10 14:47:54 +0530528 # validate currency conversion rate
Anand Doshibd67e872014-04-11 16:51:27 +0530529 validate_conversion_rate(args.currency, args.conversion_rate,
Nabin Hait436f5262014-02-10 14:47:54 +0530530 meta.get_label("conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530531
532 args.conversion_rate = flt(args.conversion_rate,
533 get_field_precision(meta.get_field("conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530534 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530535
Manas Solanki3504a232018-06-06 12:46:06 +0530536 if (not args.plc_conversion_rate
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530537 and args.price_list_currency==frappe.db.get_value("Price List", args.price_list, "currency", cache=True)):
Manas Solanki3504a232018-06-06 12:46:06 +0530538 args.plc_conversion_rate = 1.0
539
Nabin Hait436f5262014-02-10 14:47:54 +0530540 # validate price list currency conversion rate
541 if not args.get("price_list_currency"):
542 throw(_("Price List Currency not selected"))
543 else:
Anand Doshibd67e872014-04-11 16:51:27 +0530544 validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate,
Nabin Hait436f5262014-02-10 14:47:54 +0530545 meta.get_label("plc_conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530546
547 args.plc_conversion_rate = flt(args.plc_conversion_rate,
548 get_field_precision(meta.get_field("plc_conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530549 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530550
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530551def get_party_item_code(args, item_doc, out):
Nabin Hait34d28222016-01-19 15:45:49 +0530552 if args.transaction_type=="selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +0530553 out.customer_item_code = None
Nabin Hait79f091e2014-12-26 11:41:15 +0530554 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +0530555
556 if customer_item_code:
557 out.customer_item_code = customer_item_code[0].ref_code
558 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +0530559 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +0530560 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
561 if customer_group_item_code and not customer_group_item_code[0].customer_name:
562 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +0530563
Nabin Hait34d28222016-01-19 15:45:49 +0530564 if args.transaction_type=="buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +0530565 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +0530566 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +0530567
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530568def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530569 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +0530570
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530571 if not frappe.flags.pos_profile and not pos_profile:
572 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get('pos_profile'))
Anand Doshibd67e872014-04-11 16:51:27 +0530573
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530574 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +0530575 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530576 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530577 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530578
Nabin Hait436f5262014-02-10 14:47:54 +0530579 if res.get("warehouse"):
Saurabhd3135532016-02-25 18:59:20 +0530580 res.actual_qty = get_bin_details(args.item_code,
Nabin Hait436f5262014-02-10 14:47:54 +0530581 res.warehouse).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +0530582
Nabin Hait436f5262014-02-10 14:47:54 +0530583 return res
584
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530585@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530586def get_pos_profile(company, pos_profile=None, user=None):
587 if pos_profile:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530588 return frappe.get_cached_doc('POS Profile', pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530589
590 if not user:
591 user = frappe.session['user']
592
593 pos_profile = frappe.db.sql("""select pf.*
594 from
595 `tabPOS Profile` pf, `tabPOS Profile User` pfu
596 where
597 pfu.parent = pf.name and pfu.user = %s and pf.company = %s
598 and pf.disabled = 0 and pfu.default=1""", (user, company), as_dict=1)
Anand Doshibd67e872014-04-11 16:51:27 +0530599
Nabin Haitc469f2c2017-04-03 13:01:11 +0530600 if not pos_profile:
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530601 pos_profile = frappe.db.sql("""select pf.*
602 from
603 `tabPOS Profile` pf left join `tabPOS Profile User` pfu
604 on
605 pf.name = pfu.parent
606 where
607 ifnull(pfu.user, '') = '' and pf.company = %s
608 and pf.disabled = 0""", (company), as_dict=1)
Anand Doshibd67e872014-04-11 16:51:27 +0530609
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530610 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +0530611
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530612def get_serial_nos_by_fifo(args, sales_order=None):
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530613 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
614 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530615 where item_code=%(item_code)s and warehouse=%(warehouse)s and
616 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
617 order by timestamp(purchase_date, purchase_time)
618 asc limit %(qty)s""",
619 {
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530620 "item_code": args.item_code,
621 "warehouse": args.warehouse,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530622 "qty": abs(cint(args.stock_qty)),
623 "sales_order": sales_order
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530624 }))
Nabin Hait08222152014-02-28 11:30:47 +0530625
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530626def get_serial_no_batchwise(args, sales_order=None):
Shreyaa20157a2018-04-13 12:03:42 +0530627 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
628 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530629 where item_code=%(item_code)s and warehouse=%(warehouse)s and
630 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
631 and batch_no=IF(%(batch_no)s IS NULL, batch_no, %(batch_no)s) order
632 by timestamp(purchase_date, purchase_time) asc limit %(qty)s""", {
Shreyaa20157a2018-04-13 12:03:42 +0530633 "item_code": args.item_code,
634 "warehouse": args.warehouse,
635 "batch_no": args.batch_no,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530636 "qty": abs(cint(args.stock_qty)),
637 "sales_order": sales_order
Shreyaa20157a2018-04-13 12:03:42 +0530638 }))
639
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530640@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530641def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530642 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530643 filters = {"parent": item_code, "uom": uom}
644 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +0530645 filters["parent"] = ("in", (item_code, variant_of))
Anand Doshie9baaa62014-02-26 12:35:33 +0530646 return {"conversion_factor": frappe.db.get_value("UOM Conversion Detail",
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530647 filters, "conversion_factor")}
Nabin Hait08222152014-02-28 11:30:47 +0530648
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530649@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530650def get_projected_qty(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530651 return {"projected_qty": frappe.db.get_value("Bin",
Nabin Hait436f5262014-02-10 14:47:54 +0530652 {"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
Nabin Hait08222152014-02-28 11:30:47 +0530653
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530654@frappe.whitelist()
Saurabhd3135532016-02-25 18:59:20 +0530655def get_bin_details(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530656 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Nabin Haita804d6d2018-08-29 13:34:58 +0530657 ["projected_qty", "actual_qty", "reserved_qty"], as_dict=True, cache=True) \
Shreya Shahbe770332018-08-22 14:45:22 +0530658 or {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530659
660@frappe.whitelist()
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530661def get_serial_no_details(item_code, warehouse, stock_qty, serial_no):
662 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "serial_no":serial_no})
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530663 serial_no = get_serial_no(args)
664 return {'serial_no': serial_no}
Rushabh Mehta985cb822016-12-30 15:06:54 +0530665
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530666@frappe.whitelist()
Shreyaa20157a2018-04-13 12:03:42 +0530667def get_bin_details_and_serial_nos(item_code, warehouse, has_batch_no, stock_qty=None, serial_no=None):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530668 bin_details_and_serial_nos = {}
669 bin_details_and_serial_nos.update(get_bin_details(item_code, warehouse))
Rushabh Mehta49f97472018-08-30 18:50:48 +0530670 if flt(stock_qty) > 0:
Shreyaa20157a2018-04-13 12:03:42 +0530671 if has_batch_no:
672 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty})
673 serial_no = get_serial_no(args)
674 bin_details_and_serial_nos.update({'serial_no': serial_no})
675 return bin_details_and_serial_nos
676
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530677 bin_details_and_serial_nos.update(get_serial_no_details(item_code, warehouse, stock_qty, serial_no))
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530678 return bin_details_and_serial_nos
Anand Doshidffec8f2014-07-01 17:45:15 +0530679
680@frappe.whitelist()
Shreyaa20157a2018-04-13 12:03:42 +0530681def get_batch_qty_and_serial_no(batch_no, stock_qty, warehouse, item_code, has_serial_no):
682 batch_qty_and_serial_no = {}
683 batch_qty_and_serial_no.update(get_batch_qty(batch_no, warehouse, item_code))
684
685 if (flt(batch_qty_and_serial_no.get('actual_batch_qty')) >= flt(stock_qty)) and has_serial_no:
686 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "batch_no":batch_no})
687 serial_no = get_serial_no(args)
688 batch_qty_and_serial_no.update({'serial_no': serial_no})
689 return batch_qty_and_serial_no
690
691@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530692def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +0700693 from erpnext.stock.doctype.batch import batch
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +0530694 if batch_no:
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530695 return {'actual_batch_qty': batch.get_batch_qty(batch_no, warehouse)}
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530696
Anand Doshidffec8f2014-07-01 17:45:15 +0530697@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530698def apply_price_list(args, as_doc=False):
699 """Apply pricelist on a document-like dict object and return as
700 {'parent': dict, 'children': list}
701
702 :param args: See below
703 :param as_doc: Updates value in the passed dict
704
Anand Doshidffec8f2014-07-01 17:45:15 +0530705 args = {
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530706 "doctype": "",
707 "name": "",
708 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
Anand Doshidffec8f2014-07-01 17:45:15 +0530709 "conversion_rate": 1.0,
710 "selling_price_list": None,
711 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530712 "price_list_uom_dependant": None,
Anand Doshidffec8f2014-07-01 17:45:15 +0530713 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530714 "doctype": "",
715 "name": "",
Anand Doshidffec8f2014-07-01 17:45:15 +0530716 "supplier": None,
717 "transaction_date": None,
718 "conversion_rate": 1.0,
719 "buying_price_list": None,
Anand Doshidffec8f2014-07-01 17:45:15 +0530720 "ignore_pricing_rule": 0/1
721 }
722 """
723 args = process_args(args)
724
725 parent = get_price_list_currency_and_exchange_rate(args)
726 children = []
727
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530728 if "items" in args:
729 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +0530730 args.update(parent)
731
732 for item in item_list:
733 args_copy = frappe._dict(args.copy())
734 args_copy.update(item)
735 item_details = apply_price_list_on_item(args_copy)
736 children.append(item_details)
737
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530738 if as_doc:
Shreya Shahb13a54a2017-12-06 19:17:04 +0530739 args.price_list_currency = parent.price_list_currency,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530740 args.plc_conversion_rate = parent.plc_conversion_rate
741 if args.get('items'):
742 for i, item in enumerate(args.get('items')):
743 for fieldname in children[i]:
744 # if the field exists in the original doc
745 # update the value
746 if fieldname in item and fieldname not in ("name", "doctype"):
747 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530748 return args
749 else:
750 return {
751 "parent": parent,
752 "children": children
753 }
Anand Doshidffec8f2014-07-01 17:45:15 +0530754
755def apply_price_list_on_item(args):
756 item_details = frappe._dict()
757 item_doc = frappe.get_doc("Item", args.item_code)
758 get_price_list_rate(args, item_doc, item_details)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530759
Anand Doshidffec8f2014-07-01 17:45:15 +0530760 item_details.update(get_pricing_rule_for_item(args))
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530761
Anand Doshidffec8f2014-07-01 17:45:15 +0530762 return item_details
763
764def get_price_list_currency(price_list):
Neil Trini Lasradoadb1b2c2015-03-18 11:40:39 +0530765 if price_list:
766 result = frappe.db.get_value("Price List", {"name": price_list,
767 "enabled": 1}, ["name", "currency"], as_dict=True)
Anand Doshidffec8f2014-07-01 17:45:15 +0530768
Neil Trini Lasradoadb1b2c2015-03-18 11:40:39 +0530769 if not result:
Rushabh Mehta985cb822016-12-30 15:06:54 +0530770 throw(_("Price List {0} is disabled or does not exist").format(price_list))
Anand Doshidffec8f2014-07-01 17:45:15 +0530771
Neil Trini Lasradoadb1b2c2015-03-18 11:40:39 +0530772 return result.currency
Anand Doshidffec8f2014-07-01 17:45:15 +0530773
Shreya Shahb13a54a2017-12-06 19:17:04 +0530774def get_price_list_uom_dependant(price_list):
775 if price_list:
776 result = frappe.db.get_value("Price List", {"name": price_list,
777 "enabled": 1}, ["name", "price_not_uom_dependant"], as_dict=True)
778
779 if not result:
780 throw(_("Price List {0} is disabled or does not exist").format(price_list))
781
782 return result.price_not_uom_dependant
783
784
Anand Doshidffec8f2014-07-01 17:45:15 +0530785def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +0530786 if not args.price_list:
787 return {}
788
Shreya3f778522018-05-15 16:59:20 +0530789 if args.doctype in ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']:
790 args.update({"exchange_rate": "for_selling"})
791 elif args.doctype in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']:
792 args.update({"exchange_rate": "for_buying"})
793
Anand Doshidffec8f2014-07-01 17:45:15 +0530794 price_list_currency = get_price_list_currency(args.price_list)
Shreya Shahb13a54a2017-12-06 19:17:04 +0530795 price_list_uom_dependant = get_price_list_uom_dependant(args.price_list)
Anand Doshidffec8f2014-07-01 17:45:15 +0530796 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +0100797 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +0530798
Nabin Haitdd82bf22015-05-11 16:49:17 +0530799 if (not plc_conversion_rate) or (price_list_currency and args.price_list_currency \
800 and price_list_currency != args.price_list_currency):
Rushabh Mehta6b537922017-03-14 16:59:11 +0530801 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
tundebabzy6e90f492018-02-12 10:48:57 +0100802 plc_conversion_rate = get_exchange_rate(price_list_currency, company_currency,
Shreya3f778522018-05-15 16:59:20 +0530803 args.transaction_date, args.exchange_rate) or plc_conversion_rate
Anand Doshidffec8f2014-07-01 17:45:15 +0530804
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530805 return frappe._dict({
Anand Doshidffec8f2014-07-01 17:45:15 +0530806 "price_list_currency": price_list_currency,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530807 "price_list_uom_dependant": price_list_uom_dependant,
Anand Doshidffec8f2014-07-01 17:45:15 +0530808 "plc_conversion_rate": plc_conversion_rate
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530809 })
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530810
811@frappe.whitelist()
812def get_default_bom(item_code=None):
813 if item_code:
814 bom = frappe.db.get_value("BOM", {"docstatus": 1, "is_default": 1, "is_active": 1, "item": item_code})
815 if bom:
816 return bom
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530817
Manas Solanki087a2252018-05-04 16:02:38 +0530818def get_valuation_rate(item_code, company, warehouse=None):
Manas Solankib16a4ec2018-05-04 16:49:33 +0530819 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530820 item_group = get_item_group_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +0530821 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +0530822 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +0530823 if not warehouse:
Shreya Shah3c9839f2018-07-17 18:01:44 +0530824 warehouse = item.get("default_warehouse") or item_group.get("default_warehouse")
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530825
826 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Saurabhbd01a812016-03-07 14:32:23 +0530827 ["valuation_rate"], as_dict=True) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530828
Manas Solankie3910fb2018-05-16 15:50:17 +0530829 elif not item.get("is_stock_item"):
Nabin Haitfe876c02017-03-06 16:32:57 +0530830 valuation_rate =frappe.db.sql("""select sum(base_net_amount) / sum(qty*conversion_factor)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530831 from `tabPurchase Invoice Item`
Saurabhbd01a812016-03-07 14:32:23 +0530832 where item_code = %s and docstatus=1""", item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530833
Saurabhbd01a812016-03-07 14:32:23 +0530834 if valuation_rate:
835 return {"valuation_rate": valuation_rate[0][0] or 0.0}
836 else:
837 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530838
Saurabh2d7af632016-02-26 11:09:20 +0530839def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +0530840 if out.valuation_rate:
841 out.update({
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530842 "gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)
Saurabh5ada14b2016-02-26 18:02:55 +0530843 })
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530844
Saurabhd3135532016-02-25 18:59:20 +0530845 return out
mbauskar6f603392016-01-21 16:10:22 +0530846
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530847@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530848def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +0530849 serial_no = None
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530850 if isinstance(args, string_types):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530851 args = json.loads(args)
852 args = frappe._dict(args)
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530853 if args.get('doctype') == 'Sales Invoice' and not args.get('update_stock'):
854 return ""
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530855 if args.get('warehouse') and args.get('stock_qty') and args.get('item_code'):
Shreyaa20157a2018-04-13 12:03:42 +0530856 has_serial_no = frappe.get_value('Item', {'item_code': args.item_code}, "has_serial_no")
Shreyaa20157a2018-04-13 12:03:42 +0530857 if args.get('batch_no') and has_serial_no == 1:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530858 return get_serial_no_batchwise(args, sales_order)
Shreyaa20157a2018-04-13 12:03:42 +0530859 elif has_serial_no == 1:
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530860 args = json.dumps({"item_code": args.get('item_code'),"warehouse": args.get('warehouse'),"stock_qty": args.get('stock_qty')})
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530861 args = process_args(args)
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530862 serial_no = get_serial_nos_by_fifo(args, sales_order)
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +0530863
864 if not serial_no and serial_nos:
865 # For POS
866 serial_no = serial_nos
867
868 return serial_no
Manas Solankie5e87f72018-05-28 20:07:08 +0530869
870
871def update_party_blanket_order(args, out):
872 blanket_order_details = get_blanket_order_details(args)
873 if blanket_order_details:
874 out.update(blanket_order_details)
875
876@frappe.whitelist()
877def get_blanket_order_details(args):
878 if isinstance(args, string_types):
879 args = frappe._dict(json.loads(args))
880
881 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +0530882 condition = ''
Manas Solankie5e87f72018-05-28 20:07:08 +0530883 if args.item_code:
884 if args.customer and args.doctype == "Sales Order":
Nabin Hait2737b082018-06-14 18:07:22 +0530885 condition = ' and bo.customer=%(customer)s'
Manas Solankie5e87f72018-05-28 20:07:08 +0530886 elif args.supplier and args.doctype == "Purchase Order":
Nabin Hait2737b082018-06-14 18:07:22 +0530887 condition = ' and bo.supplier=%(supplier)s'
Manas Solankie5e87f72018-05-28 20:07:08 +0530888 if args.blanket_order:
Nabin Hait2737b082018-06-14 18:07:22 +0530889 condition += ' and bo.name =%(blanket_order)s'
890 if args.transaction_date:
891 condition += ' and bo.to_date>=%(transaction_date)s'
892
Manas Solankie5e87f72018-05-28 20:07:08 +0530893 blanket_order_details = frappe.db.sql('''
894 select boi.rate as blanket_order_rate, bo.name as blanket_order
895 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
Nabin Hait2737b082018-06-14 18:07:22 +0530896 where bo.company=%(company)s and boi.item_code=%(item_code)s
897 and bo.docstatus=1 and bo.name = boi.parent {0}
898 '''.format(condition), args, as_dict=True)
899
Manas Solankie5e87f72018-05-28 20:07:08 +0530900 blanket_order_details = blanket_order_details[0] if blanket_order_details else ''
901 return blanket_order_details
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530902
903def get_so_reservation_for_item(args):
904 reserved_so = None
905 if args.get('against_sales_order'):
906 if get_reserved_qty_for_so(args.get('against_sales_order'), args.get('item_code')):
907 reserved_so = args.get('against_sales_order')
908 elif args.get('against_sales_invoice'):
909 sales_order = frappe.db.sql("""select sales_order from `tabSales Invoice Item` where
910 parent=%s and item_code=%s""", (args.get('against_sales_invoice'), args.get('item_code')))
911 if sales_order and sales_order[0]:
912 if get_reserved_qty_for_so(sales_order[0][0], args.get('item_code')):
913 reserved_so = sales_order[0]
914 elif args.get("sales_order"):
915 if get_reserved_qty_for_so(args.get('sales_order'), args.get('item_code')):
916 reserved_so = args.get('sales_order')
917 return reserved_so
918
919def get_reserved_qty_for_so(sales_order, item_code):
920 reserved_qty = frappe.db.sql("""select sum(qty) from `tabSales Order Item`
921 where parent=%s and item_code=%s and ensure_delivery_based_on_produced_serial_no=1
922 """, (sales_order, item_code))
923 if reserved_qty and reserved_qty[0][0]:
924 return reserved_qty[0][0]
925 else:
926 return 0