blob: 8b81972b4d18637c788f73e7b97f25d7fe8206a0 [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
Sagar Vora508189e2018-09-11 17:22:25 +053014from erpnext.stock.doctype.item.item import get_item_defaults, get_uom_conv_factor
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
Nabin Hait0d1ccc32019-02-14 18:30:10 +053019sales_doctypes = ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']
20purchase_doctypes = ['Material Request', 'Supplier Quotation', 'Purchase Order', 'Purchase Receipt', 'Purchase Invoice']
21
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053022@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +053023def get_item_details(args):
24 """
25 args = {
26 "item_code": "",
27 "warehouse": None,
28 "customer": "",
29 "conversion_rate": 1.0,
30 "selling_price_list": None,
31 "price_list_currency": None,
Nabin Hait615d3422014-02-25 19:01:20 +053032 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +053033 "doctype": "",
34 "name": "",
Nabin Hait436f5262014-02-10 14:47:54 +053035 "supplier": None,
36 "transaction_date": None,
37 "conversion_rate": 1.0,
38 "buying_price_list": None,
39 "is_subcontracted": "Yes" / "No",
Nabin Hait444f9562014-06-20 15:59:49 +053040 "ignore_pricing_rule": 0/1
Neil Trini Lasrado6e343e22016-03-09 17:02:59 +053041 "project": ""
Saif Ur Rehman2689dea2019-01-09 13:43:06 +050042 "set_warehouse": ""
Nabin Hait436f5262014-02-10 14:47:54 +053043 }
44 """
Anand Doshidffec8f2014-07-01 17:45:15 +053045 args = process_args(args)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053046 item = frappe.get_cached_doc("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053047 validate_item_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053048
Rushabh Mehta1a763742014-10-03 16:36:43 +053049 out = get_basic_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053050
Rushabh Mehta708e47a2018-08-08 16:37:31 +053051 get_party_item_code(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053052
Rushabh Mehta708e47a2018-08-08 16:37:31 +053053 set_valuation_rate(out, args)
Anand Doshibd67e872014-04-11 16:51:27 +053054
Manas Solankie5e87f72018-05-28 20:07:08 +053055 update_party_blanket_order(args, out)
56
Rushabh Mehta708e47a2018-08-08 16:37:31 +053057 get_price_list_rate(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053058
Rushabh Mehtab46069d2016-01-15 16:59:26 +053059 if args.customer and cint(args.is_pos):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +053060 out.update(get_pos_profile_item_details(args.company, args))
Rushabh Mehta6b537922017-03-14 16:59:11 +053061
Nabin Hait0287d312017-01-11 10:31:33 +053062 if out.get("warehouse"):
63 out.update(get_bin_details(args.item_code, out.warehouse))
Anand Doshibd67e872014-04-11 16:51:27 +053064
Nabin Haita3dd72a2014-05-28 12:49:20 +053065 # update args with out, if key or value not exists
Achilles Rasquinha714c7462018-02-15 11:28:55 +053066 for key, value in iteritems(out):
Nabin Haita3dd72a2014-05-28 12:49:20 +053067 if args.get(key) is None:
68 args[key] = value
69
Nabin Hait444f9562014-06-20 15:59:49 +053070 out.update(get_pricing_rule_for_item(args))
Rushabh Mehta708e47a2018-08-08 16:37:31 +053071
72 update_stock(args, out)
73
74 if args.transaction_date and item.lead_time_days:
75 out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
76 item.lead_time_days)
77
78 if args.get("is_subcontracted") == "Yes":
79 out.bom = args.get('bom') or get_default_bom(args.item_code)
80
81 get_gross_profit(out)
82 if args.doctype == 'Material Request':
83 out.rate = args.rate or out.price_list_rate
84 out.amount = flt(args.qty * out.rate)
85
86 return out
87
88def update_stock(args, out):
pratu16x7577e4c42017-06-23 11:39:03 +053089 if (args.get("doctype") == "Delivery Note" or
Nabin Hait3ce41d62017-05-03 18:22:24 +053090 (args.get("doctype") == "Sales Invoice" and args.get('update_stock'))) \
91 and out.warehouse and out.stock_qty > 0:
pratu16x7577e4c42017-06-23 11:39:03 +053092
Nabin Hait8fac2ad2017-05-18 11:54:24 +053093 if out.has_batch_no and not args.get("batch_no"):
Rushabh Mehta551406a2017-04-21 12:40:19 +053094 out.batch_no = get_batch_no(out.item_code, out.warehouse, out.qty)
rohitwaghchaure2fb8cc52017-11-29 13:50:04 +053095 actual_batch_qty = get_batch_qty(out.batch_no, out.warehouse, out.item_code)
96 if actual_batch_qty:
97 out.update(actual_batch_qty)
Shreya14bd43d2018-04-27 16:24:05 +053098
99 if out.has_serial_no and args.get('batch_no'):
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530100 reserved_so = get_so_reservation_for_item(args)
Shreya14bd43d2018-04-27 16:24:05 +0530101 out.batch_no = args.get('batch_no')
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530102 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Shreya14bd43d2018-04-27 16:24:05 +0530103
104 elif out.has_serial_no:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530105 reserved_so = get_so_reservation_for_item(args)
106 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Rushabh Mehta551406a2017-04-21 12:40:19 +0530107
Anand Doshibd67e872014-04-11 16:51:27 +0530108
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530109def set_valuation_rate(out, args):
Nabin Hait50238c32018-08-08 18:43:04 +0530110 if frappe.db.exists("Product Bundle", args.item_code, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530111 valuation_rate = 0.0
112 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530113
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530114 for bundle_item in bundled_items.items:
115 valuation_rate += \
116 flt(get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get("valuation_rate") \
117 * bundle_item.qty)
Anand Doshi70f57eb2015-11-27 14:37:40 +0530118
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530119 out.update({
120 "valuation_rate": valuation_rate
121 })
122
123 else:
124 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
125
Nabin Hait436f5262014-02-10 14:47:54 +0530126
Anand Doshidffec8f2014-07-01 17:45:15 +0530127def process_args(args):
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530128 if isinstance(args, string_types):
Anand Doshidffec8f2014-07-01 17:45:15 +0530129 args = json.loads(args)
130
131 args = frappe._dict(args)
132
Anand Doshidffec8f2014-07-01 17:45:15 +0530133 if not args.get("price_list"):
134 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
135
136 if args.barcode:
137 args.item_code = get_item_code(barcode=args.barcode)
138 elif not args.item_code and args.serial_no:
139 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530140
mbauskar6f603392016-01-21 16:10:22 +0530141 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530142 return args
143
tundebabzyacccdb32017-11-23 08:35:15 +0100144
Neil Trini Lasrado4abda672015-02-25 17:34:27 +0530145@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530146def get_item_code(barcode=None, serial_no=None):
147 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100148 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530149 if not item_code:
150 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530151 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530152 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530153 if not item_code:
154 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530155
Nabin Hait436f5262014-02-10 14:47:54 +0530156 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530157
tundebabzyacccdb32017-11-23 08:35:15 +0100158
Nabin Hait436f5262014-02-10 14:47:54 +0530159def validate_item_details(args, item):
160 if not args.company:
161 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530162
Nabin Hait436f5262014-02-10 14:47:54 +0530163 from erpnext.stock.doctype.item.item import validate_end_of_life
Anand Doshi21e09a22015-10-29 12:21:41 +0530164 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530165
tundebabzyacccdb32017-11-23 08:35:15 +0100166 if args.transaction_type == "selling" and cint(item.has_variants):
Umair Sayyed72534de2016-04-15 12:52:12 +0530167 throw(_("Item {0} is a template, please select one of its variants").format(item.name))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530168
tundebabzyacccdb32017-11-23 08:35:15 +0100169 elif args.transaction_type == "buying" and args.doctype != "Material Request":
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530170 if args.get("is_subcontracted") == "Yes" and item.is_sub_contracted_item != 1:
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530171 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530172
tundebabzyacccdb32017-11-23 08:35:15 +0100173
Rushabh Mehta1a763742014-10-03 16:36:43 +0530174def get_basic_details(args, item):
tundebabzyacccdb32017-11-23 08:35:15 +0100175 """
176 :param args: {
177 "item_code": "",
178 "warehouse": None,
179 "customer": "",
180 "conversion_rate": 1.0,
181 "selling_price_list": None,
182 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530183 "price_list_uom_dependant": None,
tundebabzyacccdb32017-11-23 08:35:15 +0100184 "plc_conversion_rate": 1.0,
185 "doctype": "",
186 "name": "",
187 "supplier": None,
188 "transaction_date": None,
189 "conversion_rate": 1.0,
190 "buying_price_list": None,
191 "is_subcontracted": "Yes" / "No",
192 "ignore_pricing_rule": 0/1
193 "project": "",
194 barcode: "",
195 serial_no: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100196 currency: "",
197 update_stock: "",
198 price_list: "",
199 company: "",
200 order_type: "",
201 is_pos: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100202 project: "",
203 qty: "",
204 stock_qty: "",
205 conversion_factor: ""
206 }
207 :param item: `item_code` of Item object
208 :return: frappe._dict
209 """
210
Rushabh Mehta1a763742014-10-03 16:36:43 +0530211 if not item:
212 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530213
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530214 if item.variant_of:
215 item.update_template_tables()
216
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530217 from frappe.defaults import get_user_default_as_list
Nabin Haitb6b56452015-12-23 16:37:00 +0530218 user_default_warehouse_list = get_user_default_as_list('Warehouse')
Nabin Hait436f5262014-02-10 14:47:54 +0530219 user_default_warehouse = user_default_warehouse_list[0] \
tundebabzyacccdb32017-11-23 08:35:15 +0100220 if len(user_default_warehouse_list) == 1 else ""
Manas Solanki64614372018-05-07 16:55:32 +0530221
Manas Solankib16a4ec2018-05-04 16:49:33 +0530222 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530223 item_group_defaults = get_item_group_defaults(item.name, args.company)
224
Saif Ur Rehman2689dea2019-01-09 13:43:06 +0500225 warehouse = args.get("set_warehouse") or user_default_warehouse or item_defaults.get("default_warehouse") or\
Shreya Shah3c9839f2018-07-17 18:01:44 +0530226 item_group_defaults.get("default_warehouse") or args.warehouse
Nabin Hait36028bf2014-02-12 19:09:28 +0530227
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530228 if args.get('doctype') == "Material Request" and not args.get('material_request_type'):
229 args['material_request_type'] = frappe.db.get_value('Material Request',
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530230 args.get('name'), 'material_request_type', cache=True)
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530231
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530232 #Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
233 if not args.uom:
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530234 if args.get('doctype') in sales_doctypes:
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530235 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530236 elif (args.get('doctype') in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']) or \
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530237 (args.get('doctype') == 'Material Request' and args.get('material_request_type') == 'Purchase'):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530238 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
239 else:
240 args.uom = item.stock_uom
241
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530242 out = frappe._dict({
Nabin Hait139dc7b2014-02-12 14:53:18 +0530243 "item_code": item.name,
244 "item_name": item.item_name,
Neil Trini Lasradoc48f06c2015-02-10 16:49:16 +0530245 "description": cstr(item.description).strip(),
246 "image": cstr(item.image).strip(),
Saurabhd3135532016-02-25 18:59:20 +0530247 "warehouse": warehouse,
Shreya Shah3c9839f2018-07-17 18:01:44 +0530248 "income_account": get_default_income_account(args, item_defaults, item_group_defaults),
249 "expense_account": get_default_expense_account(args, item_defaults, item_group_defaults),
250 "cost_center": get_default_cost_center(args, item_defaults, item_group_defaults),
Rushabh Mehta551406a2017-04-21 12:40:19 +0530251 'has_serial_no': item.has_serial_no,
252 'has_batch_no': item.has_batch_no,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530253 "batch_no": None,
Anand Doshibd67e872014-04-11 16:51:27 +0530254 "item_tax_rate": json.dumps(dict(([d.tax_type, d.tax_rate] for d in
Nabin Haite7d15362014-12-25 16:01:55 +0530255 item.get("taxes")))),
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530256 "uom": args.uom,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530257 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
Nabin Hait4a6c1782015-05-29 17:31:31 +0530258 "qty": args.qty or 1.0,
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530259 "stock_qty": args.qty or 1.0,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530260 "price_list_rate": 0.0,
261 "base_price_list_rate": 0.0,
262 "rate": 0.0,
263 "base_rate": 0.0,
264 "amount": 0.0,
265 "base_amount": 0.0,
Nabin Hait82e3e252015-02-23 16:58:30 +0530266 "net_rate": 0.0,
267 "net_amount": 0.0,
Saurabhc6dbe702015-10-19 14:17:52 +0530268 "discount_percentage": 0.0,
Shreya Shah3c9839f2018-07-17 18:01:44 +0530269 "supplier": get_default_supplier(args, item_defaults, item_group_defaults),
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530270 "update_stock": args.get("update_stock") if args.get('doctype') in ['Sales Invoice', 'Purchase Invoice'] else 0,
Rohit Waghchaurec858d522016-12-12 13:01:43 +0530271 "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 +0530272 "is_fixed_asset": item.is_fixed_asset,
273 "weight_per_unit":item.weight_per_unit,
274 "weight_uom":item.weight_uom,
Nabin Haite45ec662018-08-01 17:44:34 +0530275 "last_purchase_rate": item.last_purchase_rate if args.get("doctype") in ["Purchase Order"] else 0,
276 "transaction_date": args.get("transaction_date")
Nabin Hait139dc7b2014-02-12 14:53:18 +0530277 })
Anand Doshibd67e872014-04-11 16:51:27 +0530278
Zlash65627be1d2019-01-15 14:16:32 +0530279 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zlash6580f5cb02018-08-29 11:39:08 +0530280 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530281
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530282 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530283 if item.stock_uom == args.uom:
284 out.conversion_factor = 1.0
285 else:
286 out.conversion_factor = args.conversion_factor or \
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530287 get_conversion_factor(item.name, args.uom).get("conversion_factor")
mbauskar287fe812017-04-10 19:15:57 +0530288
289 args.conversion_factor = out.conversion_factor
290 out.stock_qty = out.qty * out.conversion_factor
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530291
Shreya Shah44fa9a62018-01-08 14:58:20 +0530292 # calculate last purchase rate
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530293 if args.get('doctype') in purchase_doctypes:
294 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
295 out.last_purchase_rate = item_last_purchase_rate(args.name, args.conversion_rate, item.name, out.conversion_factor)
Shreya Shah44fa9a62018-01-08 14:58:20 +0530296
Nabin Haitb09ed412015-02-17 10:33:58 +0530297 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530298 for d in [
299 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530300 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530301 ["Cost Center", "cost_center", "cost_center"],
302 ["Warehouse", "warehouse", ""]]:
Nabin Hait33df0b42018-05-26 09:09:02 +0530303 if not out[d[1]]:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530304 out[d[1]] = frappe.get_cached_value('Company', args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530305
Giovanni2144e022017-12-10 17:27:09 +0100306 for fieldname in ("item_name", "item_group", "barcodes", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530307 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530308
Nabin Hait436f5262014-02-10 14:47:54 +0530309 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530310
Zlash6580f5cb02018-08-29 11:39:08 +0530311@frappe.whitelist()
312def calculate_service_end_date(args, item=None):
313 args = process_args(args)
314 if not item:
315 item = frappe.get_cached_doc("Item", args.item_code)
316
Zlash65627be1d2019-01-15 14:16:32 +0530317 doctype = args.get("parenttype") or args.get("doctype")
Zlash65a3dd7982019-01-15 14:36:11 +0530318 if doctype == "Sales Invoice":
319 enable_deferred = "enable_deferred_revenue"
320 no_of_months = "no_of_months"
321 account = "deferred_revenue_account"
322 else:
323 enable_deferred = "enable_deferred_expense"
324 no_of_months = "no_of_months_exp"
325 account = "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530326
Zlash6580f5cb02018-08-29 11:39:08 +0530327 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
Zarrare83ff382018-09-21 15:45:40 +0530328 service_end_date = add_months(service_start_date, item.get(no_of_months))
Zlash6580f5cb02018-08-29 11:39:08 +0530329 deferred_detail = {
Zlash6580f5cb02018-08-29 11:39:08 +0530330 "service_start_date": service_start_date,
331 "service_end_date": service_end_date
332 }
Zarrare83ff382018-09-21 15:45:40 +0530333 deferred_detail[enable_deferred] = item.get(enable_deferred)
334 deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)
Zlash6580f5cb02018-08-29 11:39:08 +0530335
336 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100337
Shreya Shah3c9839f2018-07-17 18:01:44 +0530338def get_default_income_account(args, item, item_group):
Manas Solanki38667ab2018-05-16 16:55:23 +0530339 return (item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530340 or item_group.get("income_account")
341 or args.income_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530342
Shreya Shah3c9839f2018-07-17 18:01:44 +0530343def get_default_expense_account(args, item, item_group):
Manas Solanki38667ab2018-05-16 16:55:23 +0530344 return (item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530345 or item_group.get("expense_account")
346 or args.expense_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530347
Zarrare83ff382018-09-21 15:45:40 +0530348def get_default_deferred_account(args, item, fieldname=None):
Zlash65627be1d2019-01-15 14:16:32 +0530349 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zarrare83ff382018-09-21 15:45:40 +0530350 return (item.get(fieldname)
351 or args.get(fieldname)
352 or frappe.get_cached_value('Company', args.company, "default_"+fieldname))
Manas Solanki03938482018-05-14 16:16:46 +0530353 else:
354 return None
355
Shreya Shah3c9839f2018-07-17 18:01:44 +0530356def get_default_cost_center(args, item, item_group):
Nabin Hait50238c32018-08-08 18:43:04 +0530357 cost_center = None
358 if args.get('project'):
359 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530360
Nabin Hait50238c32018-08-08 18:43:04 +0530361 if not cost_center:
362 if args.get('customer'):
363 cost_center = item.get('selling_cost_center') or item_group.get('selling_cost_center')
364 else:
365 cost_center = item.get('buying_cost_center') or item_group.get('buying_cost_center')
Rushabh Mehta49f97472018-08-30 18:50:48 +0530366
Nabin Hait50238c32018-08-08 18:43:04 +0530367 return cost_center or args.get("cost_center")
Rushabh Mehta1a763742014-10-03 16:36:43 +0530368
Shreya Shah3c9839f2018-07-17 18:01:44 +0530369def get_default_supplier(args, item, item_group):
370 return (item.get("default_supplier")
371 or item_group.get("default_supplier"))
372
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530373def get_price_list_rate(args, item_doc, out):
Anand Doshi39a28912016-02-15 11:42:18 +0530374 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530375
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530376 if meta.get_field("currency") or args.get('currency'):
Nabin Hait158e7dc2019-01-04 11:04:37 +0530377 pl_details = get_price_list_currency_and_exchange_rate(args)
378 args.update(pl_details)
Nabin Hait436f5262014-02-10 14:47:54 +0530379 validate_price_list(args)
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530380 if meta.get_field("currency") and args.price_list:
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530381 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530382
Nabin Haite45ec662018-08-01 17:44:34 +0530383 price_list_rate = get_price_list_rate_for(args, item_doc.name) or 0
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530384
hiousi1516e292019-01-08 18:34:08 +0100385 # variant
386 if not price_list_rate and item_doc.variant_of:
387 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530388
389 # insert in database
Rushabh Mehta1a763742014-10-03 16:36:43 +0530390 if not price_list_rate:
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530391 if args.price_list and args.rate:
392 insert_item_price(args)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530393 return {}
Anand Doshibd67e872014-04-11 16:51:27 +0530394
Nabin Hait436f5262014-02-10 14:47:54 +0530395 out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) \
396 / flt(args.conversion_rate)
mbauskar287fe812017-04-10 19:15:57 +0530397
Nabin Hait34d28222016-01-19 15:45:49 +0530398 if not out.price_list_rate and args.transaction_type=="buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530399 from erpnext.stock.doctype.item.item import get_last_purchase_details
Anand Doshibd67e872014-04-11 16:51:27 +0530400 out.update(get_last_purchase_details(item_doc.name,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530401 args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530402
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530403def insert_item_price(args):
404 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530405 if frappe.db.get_value("Price List", args.price_list, "currency", cache=True) == args.currency \
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530406 and cint(frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")):
407 if frappe.has_permission("Item Price", "write"):
Nabin Haite45ec662018-08-01 17:44:34 +0530408 price_list_rate = (args.rate / args.get('conversion_factor')
409 if args.get("conversion_factor") else args.rate)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530410
Nabin Haitb479a872018-09-07 13:17:11 +0530411 item_price = frappe.db.get_value('Item Price',
412 {'item_code': args.item_code, 'price_list': args.price_list, 'currency': args.currency},
413 ['name', 'price_list_rate'], as_dict=1)
414 if item_price and item_price.name:
415 if item_price.price_list_rate != price_list_rate:
416 frappe.db.set_value('Item Price', item_price.name, "price_list_rate", price_list_rate)
417 frappe.msgprint(_("Item Price updated for {0} in Price List {1}").format(args.item_code,
418 args.price_list), alert=True)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530419 else:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530420 item_price = frappe.get_doc({
421 "doctype": "Item Price",
422 "price_list": args.price_list,
423 "item_code": args.item_code,
424 "currency": args.currency,
425 "price_list_rate": price_list_rate
426 })
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530427 item_price.insert()
428 frappe.msgprint(_("Item Price added for {0} in Price List {1}").format(args.item_code,
Rushabh Mehta49f97472018-08-30 18:50:48 +0530429 args.price_list), alert=True)
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530430
Nabin Hait01ca3e52019-01-25 16:25:15 +0530431def get_item_price(args, item_code, ignore_party=False):
Nabin Haite45ec662018-08-01 17:44:34 +0530432 """
433 Get name, price_list_rate from Item Price based on conditions
434 Check if the Derised qty is within the increment of the packing list.
435 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
436 optional fields min_qty, transaction_date, customer, supplier
437 :param item_code: str, Item Doctype field item_code
438 """
439
440 args['item_code'] = item_code
Nabin Haite45ec662018-08-01 17:44:34 +0530441
Nabin Hait01ca3e52019-01-25 16:25:15 +0530442 conditions = """where item_code=%(item_code)s
Nabin Haite45ec662018-08-01 17:44:34 +0530443 and price_list=%(price_list)s
444 and ifnull(uom, '') in ('', %(uom)s)"""
445
Nabin Hait01ca3e52019-01-25 16:25:15 +0530446 if not ignore_party:
Nabin Hait01ca3e52019-01-25 16:25:15 +0530447 if args.get("customer"):
448 conditions += " and customer=%(customer)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530449 elif args.get("supplier"):
Nabin Hait01ca3e52019-01-25 16:25:15 +0530450 conditions += " and supplier=%(supplier)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530451 else:
452 conditions += " and (customer is null or customer = '') and (supplier is null or supplier = '')"
Nabin Hait01ca3e52019-01-25 16:25:15 +0530453
Nabin Haite45ec662018-08-01 17:44:34 +0530454 if args.get('min_qty'):
455 conditions += " and ifnull(min_qty, 0) <= %(min_qty)s"
456
457 if args.get('transaction_date'):
458 conditions += """ and %(transaction_date)s between
459 ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
460
461 return frappe.db.sql(""" select name, price_list_rate, uom
462 from `tabItem Price` {conditions}
463 order by uom desc, min_qty desc """.format(conditions=conditions), args)
464
465def get_price_list_rate_for(args, item_code):
466 """
467 Return Price Rate based on min_qty of each Item Price Rate.\
468 For example, desired qty is 10 and Item Price Rates exists
469 for min_qty 9 and min_qty 20. It returns Item Price Rate for qty 9 as
470 the best fit in the range of avaliable min_qtyies
471
472 :param customer: link to Customer DocType
473 :param supplier: link to Supplier DocType
474 :param price_list: str (Standard Buying or Standard Selling)
475 :param item_code: str, Item Doctype field item_code
476 :param qty: Derised Qty
477 :param transaction_date: Date of the price
478 """
479 item_price_args = {
480 "item_code": item_code,
481 "price_list": args.get('price_list'),
482 "customer": args.get('customer'),
483 "supplier": args.get('supplier'),
484 "uom": args.get('uom'),
485 "min_qty": args.get('qty'),
486 "transaction_date": args.get('transaction_date'),
487 }
488
489 item_price_data = 0
490 price_list_rate = get_item_price(item_price_args, item_code)
491 if price_list_rate:
492 desired_qty = args.get("qty")
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530493 if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
Nabin Haite45ec662018-08-01 17:44:34 +0530494 item_price_data = price_list_rate
495 else:
496 for field in ["customer", "supplier", "min_qty"]:
497 del item_price_args[field]
498
Nabin Hait01ca3e52019-01-25 16:25:15 +0530499 general_price_list_rate = get_item_price(item_price_args, item_code, ignore_party=args.get("ignore_party"))
Nabin Haite45ec662018-08-01 17:44:34 +0530500 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
501 item_price_args["args"] = args.get("stock_uom")
Nabin Hait01ca3e52019-01-25 16:25:15 +0530502 general_price_list_rate = get_item_price(item_price_args, item_code, ignore_party=args.get("ignore_party"))
Nabin Haite45ec662018-08-01 17:44:34 +0530503
504 if general_price_list_rate:
505 item_price_data = general_price_list_rate
506
507 if item_price_data:
508 if item_price_data[0][2] == args.get("uom"):
509 return item_price_data[0][1]
510 elif not args.get('price_list_uom_dependant'):
511 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
512 else:
513 return item_price_data[0][1]
514
515def check_packing_list(price_list_rate_name, desired_qty, item_code):
516 """
517 Check if the Derised qty is within the increment of the packing list.
518 :param price_list_rate_name: Name of Item Price
519 :param desired_qty: Derised Qt
520 :param item_code: str, Item Doctype field item_code
521 :param qty: Derised Qt
522 """
523
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530524 flag = True
Nabin Haite45ec662018-08-01 17:44:34 +0530525 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530526 if item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +0530527 packing_increment = desired_qty % item_price.packing_unit
528
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530529 if packing_increment != 0:
530 flag = False
531
532 return flag
Rushabh Mehta1a763742014-10-03 16:36:43 +0530533
Nabin Hait436f5262014-02-10 14:47:54 +0530534def validate_price_list(args):
535 if args.get("price_list"):
Anand Doshibd67e872014-04-11 16:51:27 +0530536 if not frappe.db.get_value("Price List",
Nabin Hait34d28222016-01-19 15:45:49 +0530537 {"name": args.price_list, args.transaction_type: 1, "enabled": 1}):
Rushabh Mehta985cb822016-12-30 15:06:54 +0530538 throw(_("Price List {0} is disabled or does not exist").format(args.price_list))
mbauskar0b665ac2017-04-11 02:49:24 -0400539 elif not args.get("supplier"):
Nabin Hait436f5262014-02-10 14:47:54 +0530540 throw(_("Price List not selected"))
Anand Doshibd67e872014-04-11 16:51:27 +0530541
Nabin Hait436f5262014-02-10 14:47:54 +0530542def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +0530543 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +0530544
Anand Doshife13bfe2015-08-25 12:49:40 +0530545 if (not args.conversion_rate
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530546 and args.currency==frappe.get_cached_value('Company', args.company, "default_currency")):
Anand Doshife13bfe2015-08-25 12:49:40 +0530547 args.conversion_rate = 1.0
548
Nabin Hait436f5262014-02-10 14:47:54 +0530549 # validate currency conversion rate
Anand Doshibd67e872014-04-11 16:51:27 +0530550 validate_conversion_rate(args.currency, args.conversion_rate,
Nabin Hait436f5262014-02-10 14:47:54 +0530551 meta.get_label("conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530552
553 args.conversion_rate = flt(args.conversion_rate,
554 get_field_precision(meta.get_field("conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530555 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530556
Manas Solanki3504a232018-06-06 12:46:06 +0530557 if (not args.plc_conversion_rate
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530558 and args.price_list_currency==frappe.db.get_value("Price List", args.price_list, "currency", cache=True)):
Manas Solanki3504a232018-06-06 12:46:06 +0530559 args.plc_conversion_rate = 1.0
560
Nabin Hait436f5262014-02-10 14:47:54 +0530561 # validate price list currency conversion rate
562 if not args.get("price_list_currency"):
563 throw(_("Price List Currency not selected"))
564 else:
Anand Doshibd67e872014-04-11 16:51:27 +0530565 validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate,
Nabin Hait436f5262014-02-10 14:47:54 +0530566 meta.get_label("plc_conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530567
Nabin Hait158e7dc2019-01-04 11:04:37 +0530568 if meta.get_field("plc_conversion_rate"):
569 args.plc_conversion_rate = flt(args.plc_conversion_rate,
570 get_field_precision(meta.get_field("plc_conversion_rate"),
571 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530572
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530573def get_party_item_code(args, item_doc, out):
Nabin Hait34d28222016-01-19 15:45:49 +0530574 if args.transaction_type=="selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +0530575 out.customer_item_code = None
Nabin Hait79f091e2014-12-26 11:41:15 +0530576 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +0530577
578 if customer_item_code:
579 out.customer_item_code = customer_item_code[0].ref_code
580 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +0530581 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +0530582 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
583 if customer_group_item_code and not customer_group_item_code[0].customer_name:
584 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +0530585
Nabin Hait34d28222016-01-19 15:45:49 +0530586 if args.transaction_type=="buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +0530587 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +0530588 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +0530589
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530590def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530591 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +0530592
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530593 if not frappe.flags.pos_profile and not pos_profile:
594 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get('pos_profile'))
Anand Doshibd67e872014-04-11 16:51:27 +0530595
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530596 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +0530597 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530598 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530599 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530600
Nabin Hait436f5262014-02-10 14:47:54 +0530601 if res.get("warehouse"):
Saurabhd3135532016-02-25 18:59:20 +0530602 res.actual_qty = get_bin_details(args.item_code,
Nabin Hait436f5262014-02-10 14:47:54 +0530603 res.warehouse).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +0530604
Nabin Hait436f5262014-02-10 14:47:54 +0530605 return res
606
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530607@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530608def get_pos_profile(company, pos_profile=None, user=None):
Rohit Waghchauref7a83cb2019-04-05 00:42:48 +0530609 if pos_profile: return frappe.get_cached_doc('POS Profile', pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530610
611 if not user:
612 user = frappe.session['user']
613
Rohit Waghchauref7a83cb2019-04-05 00:42:48 +0530614 condition = "pfu.user = %(user)s AND pfu.default=1"
615 if user and company:
616 condition = "pfu.user = %(user)s AND pf.company = %(company)s AND pfu.default=1"
617
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530618 pos_profile = frappe.db.sql("""SELECT pf.*
619 FROM
620 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
621 ON
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530622 pf.name = pfu.parent
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530623 WHERE
Rohit Waghchauref7a83cb2019-04-05 00:42:48 +0530624 {cond} AND pf.disabled = 0
625 """.format(cond = condition), {
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530626 'user': user,
627 'company': company
628 }, as_dict=1)
Anand Doshibd67e872014-04-11 16:51:27 +0530629
Rohit Waghchauref7a83cb2019-04-05 00:42:48 +0530630 if not pos_profile and company:
631 pos_profile = frappe.db.sql("""SELECT pf.*
632 FROM
633 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
634 ON
635 pf.name = pfu.parent
636 WHERE
637 pf.company = %(company)s AND pf.disabled = 0
638 """, {
639 'company': company
640 }, as_dict=1)
641
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530642 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +0530643
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530644def get_serial_nos_by_fifo(args, sales_order=None):
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530645 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
646 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530647 where item_code=%(item_code)s and warehouse=%(warehouse)s and
648 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
649 order by timestamp(purchase_date, purchase_time)
650 asc limit %(qty)s""",
651 {
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530652 "item_code": args.item_code,
653 "warehouse": args.warehouse,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530654 "qty": abs(cint(args.stock_qty)),
655 "sales_order": sales_order
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530656 }))
Nabin Hait08222152014-02-28 11:30:47 +0530657
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530658def get_serial_no_batchwise(args, sales_order=None):
Shreyaa20157a2018-04-13 12:03:42 +0530659 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
660 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530661 where item_code=%(item_code)s and warehouse=%(warehouse)s and
662 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
663 and batch_no=IF(%(batch_no)s IS NULL, batch_no, %(batch_no)s) order
664 by timestamp(purchase_date, purchase_time) asc limit %(qty)s""", {
Shreyaa20157a2018-04-13 12:03:42 +0530665 "item_code": args.item_code,
666 "warehouse": args.warehouse,
667 "batch_no": args.batch_no,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530668 "qty": abs(cint(args.stock_qty)),
669 "sales_order": sales_order
Shreyaa20157a2018-04-13 12:03:42 +0530670 }))
671
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530672@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530673def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530674 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530675 filters = {"parent": item_code, "uom": uom}
676 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +0530677 filters["parent"] = ("in", (item_code, variant_of))
Sagar Vora508189e2018-09-11 17:22:25 +0530678 conversion_factor = frappe.db.get_value("UOM Conversion Detail",
679 filters, "conversion_factor")
680 if not conversion_factor:
681 stock_uom = frappe.db.get_value("Item", item_code, "stock_uom")
682 conversion_factor = get_uom_conv_factor(uom, stock_uom)
rohitwaghchaureffdadbf2019-01-08 16:21:25 +0530683 return {"conversion_factor": conversion_factor or 1.0}
Nabin Hait08222152014-02-28 11:30:47 +0530684
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530685@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530686def get_projected_qty(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530687 return {"projected_qty": frappe.db.get_value("Bin",
Nabin Hait436f5262014-02-10 14:47:54 +0530688 {"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
Nabin Hait08222152014-02-28 11:30:47 +0530689
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530690@frappe.whitelist()
Saurabhd3135532016-02-25 18:59:20 +0530691def get_bin_details(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530692 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Nabin Haita804d6d2018-08-29 13:34:58 +0530693 ["projected_qty", "actual_qty", "reserved_qty"], as_dict=True, cache=True) \
Shreya Shahbe770332018-08-22 14:45:22 +0530694 or {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530695
696@frappe.whitelist()
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530697def get_serial_no_details(item_code, warehouse, stock_qty, serial_no):
698 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "serial_no":serial_no})
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530699 serial_no = get_serial_no(args)
700 return {'serial_no': serial_no}
Rushabh Mehta985cb822016-12-30 15:06:54 +0530701
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530702@frappe.whitelist()
Shreyaa20157a2018-04-13 12:03:42 +0530703def 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 +0530704 bin_details_and_serial_nos = {}
705 bin_details_and_serial_nos.update(get_bin_details(item_code, warehouse))
Rushabh Mehta49f97472018-08-30 18:50:48 +0530706 if flt(stock_qty) > 0:
Shreyaa20157a2018-04-13 12:03:42 +0530707 if has_batch_no:
708 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty})
709 serial_no = get_serial_no(args)
710 bin_details_and_serial_nos.update({'serial_no': serial_no})
711 return bin_details_and_serial_nos
712
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530713 bin_details_and_serial_nos.update(get_serial_no_details(item_code, warehouse, stock_qty, serial_no))
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530714 return bin_details_and_serial_nos
Anand Doshidffec8f2014-07-01 17:45:15 +0530715
716@frappe.whitelist()
Shreyaa20157a2018-04-13 12:03:42 +0530717def get_batch_qty_and_serial_no(batch_no, stock_qty, warehouse, item_code, has_serial_no):
718 batch_qty_and_serial_no = {}
719 batch_qty_and_serial_no.update(get_batch_qty(batch_no, warehouse, item_code))
720
721 if (flt(batch_qty_and_serial_no.get('actual_batch_qty')) >= flt(stock_qty)) and has_serial_no:
722 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "batch_no":batch_no})
723 serial_no = get_serial_no(args)
724 batch_qty_and_serial_no.update({'serial_no': serial_no})
725 return batch_qty_and_serial_no
726
727@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530728def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +0700729 from erpnext.stock.doctype.batch import batch
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +0530730 if batch_no:
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530731 return {'actual_batch_qty': batch.get_batch_qty(batch_no, warehouse)}
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530732
Anand Doshidffec8f2014-07-01 17:45:15 +0530733@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530734def apply_price_list(args, as_doc=False):
735 """Apply pricelist on a document-like dict object and return as
736 {'parent': dict, 'children': list}
737
738 :param args: See below
739 :param as_doc: Updates value in the passed dict
740
Anand Doshidffec8f2014-07-01 17:45:15 +0530741 args = {
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530742 "doctype": "",
743 "name": "",
744 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
Anand Doshidffec8f2014-07-01 17:45:15 +0530745 "conversion_rate": 1.0,
746 "selling_price_list": None,
747 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530748 "price_list_uom_dependant": None,
Anand Doshidffec8f2014-07-01 17:45:15 +0530749 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530750 "doctype": "",
751 "name": "",
Anand Doshidffec8f2014-07-01 17:45:15 +0530752 "supplier": None,
753 "transaction_date": None,
754 "conversion_rate": 1.0,
755 "buying_price_list": None,
Anand Doshidffec8f2014-07-01 17:45:15 +0530756 "ignore_pricing_rule": 0/1
757 }
758 """
759 args = process_args(args)
760
761 parent = get_price_list_currency_and_exchange_rate(args)
762 children = []
763
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530764 if "items" in args:
765 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +0530766 args.update(parent)
767
768 for item in item_list:
769 args_copy = frappe._dict(args.copy())
770 args_copy.update(item)
771 item_details = apply_price_list_on_item(args_copy)
772 children.append(item_details)
773
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530774 if as_doc:
Shreya Shahb13a54a2017-12-06 19:17:04 +0530775 args.price_list_currency = parent.price_list_currency,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530776 args.plc_conversion_rate = parent.plc_conversion_rate
777 if args.get('items'):
778 for i, item in enumerate(args.get('items')):
779 for fieldname in children[i]:
780 # if the field exists in the original doc
781 # update the value
782 if fieldname in item and fieldname not in ("name", "doctype"):
783 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530784 return args
785 else:
786 return {
787 "parent": parent,
788 "children": children
789 }
Anand Doshidffec8f2014-07-01 17:45:15 +0530790
791def apply_price_list_on_item(args):
792 item_details = frappe._dict()
793 item_doc = frappe.get_doc("Item", args.item_code)
794 get_price_list_rate(args, item_doc, item_details)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530795
Anand Doshidffec8f2014-07-01 17:45:15 +0530796 item_details.update(get_pricing_rule_for_item(args))
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530797
Anand Doshidffec8f2014-07-01 17:45:15 +0530798 return item_details
799
800def get_price_list_currency(price_list):
Neil Trini Lasradoadb1b2c2015-03-18 11:40:39 +0530801 if price_list:
802 result = frappe.db.get_value("Price List", {"name": price_list,
803 "enabled": 1}, ["name", "currency"], as_dict=True)
Anand Doshidffec8f2014-07-01 17:45:15 +0530804
Neil Trini Lasradoadb1b2c2015-03-18 11:40:39 +0530805 if not result:
Rushabh Mehta985cb822016-12-30 15:06:54 +0530806 throw(_("Price List {0} is disabled or does not exist").format(price_list))
Anand Doshidffec8f2014-07-01 17:45:15 +0530807
Neil Trini Lasradoadb1b2c2015-03-18 11:40:39 +0530808 return result.currency
Anand Doshidffec8f2014-07-01 17:45:15 +0530809
Shreya Shahb13a54a2017-12-06 19:17:04 +0530810def get_price_list_uom_dependant(price_list):
811 if price_list:
812 result = frappe.db.get_value("Price List", {"name": price_list,
813 "enabled": 1}, ["name", "price_not_uom_dependant"], as_dict=True)
814
815 if not result:
816 throw(_("Price List {0} is disabled or does not exist").format(price_list))
817
Nabin Hait158e7dc2019-01-04 11:04:37 +0530818 return not result.price_not_uom_dependant
Shreya Shahb13a54a2017-12-06 19:17:04 +0530819
820
Anand Doshidffec8f2014-07-01 17:45:15 +0530821def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +0530822 if not args.price_list:
823 return {}
824
Shreya3f778522018-05-15 16:59:20 +0530825 if args.doctype in ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']:
826 args.update({"exchange_rate": "for_selling"})
827 elif args.doctype in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']:
828 args.update({"exchange_rate": "for_buying"})
829
Anand Doshidffec8f2014-07-01 17:45:15 +0530830 price_list_currency = get_price_list_currency(args.price_list)
Shreya Shahb13a54a2017-12-06 19:17:04 +0530831 price_list_uom_dependant = get_price_list_uom_dependant(args.price_list)
Anand Doshidffec8f2014-07-01 17:45:15 +0530832 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +0100833 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +0530834
Nabin Haitdd82bf22015-05-11 16:49:17 +0530835 if (not plc_conversion_rate) or (price_list_currency and args.price_list_currency \
836 and price_list_currency != args.price_list_currency):
Rushabh Mehta6b537922017-03-14 16:59:11 +0530837 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
tundebabzy6e90f492018-02-12 10:48:57 +0100838 plc_conversion_rate = get_exchange_rate(price_list_currency, company_currency,
Shreya3f778522018-05-15 16:59:20 +0530839 args.transaction_date, args.exchange_rate) or plc_conversion_rate
Anand Doshidffec8f2014-07-01 17:45:15 +0530840
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530841 return frappe._dict({
Anand Doshidffec8f2014-07-01 17:45:15 +0530842 "price_list_currency": price_list_currency,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530843 "price_list_uom_dependant": price_list_uom_dependant,
Anand Doshidffec8f2014-07-01 17:45:15 +0530844 "plc_conversion_rate": plc_conversion_rate
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530845 })
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530846
847@frappe.whitelist()
848def get_default_bom(item_code=None):
849 if item_code:
850 bom = frappe.db.get_value("BOM", {"docstatus": 1, "is_default": 1, "is_active": 1, "item": item_code})
851 if bom:
852 return bom
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530853
Manas Solanki087a2252018-05-04 16:02:38 +0530854def get_valuation_rate(item_code, company, warehouse=None):
Manas Solankib16a4ec2018-05-04 16:49:33 +0530855 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530856 item_group = get_item_group_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +0530857 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +0530858 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +0530859 if not warehouse:
Shreya Shah3c9839f2018-07-17 18:01:44 +0530860 warehouse = item.get("default_warehouse") or item_group.get("default_warehouse")
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530861
862 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Saurabhbd01a812016-03-07 14:32:23 +0530863 ["valuation_rate"], as_dict=True) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530864
Manas Solankie3910fb2018-05-16 15:50:17 +0530865 elif not item.get("is_stock_item"):
Nabin Haitfe876c02017-03-06 16:32:57 +0530866 valuation_rate =frappe.db.sql("""select sum(base_net_amount) / sum(qty*conversion_factor)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530867 from `tabPurchase Invoice Item`
Saurabhbd01a812016-03-07 14:32:23 +0530868 where item_code = %s and docstatus=1""", item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530869
Saurabhbd01a812016-03-07 14:32:23 +0530870 if valuation_rate:
871 return {"valuation_rate": valuation_rate[0][0] or 0.0}
872 else:
873 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530874
Saurabh2d7af632016-02-26 11:09:20 +0530875def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +0530876 if out.valuation_rate:
877 out.update({
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530878 "gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)
Saurabh5ada14b2016-02-26 18:02:55 +0530879 })
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530880
Saurabhd3135532016-02-25 18:59:20 +0530881 return out
mbauskar6f603392016-01-21 16:10:22 +0530882
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530883@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530884def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +0530885 serial_no = None
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530886 if isinstance(args, string_types):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530887 args = json.loads(args)
888 args = frappe._dict(args)
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530889 if args.get('doctype') == 'Sales Invoice' and not args.get('update_stock'):
890 return ""
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530891 if args.get('warehouse') and args.get('stock_qty') and args.get('item_code'):
Shreyaa20157a2018-04-13 12:03:42 +0530892 has_serial_no = frappe.get_value('Item', {'item_code': args.item_code}, "has_serial_no")
Shreyaa20157a2018-04-13 12:03:42 +0530893 if args.get('batch_no') and has_serial_no == 1:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530894 return get_serial_no_batchwise(args, sales_order)
Shreyaa20157a2018-04-13 12:03:42 +0530895 elif has_serial_no == 1:
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530896 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 +0530897 args = process_args(args)
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530898 serial_no = get_serial_nos_by_fifo(args, sales_order)
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +0530899
900 if not serial_no and serial_nos:
901 # For POS
902 serial_no = serial_nos
903
904 return serial_no
Manas Solankie5e87f72018-05-28 20:07:08 +0530905
906
907def update_party_blanket_order(args, out):
908 blanket_order_details = get_blanket_order_details(args)
909 if blanket_order_details:
910 out.update(blanket_order_details)
911
912@frappe.whitelist()
913def get_blanket_order_details(args):
914 if isinstance(args, string_types):
915 args = frappe._dict(json.loads(args))
916
917 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +0530918 condition = ''
Manas Solankie5e87f72018-05-28 20:07:08 +0530919 if args.item_code:
920 if args.customer and args.doctype == "Sales Order":
Nabin Hait2737b082018-06-14 18:07:22 +0530921 condition = ' and bo.customer=%(customer)s'
Manas Solankie5e87f72018-05-28 20:07:08 +0530922 elif args.supplier and args.doctype == "Purchase Order":
Nabin Hait2737b082018-06-14 18:07:22 +0530923 condition = ' and bo.supplier=%(supplier)s'
Manas Solankie5e87f72018-05-28 20:07:08 +0530924 if args.blanket_order:
Nabin Hait2737b082018-06-14 18:07:22 +0530925 condition += ' and bo.name =%(blanket_order)s'
926 if args.transaction_date:
927 condition += ' and bo.to_date>=%(transaction_date)s'
928
Manas Solankie5e87f72018-05-28 20:07:08 +0530929 blanket_order_details = frappe.db.sql('''
930 select boi.rate as blanket_order_rate, bo.name as blanket_order
931 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
Nabin Hait2737b082018-06-14 18:07:22 +0530932 where bo.company=%(company)s and boi.item_code=%(item_code)s
933 and bo.docstatus=1 and bo.name = boi.parent {0}
934 '''.format(condition), args, as_dict=True)
935
Manas Solankie5e87f72018-05-28 20:07:08 +0530936 blanket_order_details = blanket_order_details[0] if blanket_order_details else ''
937 return blanket_order_details
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530938
939def get_so_reservation_for_item(args):
940 reserved_so = None
941 if args.get('against_sales_order'):
942 if get_reserved_qty_for_so(args.get('against_sales_order'), args.get('item_code')):
943 reserved_so = args.get('against_sales_order')
944 elif args.get('against_sales_invoice'):
945 sales_order = frappe.db.sql("""select sales_order from `tabSales Invoice Item` where
946 parent=%s and item_code=%s""", (args.get('against_sales_invoice'), args.get('item_code')))
947 if sales_order and sales_order[0]:
948 if get_reserved_qty_for_so(sales_order[0][0], args.get('item_code')):
949 reserved_so = sales_order[0]
950 elif args.get("sales_order"):
951 if get_reserved_qty_for_so(args.get('sales_order'), args.get('item_code')):
952 reserved_so = args.get('sales_order')
953 return reserved_so
954
955def get_reserved_qty_for_so(sales_order, item_code):
956 reserved_qty = frappe.db.sql("""select sum(qty) from `tabSales Order Item`
957 where parent=%s and item_code=%s and ensure_delivery_based_on_produced_serial_no=1
958 """, (sales_order, item_code))
959 if reserved_qty and reserved_qty[0][0]:
960 return reserved_qty[0][0]
961 else:
962 return 0