blob: 9f47edc7740bc66ee16dc917b65defc3c6795e8b [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
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +05308import json, copy
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
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053015from erpnext.stock.doctype.price_list.price_list import get_price_list_details
Shreya Shah3c9839f2018-07-17 18:01:44 +053016from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +050017from erpnext.setup.doctype.brand.brand import get_brand_defaults
Rohit Waghchaure3cf24362019-06-02 16:03:05 +053018from erpnext.stock.doctype.item_manufacturer.item_manufacturer import get_item_manufacturer_part_no
Nabin Hait98c2a052014-05-05 18:41:41 +053019
Achilles Rasquinha714c7462018-02-15 11:28:55 +053020from six import string_types, iteritems
tundebabzyacccdb32017-11-23 08:35:15 +010021
Nabin Hait0d1ccc32019-02-14 18:30:10 +053022sales_doctypes = ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']
23purchase_doctypes = ['Material Request', 'Supplier Quotation', 'Purchase Order', 'Purchase Receipt', 'Purchase Invoice']
24
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053025@frappe.whitelist()
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053026def get_item_details(args, doc=None, for_validate=False, overwrite_warehouse=True):
Nabin Hait436f5262014-02-10 14:47:54 +053027 """
28 args = {
29 "item_code": "",
30 "warehouse": None,
31 "customer": "",
32 "conversion_rate": 1.0,
33 "selling_price_list": None,
34 "price_list_currency": None,
Nabin Hait615d3422014-02-25 19:01:20 +053035 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +053036 "doctype": "",
37 "name": "",
Nabin Hait436f5262014-02-10 14:47:54 +053038 "supplier": None,
39 "transaction_date": None,
40 "conversion_rate": 1.0,
41 "buying_price_list": None,
42 "is_subcontracted": "Yes" / "No",
Nabin Hait444f9562014-06-20 15:59:49 +053043 "ignore_pricing_rule": 0/1
Neil Trini Lasrado6e343e22016-03-09 17:02:59 +053044 "project": ""
Saif Ur Rehman2689dea2019-01-09 13:43:06 +050045 "set_warehouse": ""
Nabin Hait436f5262014-02-10 14:47:54 +053046 }
47 """
Suraj Shetty182f4de2019-08-16 08:16:22 +053048
Anand Doshidffec8f2014-07-01 17:45:15 +053049 args = process_args(args)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053050 item = frappe.get_cached_doc("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053051 validate_item_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053052
Suraj Shetty182f4de2019-08-16 08:16:22 +053053 out = get_basic_details(args, item, overwrite_warehouse)
54
Saif Ur Rehman67786682018-12-27 02:11:07 +050055 get_item_tax_template(args, item, out)
Saif Ur Rehman648bd152019-01-03 03:48:01 +050056 out["item_tax_rate"] = get_item_tax_map(args.company, args.get("item_tax_template") if out.get("item_tax_template") is None \
57 else out.get("item_tax_template"), as_json=True)
Saif Ur Rehman67786682018-12-27 02:11:07 +050058
Rushabh Mehta708e47a2018-08-08 16:37:31 +053059 get_party_item_code(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053060
Rushabh Mehta708e47a2018-08-08 16:37:31 +053061 set_valuation_rate(out, args)
Anand Doshibd67e872014-04-11 16:51:27 +053062
Manas Solankie5e87f72018-05-28 20:07:08 +053063 update_party_blanket_order(args, out)
64
Rushabh Mehta708e47a2018-08-08 16:37:31 +053065 get_price_list_rate(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053066
Rushabh Mehtab46069d2016-01-15 16:59:26 +053067 if args.customer and cint(args.is_pos):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +053068 out.update(get_pos_profile_item_details(args.company, args))
Rushabh Mehta6b537922017-03-14 16:59:11 +053069
Nabin Hait0287d312017-01-11 10:31:33 +053070 if out.get("warehouse"):
71 out.update(get_bin_details(args.item_code, out.warehouse))
Anand Doshibd67e872014-04-11 16:51:27 +053072
Nabin Haita3dd72a2014-05-28 12:49:20 +053073 # update args with out, if key or value not exists
Achilles Rasquinha714c7462018-02-15 11:28:55 +053074 for key, value in iteritems(out):
Nabin Haita3dd72a2014-05-28 12:49:20 +053075 if args.get(key) is None:
76 args[key] = value
77
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053078 data = get_pricing_rule_for_item(args, out.price_list_rate,
79 doc, for_validate=for_validate)
80
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +053081 out.update(data)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053082
83 update_stock(args, out)
84
85 if args.transaction_date and item.lead_time_days:
86 out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
87 item.lead_time_days)
88
89 if args.get("is_subcontracted") == "Yes":
90 out.bom = args.get('bom') or get_default_bom(args.item_code)
91
92 get_gross_profit(out)
93 if args.doctype == 'Material Request':
94 out.rate = args.rate or out.price_list_rate
95 out.amount = flt(args.qty * out.rate)
96
97 return out
98
99def update_stock(args, out):
pratu16x7577e4c42017-06-23 11:39:03 +0530100 if (args.get("doctype") == "Delivery Note" or
Nabin Hait3ce41d62017-05-03 18:22:24 +0530101 (args.get("doctype") == "Sales Invoice" and args.get('update_stock'))) \
102 and out.warehouse and out.stock_qty > 0:
pratu16x7577e4c42017-06-23 11:39:03 +0530103
Nabin Hait8fac2ad2017-05-18 11:54:24 +0530104 if out.has_batch_no and not args.get("batch_no"):
Rushabh Mehta551406a2017-04-21 12:40:19 +0530105 out.batch_no = get_batch_no(out.item_code, out.warehouse, out.qty)
rohitwaghchaure2fb8cc52017-11-29 13:50:04 +0530106 actual_batch_qty = get_batch_qty(out.batch_no, out.warehouse, out.item_code)
107 if actual_batch_qty:
108 out.update(actual_batch_qty)
Shreya14bd43d2018-04-27 16:24:05 +0530109
110 if out.has_serial_no and args.get('batch_no'):
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530111 reserved_so = get_so_reservation_for_item(args)
Shreya14bd43d2018-04-27 16:24:05 +0530112 out.batch_no = args.get('batch_no')
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530113 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Shreya14bd43d2018-04-27 16:24:05 +0530114
115 elif out.has_serial_no:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530116 reserved_so = get_so_reservation_for_item(args)
117 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Rushabh Mehta551406a2017-04-21 12:40:19 +0530118
Anand Doshibd67e872014-04-11 16:51:27 +0530119
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530120def set_valuation_rate(out, args):
Nabin Hait50238c32018-08-08 18:43:04 +0530121 if frappe.db.exists("Product Bundle", args.item_code, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530122 valuation_rate = 0.0
123 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530124
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530125 for bundle_item in bundled_items.items:
126 valuation_rate += \
127 flt(get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get("valuation_rate") \
128 * bundle_item.qty)
Anand Doshi70f57eb2015-11-27 14:37:40 +0530129
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530130 out.update({
131 "valuation_rate": valuation_rate
132 })
133
134 else:
135 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
136
Nabin Hait436f5262014-02-10 14:47:54 +0530137
Anand Doshidffec8f2014-07-01 17:45:15 +0530138def process_args(args):
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530139 if isinstance(args, string_types):
Anand Doshidffec8f2014-07-01 17:45:15 +0530140 args = json.loads(args)
141
142 args = frappe._dict(args)
143
Anand Doshidffec8f2014-07-01 17:45:15 +0530144 if not args.get("price_list"):
145 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
146
147 if args.barcode:
148 args.item_code = get_item_code(barcode=args.barcode)
149 elif not args.item_code and args.serial_no:
150 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530151
mbauskar6f603392016-01-21 16:10:22 +0530152 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530153 return args
154
tundebabzyacccdb32017-11-23 08:35:15 +0100155
Neil Trini Lasrado4abda672015-02-25 17:34:27 +0530156@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530157def get_item_code(barcode=None, serial_no=None):
158 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100159 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530160 if not item_code:
161 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530162 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530163 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530164 if not item_code:
165 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530166
Nabin Hait436f5262014-02-10 14:47:54 +0530167 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530168
tundebabzyacccdb32017-11-23 08:35:15 +0100169
Nabin Hait436f5262014-02-10 14:47:54 +0530170def validate_item_details(args, item):
171 if not args.company:
172 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530173
Nabin Hait436f5262014-02-10 14:47:54 +0530174 from erpnext.stock.doctype.item.item import validate_end_of_life
Anand Doshi21e09a22015-10-29 12:21:41 +0530175 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530176
tundebabzyacccdb32017-11-23 08:35:15 +0100177 if args.transaction_type == "selling" and cint(item.has_variants):
Umair Sayyed72534de2016-04-15 12:52:12 +0530178 throw(_("Item {0} is a template, please select one of its variants").format(item.name))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530179
tundebabzyacccdb32017-11-23 08:35:15 +0100180 elif args.transaction_type == "buying" and args.doctype != "Material Request":
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530181 if args.get("is_subcontracted") == "Yes" and item.is_sub_contracted_item != 1:
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530182 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530183
tundebabzyacccdb32017-11-23 08:35:15 +0100184
Suraj Shetty182f4de2019-08-16 08:16:22 +0530185def get_basic_details(args, item, overwrite_warehouse=True):
tundebabzyacccdb32017-11-23 08:35:15 +0100186 """
187 :param args: {
188 "item_code": "",
189 "warehouse": None,
190 "customer": "",
191 "conversion_rate": 1.0,
192 "selling_price_list": None,
193 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530194 "price_list_uom_dependant": None,
tundebabzyacccdb32017-11-23 08:35:15 +0100195 "plc_conversion_rate": 1.0,
196 "doctype": "",
197 "name": "",
198 "supplier": None,
199 "transaction_date": None,
200 "conversion_rate": 1.0,
201 "buying_price_list": None,
202 "is_subcontracted": "Yes" / "No",
203 "ignore_pricing_rule": 0/1
204 "project": "",
205 barcode: "",
206 serial_no: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100207 currency: "",
208 update_stock: "",
209 price_list: "",
210 company: "",
211 order_type: "",
212 is_pos: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100213 project: "",
214 qty: "",
215 stock_qty: "",
216 conversion_factor: ""
217 }
218 :param item: `item_code` of Item object
219 :return: frappe._dict
220 """
221
Rushabh Mehta1a763742014-10-03 16:36:43 +0530222 if not item:
223 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530224
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530225 if item.variant_of:
226 item.update_template_tables()
227
Manas Solankib16a4ec2018-05-04 16:49:33 +0530228 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530229 item_group_defaults = get_item_group_defaults(item.name, args.company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500230 brand_defaults = get_brand_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530231
Suraj Shetty182f4de2019-08-16 08:16:22 +0530232 if overwrite_warehouse or not args.warehouse:
233 warehouse = (
234 args.get("set_warehouse") or
235 item_defaults.get("default_warehouse") or
236 item_group_defaults.get("default_warehouse") or
237 brand_defaults.get("default_warehouse") or
238 args.warehouse
239 )
Rohit Waghchaurec41118b2019-05-21 15:19:03 +0530240
Suraj Shetty182f4de2019-08-16 08:16:22 +0530241 if not warehouse:
242 defaults = frappe.defaults.get_defaults() or {}
243 warehouse_exists = frappe.db.exists("Warehouse", {
244 'name': defaults.default_warehouse,
245 'company': args.company
246 })
247 if defaults.get("default_warehouse") and warehouse_exists:
248 warehouse = defaults.default_warehouse
249
250 else:
251 warehouse = args.warehouse
Nabin Hait36028bf2014-02-12 19:09:28 +0530252
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530253 if args.get('doctype') == "Material Request" and not args.get('material_request_type'):
254 args['material_request_type'] = frappe.db.get_value('Material Request',
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530255 args.get('name'), 'material_request_type', cache=True)
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530256
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530257 #Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
258 if not args.uom:
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530259 if args.get('doctype') in sales_doctypes:
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530260 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530261 elif (args.get('doctype') in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']) or \
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530262 (args.get('doctype') == 'Material Request' and args.get('material_request_type') == 'Purchase'):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530263 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
264 else:
265 args.uom = item.stock_uom
266
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530267 out = frappe._dict({
Nabin Hait139dc7b2014-02-12 14:53:18 +0530268 "item_code": item.name,
269 "item_name": item.item_name,
Neil Trini Lasradoc48f06c2015-02-10 16:49:16 +0530270 "description": cstr(item.description).strip(),
271 "image": cstr(item.image).strip(),
Saurabhd3135532016-02-25 18:59:20 +0530272 "warehouse": warehouse,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500273 "income_account": get_default_income_account(args, item_defaults, item_group_defaults, brand_defaults),
274 "expense_account": get_default_expense_account(args, item_defaults, item_group_defaults, brand_defaults),
275 "cost_center": get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults),
Rushabh Mehta551406a2017-04-21 12:40:19 +0530276 'has_serial_no': item.has_serial_no,
277 'has_batch_no': item.has_batch_no,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530278 "batch_no": None,
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530279 "uom": args.uom,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530280 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
Fisher Yu2cd49f52019-01-11 18:01:33 +0800281 "qty": flt(args.qty) or 1.0,
282 "stock_qty": flt(args.qty) or 1.0,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530283 "price_list_rate": 0.0,
284 "base_price_list_rate": 0.0,
285 "rate": 0.0,
286 "base_rate": 0.0,
287 "amount": 0.0,
288 "base_amount": 0.0,
Nabin Hait82e3e252015-02-23 16:58:30 +0530289 "net_rate": 0.0,
290 "net_amount": 0.0,
Saurabhc6dbe702015-10-19 14:17:52 +0530291 "discount_percentage": 0.0,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500292 "supplier": get_default_supplier(args, item_defaults, item_group_defaults, brand_defaults),
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530293 "update_stock": args.get("update_stock") if args.get('doctype') in ['Sales Invoice', 'Purchase Invoice'] else 0,
Rohit Waghchaurec858d522016-12-12 13:01:43 +0530294 "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 +0530295 "is_fixed_asset": item.is_fixed_asset,
296 "weight_per_unit":item.weight_per_unit,
297 "weight_uom":item.weight_uom,
Nabin Haite45ec662018-08-01 17:44:34 +0530298 "last_purchase_rate": item.last_purchase_rate if args.get("doctype") in ["Purchase Order"] else 0,
299 "transaction_date": args.get("transaction_date")
Nabin Hait139dc7b2014-02-12 14:53:18 +0530300 })
Anand Doshibd67e872014-04-11 16:51:27 +0530301
Zlash65627be1d2019-01-15 14:16:32 +0530302 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zlash6580f5cb02018-08-29 11:39:08 +0530303 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530304
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530305 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530306 if item.stock_uom == args.uom:
307 out.conversion_factor = 1.0
308 else:
309 out.conversion_factor = args.conversion_factor or \
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530310 get_conversion_factor(item.name, args.uom).get("conversion_factor")
mbauskar287fe812017-04-10 19:15:57 +0530311
312 args.conversion_factor = out.conversion_factor
313 out.stock_qty = out.qty * out.conversion_factor
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530314
Shreya Shah44fa9a62018-01-08 14:58:20 +0530315 # calculate last purchase rate
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530316 if args.get('doctype') in purchase_doctypes:
317 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
318 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 +0530319
Nabin Haitb09ed412015-02-17 10:33:58 +0530320 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530321 for d in [
322 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530323 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530324 ["Cost Center", "cost_center", "cost_center"],
325 ["Warehouse", "warehouse", ""]]:
Nabin Hait33df0b42018-05-26 09:09:02 +0530326 if not out[d[1]]:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530327 out[d[1]] = frappe.get_cached_value('Company', args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530328
Giovanni2144e022017-12-10 17:27:09 +0100329 for fieldname in ("item_name", "item_group", "barcodes", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530330 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530331
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530332 if args.get("manufacturer"):
333 part_no = get_item_manufacturer_part_no(args.get("item_code"), args.get("manufacturer"))
334 if part_no:
335 out["manufacturer_part_no"] = part_no
336 else:
337 out["manufacturer_part_no"] = None
338 out["manufacturer"] = None
339
Nabin Hait34c551d2019-07-03 10:34:31 +0530340 child_doctype = args.doctype + ' Item'
341 meta = frappe.get_meta(child_doctype)
342 if meta.get_field("barcode"):
343 update_barcode_value(out)
344
Nabin Hait436f5262014-02-10 14:47:54 +0530345 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530346
Nabin Hait34c551d2019-07-03 10:34:31 +0530347def update_barcode_value(out):
348 from erpnext.accounts.doctype.sales_invoice.pos import get_barcode_data
349 barcode_data = get_barcode_data([out])
350
351 # If item has one barcode then update the value of the barcode field
352 if barcode_data and len(barcode_data.get(out.item_code)) == 1:
353 out['barcode'] = barcode_data.get(out.item_code)[0]
354
Zlash6580f5cb02018-08-29 11:39:08 +0530355@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500356def get_item_tax_info(company, tax_category, item_codes):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500357 out = {}
358 if isinstance(item_codes, string_types):
359 item_codes = json.loads(item_codes)
360
361 for item_code in item_codes:
362 if not item_code or item_code in out:
363 continue
364 out[item_code] = {}
365 item = frappe.get_cached_doc("Item", item_code)
366 get_item_tax_template({"tax_category": tax_category}, item, out[item_code])
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500367 out[item_code]["item_tax_rate"] = get_item_tax_map(company, out[item_code].get("item_tax_template"), as_json=True)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500368
369 return out
370
371def get_item_tax_template(args, item, out):
372 """
373 args = {
374 "tax_category": None
375 "item_tax_template": None
376 }
377 """
378 item_tax_template = args.get("item_tax_template")
379
380 if not item_tax_template:
381 item_tax_template = _get_item_tax_template(args, item.taxes, out)
382
383 if not item_tax_template:
384 item_group = item.item_group
385 while item_group and not item_tax_template:
386 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
387 item_tax_template = _get_item_tax_template(args, item_group_doc.taxes, out)
388 item_group = item_group_doc.parent_item_group
389
390def _get_item_tax_template(args, taxes, out):
391 for tax in taxes:
392 if cstr(tax.tax_category) == cstr(args.get("tax_category")):
393 out["item_tax_template"] = tax.item_tax_template
394 return tax.item_tax_template
395 return None
396
397@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500398def get_item_tax_map(company, item_tax_template, as_json=True):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500399 item_tax_map = {}
400 if item_tax_template:
401 template = frappe.get_cached_doc("Item Tax Template", item_tax_template)
402 for d in template.taxes:
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500403 if frappe.get_cached_value("Account", d.tax_type, "company") == company:
404 item_tax_map[d.tax_type] = d.tax_rate
Saif Ur Rehman67786682018-12-27 02:11:07 +0500405
406 return json.dumps(item_tax_map) if as_json else item_tax_map
407
408@frappe.whitelist()
Zlash6580f5cb02018-08-29 11:39:08 +0530409def calculate_service_end_date(args, item=None):
410 args = process_args(args)
411 if not item:
412 item = frappe.get_cached_doc("Item", args.item_code)
413
Zlash65627be1d2019-01-15 14:16:32 +0530414 doctype = args.get("parenttype") or args.get("doctype")
Zlash65a3dd7982019-01-15 14:36:11 +0530415 if doctype == "Sales Invoice":
416 enable_deferred = "enable_deferred_revenue"
417 no_of_months = "no_of_months"
418 account = "deferred_revenue_account"
419 else:
420 enable_deferred = "enable_deferred_expense"
421 no_of_months = "no_of_months_exp"
422 account = "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530423
Zlash6580f5cb02018-08-29 11:39:08 +0530424 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
Zarrare83ff382018-09-21 15:45:40 +0530425 service_end_date = add_months(service_start_date, item.get(no_of_months))
Zlash6580f5cb02018-08-29 11:39:08 +0530426 deferred_detail = {
Zlash6580f5cb02018-08-29 11:39:08 +0530427 "service_start_date": service_start_date,
428 "service_end_date": service_end_date
429 }
Zarrare83ff382018-09-21 15:45:40 +0530430 deferred_detail[enable_deferred] = item.get(enable_deferred)
431 deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)
Zlash6580f5cb02018-08-29 11:39:08 +0530432
433 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100434
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500435def get_default_income_account(args, item, item_group, brand):
Manas Solanki38667ab2018-05-16 16:55:23 +0530436 return (item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530437 or item_group.get("income_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500438 or brand.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530439 or args.income_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530440
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500441def get_default_expense_account(args, item, item_group, brand):
Manas Solanki38667ab2018-05-16 16:55:23 +0530442 return (item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530443 or item_group.get("expense_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500444 or brand.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530445 or args.expense_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530446
Zarrare83ff382018-09-21 15:45:40 +0530447def get_default_deferred_account(args, item, fieldname=None):
Zlash65627be1d2019-01-15 14:16:32 +0530448 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zarrare83ff382018-09-21 15:45:40 +0530449 return (item.get(fieldname)
450 or args.get(fieldname)
451 or frappe.get_cached_value('Company', args.company, "default_"+fieldname))
Manas Solanki03938482018-05-14 16:16:46 +0530452 else:
453 return None
454
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530455def get_default_cost_center(args, item, item_group, brand, company=None):
Nabin Hait50238c32018-08-08 18:43:04 +0530456 cost_center = None
457 if args.get('project'):
458 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530459
Nabin Hait50238c32018-08-08 18:43:04 +0530460 if not cost_center:
461 if args.get('customer'):
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500462 cost_center = item.get('selling_cost_center') or item_group.get('selling_cost_center') or brand.get('selling_cost_center')
Nabin Hait50238c32018-08-08 18:43:04 +0530463 else:
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500464 cost_center = item.get('buying_cost_center') or item_group.get('buying_cost_center') or brand.get('buying_cost_center')
Rushabh Mehta49f97472018-08-30 18:50:48 +0530465
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530466 cost_center = cost_center or args.get("cost_center")
467
468 if (company and cost_center
469 and frappe.get_cached_value("Cost Center", cost_center, "company") != company):
470 return None
471
472 return cost_center
Rushabh Mehta1a763742014-10-03 16:36:43 +0530473
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500474def get_default_supplier(args, item, item_group, brand):
Shreya Shah3c9839f2018-07-17 18:01:44 +0530475 return (item.get("default_supplier")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500476 or item_group.get("default_supplier")
477 or brand.get("default_supplier"))
Shreya Shah3c9839f2018-07-17 18:01:44 +0530478
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530479def get_price_list_rate(args, item_doc, out):
Anand Doshi39a28912016-02-15 11:42:18 +0530480 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530481
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530482 if meta.get_field("currency") or args.get('currency'):
Nabin Hait158e7dc2019-01-04 11:04:37 +0530483 pl_details = get_price_list_currency_and_exchange_rate(args)
484 args.update(pl_details)
Nabin Hait06c8cf42019-05-16 19:17:02 +0530485 if meta.get_field("currency"):
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530486 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530487
Nabin Haite45ec662018-08-01 17:44:34 +0530488 price_list_rate = get_price_list_rate_for(args, item_doc.name) or 0
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530489
hiousi1516e292019-01-08 18:34:08 +0100490 # variant
491 if not price_list_rate and item_doc.variant_of:
492 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530493
494 # insert in database
Rushabh Mehta1a763742014-10-03 16:36:43 +0530495 if not price_list_rate:
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530496 if args.price_list and args.rate:
497 insert_item_price(args)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530498 return {}
Anand Doshibd67e872014-04-11 16:51:27 +0530499
Nabin Hait436f5262014-02-10 14:47:54 +0530500 out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) \
501 / flt(args.conversion_rate)
mbauskar287fe812017-04-10 19:15:57 +0530502
Nabin Hait34d28222016-01-19 15:45:49 +0530503 if not out.price_list_rate and args.transaction_type=="buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530504 from erpnext.stock.doctype.item.item import get_last_purchase_details
Anand Doshibd67e872014-04-11 16:51:27 +0530505 out.update(get_last_purchase_details(item_doc.name,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530506 args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530507
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530508def insert_item_price(args):
509 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530510 if frappe.db.get_value("Price List", args.price_list, "currency", cache=True) == args.currency \
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530511 and cint(frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")):
512 if frappe.has_permission("Item Price", "write"):
Nabin Haite45ec662018-08-01 17:44:34 +0530513 price_list_rate = (args.rate / args.get('conversion_factor')
514 if args.get("conversion_factor") else args.rate)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530515
Nabin Haitb479a872018-09-07 13:17:11 +0530516 item_price = frappe.db.get_value('Item Price',
517 {'item_code': args.item_code, 'price_list': args.price_list, 'currency': args.currency},
518 ['name', 'price_list_rate'], as_dict=1)
519 if item_price and item_price.name:
520 if item_price.price_list_rate != price_list_rate:
521 frappe.db.set_value('Item Price', item_price.name, "price_list_rate", price_list_rate)
522 frappe.msgprint(_("Item Price updated for {0} in Price List {1}").format(args.item_code,
523 args.price_list), alert=True)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530524 else:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530525 item_price = frappe.get_doc({
526 "doctype": "Item Price",
527 "price_list": args.price_list,
528 "item_code": args.item_code,
529 "currency": args.currency,
530 "price_list_rate": price_list_rate
531 })
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530532 item_price.insert()
533 frappe.msgprint(_("Item Price added for {0} in Price List {1}").format(args.item_code,
Rushabh Mehta49f97472018-08-30 18:50:48 +0530534 args.price_list), alert=True)
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530535
Nabin Hait01ca3e52019-01-25 16:25:15 +0530536def get_item_price(args, item_code, ignore_party=False):
Nabin Haite45ec662018-08-01 17:44:34 +0530537 """
538 Get name, price_list_rate from Item Price based on conditions
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530539 Check if the desired qty is within the increment of the packing list.
Nabin Haite45ec662018-08-01 17:44:34 +0530540 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
541 optional fields min_qty, transaction_date, customer, supplier
542 :param item_code: str, Item Doctype field item_code
543 """
544
545 args['item_code'] = item_code
Nabin Haite45ec662018-08-01 17:44:34 +0530546
Nabin Hait01ca3e52019-01-25 16:25:15 +0530547 conditions = """where item_code=%(item_code)s
Nabin Haite45ec662018-08-01 17:44:34 +0530548 and price_list=%(price_list)s
549 and ifnull(uom, '') in ('', %(uom)s)"""
550
Nabin Hait01ca3e52019-01-25 16:25:15 +0530551 if not ignore_party:
Nabin Hait01ca3e52019-01-25 16:25:15 +0530552 if args.get("customer"):
553 conditions += " and customer=%(customer)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530554 elif args.get("supplier"):
Nabin Hait01ca3e52019-01-25 16:25:15 +0530555 conditions += " and supplier=%(supplier)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530556 else:
557 conditions += " and (customer is null or customer = '') and (supplier is null or supplier = '')"
Nabin Hait01ca3e52019-01-25 16:25:15 +0530558
Nabin Haite45ec662018-08-01 17:44:34 +0530559 if args.get('min_qty'):
560 conditions += " and ifnull(min_qty, 0) <= %(min_qty)s"
561
562 if args.get('transaction_date'):
563 conditions += """ and %(transaction_date)s between
564 ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
565
566 return frappe.db.sql(""" select name, price_list_rate, uom
567 from `tabItem Price` {conditions}
568 order by uom desc, min_qty desc """.format(conditions=conditions), args)
569
570def get_price_list_rate_for(args, item_code):
571 """
572 Return Price Rate based on min_qty of each Item Price Rate.\
573 For example, desired qty is 10 and Item Price Rates exists
574 for min_qty 9 and min_qty 20. It returns Item Price Rate for qty 9 as
575 the best fit in the range of avaliable min_qtyies
576
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530577 :param customer: link to Customer DocType
578 :param supplier: link to Supplier DocType
Nabin Haite45ec662018-08-01 17:44:34 +0530579 :param price_list: str (Standard Buying or Standard Selling)
580 :param item_code: str, Item Doctype field item_code
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530581 :param qty: Desired Qty
Nabin Haite45ec662018-08-01 17:44:34 +0530582 :param transaction_date: Date of the price
583 """
584 item_price_args = {
585 "item_code": item_code,
586 "price_list": args.get('price_list'),
587 "customer": args.get('customer'),
588 "supplier": args.get('supplier'),
589 "uom": args.get('uom'),
590 "min_qty": args.get('qty'),
591 "transaction_date": args.get('transaction_date'),
592 }
593
594 item_price_data = 0
595 price_list_rate = get_item_price(item_price_args, item_code)
596 if price_list_rate:
597 desired_qty = args.get("qty")
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530598 if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
Nabin Haite45ec662018-08-01 17:44:34 +0530599 item_price_data = price_list_rate
600 else:
601 for field in ["customer", "supplier", "min_qty"]:
602 del item_price_args[field]
603
Nabin Hait01ca3e52019-01-25 16:25:15 +0530604 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 +0530605 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530606 item_price_args["uom"] = args.get("stock_uom")
Nabin Hait01ca3e52019-01-25 16:25:15 +0530607 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 +0530608
609 if general_price_list_rate:
610 item_price_data = general_price_list_rate
611
612 if item_price_data:
613 if item_price_data[0][2] == args.get("uom"):
614 return item_price_data[0][1]
615 elif not args.get('price_list_uom_dependant'):
616 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
617 else:
618 return item_price_data[0][1]
619
620def check_packing_list(price_list_rate_name, desired_qty, item_code):
621 """
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530622 Check if the desired qty is within the increment of the packing list.
Nabin Haite45ec662018-08-01 17:44:34 +0530623 :param price_list_rate_name: Name of Item Price
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530624 :param desired_qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530625 :param item_code: str, Item Doctype field item_code
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530626 :param qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530627 """
628
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530629 flag = True
Nabin Haite45ec662018-08-01 17:44:34 +0530630 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530631 if item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +0530632 packing_increment = desired_qty % item_price.packing_unit
633
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530634 if packing_increment != 0:
635 flag = False
636
637 return flag
Rushabh Mehta1a763742014-10-03 16:36:43 +0530638
Nabin Hait436f5262014-02-10 14:47:54 +0530639def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +0530640 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +0530641
Anand Doshife13bfe2015-08-25 12:49:40 +0530642 if (not args.conversion_rate
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530643 and args.currency==frappe.get_cached_value('Company', args.company, "default_currency")):
Anand Doshife13bfe2015-08-25 12:49:40 +0530644 args.conversion_rate = 1.0
645
Nabin Hait436f5262014-02-10 14:47:54 +0530646 # validate currency conversion rate
Anand Doshibd67e872014-04-11 16:51:27 +0530647 validate_conversion_rate(args.currency, args.conversion_rate,
Nabin Hait436f5262014-02-10 14:47:54 +0530648 meta.get_label("conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530649
650 args.conversion_rate = flt(args.conversion_rate,
651 get_field_precision(meta.get_field("conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530652 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530653
Nabin Hait06c8cf42019-05-16 19:17:02 +0530654 if args.price_list:
655 if (not args.plc_conversion_rate
656 and args.price_list_currency==frappe.db.get_value("Price List", args.price_list, "currency", cache=True)):
657 args.plc_conversion_rate = 1.0
Manas Solanki3504a232018-06-06 12:46:06 +0530658
Nabin Hait06c8cf42019-05-16 19:17:02 +0530659 # validate price list currency conversion rate
660 if not args.get("price_list_currency"):
661 throw(_("Price List Currency not selected"))
662 else:
663 validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate,
664 meta.get_label("plc_conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530665
Nabin Hait06c8cf42019-05-16 19:17:02 +0530666 if meta.get_field("plc_conversion_rate"):
667 args.plc_conversion_rate = flt(args.plc_conversion_rate,
668 get_field_precision(meta.get_field("plc_conversion_rate"),
669 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530670
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530671def get_party_item_code(args, item_doc, out):
Nabin Hait34d28222016-01-19 15:45:49 +0530672 if args.transaction_type=="selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +0530673 out.customer_item_code = None
Nabin Hait34c551d2019-07-03 10:34:31 +0530674
675 if args.quotation_to and args.quotation_to != 'Customer':
676 return
677
Nabin Hait79f091e2014-12-26 11:41:15 +0530678 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +0530679
680 if customer_item_code:
681 out.customer_item_code = customer_item_code[0].ref_code
682 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +0530683 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +0530684 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
685 if customer_group_item_code and not customer_group_item_code[0].customer_name:
686 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +0530687
Nabin Hait34d28222016-01-19 15:45:49 +0530688 if args.transaction_type=="buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +0530689 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +0530690 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +0530691
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530692def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530693 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +0530694
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530695 if not frappe.flags.pos_profile and not pos_profile:
696 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get('pos_profile'))
Anand Doshibd67e872014-04-11 16:51:27 +0530697
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530698 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +0530699 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530700 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530701 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530702
Nabin Hait436f5262014-02-10 14:47:54 +0530703 if res.get("warehouse"):
Saurabhd3135532016-02-25 18:59:20 +0530704 res.actual_qty = get_bin_details(args.item_code,
Nabin Hait436f5262014-02-10 14:47:54 +0530705 res.warehouse).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +0530706
Nabin Hait436f5262014-02-10 14:47:54 +0530707 return res
708
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530709@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530710def get_pos_profile(company, pos_profile=None, user=None):
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530711 if pos_profile: return frappe.get_cached_doc('POS Profile', pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530712
713 if not user:
714 user = frappe.session['user']
715
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530716 condition = "pfu.user = %(user)s AND pfu.default=1"
717 if user and company:
718 condition = "pfu.user = %(user)s AND pf.company = %(company)s AND pfu.default=1"
719
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530720 pos_profile = frappe.db.sql("""SELECT pf.*
721 FROM
722 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
723 ON
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530724 pf.name = pfu.parent
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530725 WHERE
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530726 {cond} AND pf.disabled = 0
727 """.format(cond = condition), {
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530728 'user': user,
729 'company': company
730 }, as_dict=1)
Anand Doshibd67e872014-04-11 16:51:27 +0530731
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530732 if not pos_profile and company:
733 pos_profile = frappe.db.sql("""SELECT pf.*
734 FROM
735 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
736 ON
737 pf.name = pfu.parent
738 WHERE
739 pf.company = %(company)s AND pf.disabled = 0
740 """, {
741 'company': company
742 }, as_dict=1)
743
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530744 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +0530745
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530746def get_serial_nos_by_fifo(args, sales_order=None):
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530747 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
748 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530749 where item_code=%(item_code)s and warehouse=%(warehouse)s and
750 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
751 order by timestamp(purchase_date, purchase_time)
752 asc limit %(qty)s""",
753 {
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530754 "item_code": args.item_code,
755 "warehouse": args.warehouse,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530756 "qty": abs(cint(args.stock_qty)),
757 "sales_order": sales_order
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530758 }))
Nabin Hait08222152014-02-28 11:30:47 +0530759
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530760def get_serial_no_batchwise(args, sales_order=None):
Shreyaa20157a2018-04-13 12:03:42 +0530761 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
762 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530763 where item_code=%(item_code)s and warehouse=%(warehouse)s and
764 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
765 and batch_no=IF(%(batch_no)s IS NULL, batch_no, %(batch_no)s) order
766 by timestamp(purchase_date, purchase_time) asc limit %(qty)s""", {
Shreyaa20157a2018-04-13 12:03:42 +0530767 "item_code": args.item_code,
768 "warehouse": args.warehouse,
769 "batch_no": args.batch_no,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530770 "qty": abs(cint(args.stock_qty)),
771 "sales_order": sales_order
Shreyaa20157a2018-04-13 12:03:42 +0530772 }))
773
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530774@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530775def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530776 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530777 filters = {"parent": item_code, "uom": uom}
778 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +0530779 filters["parent"] = ("in", (item_code, variant_of))
Sagar Vora508189e2018-09-11 17:22:25 +0530780 conversion_factor = frappe.db.get_value("UOM Conversion Detail",
781 filters, "conversion_factor")
782 if not conversion_factor:
783 stock_uom = frappe.db.get_value("Item", item_code, "stock_uom")
784 conversion_factor = get_uom_conv_factor(uom, stock_uom)
rohitwaghchaureffdadbf2019-01-08 16:21:25 +0530785 return {"conversion_factor": conversion_factor or 1.0}
Nabin Hait08222152014-02-28 11:30:47 +0530786
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530787@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530788def get_projected_qty(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530789 return {"projected_qty": frappe.db.get_value("Bin",
Nabin Hait436f5262014-02-10 14:47:54 +0530790 {"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
Nabin Hait08222152014-02-28 11:30:47 +0530791
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530792@frappe.whitelist()
Saurabhd3135532016-02-25 18:59:20 +0530793def get_bin_details(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530794 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Nabin Haita804d6d2018-08-29 13:34:58 +0530795 ["projected_qty", "actual_qty", "reserved_qty"], as_dict=True, cache=True) \
Shreya Shahbe770332018-08-22 14:45:22 +0530796 or {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530797
798@frappe.whitelist()
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530799def get_serial_no_details(item_code, warehouse, stock_qty, serial_no):
800 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "serial_no":serial_no})
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530801 serial_no = get_serial_no(args)
802 return {'serial_no': serial_no}
Rushabh Mehta985cb822016-12-30 15:06:54 +0530803
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530804@frappe.whitelist()
Rohit Waghchaure6daab3c2019-09-19 17:01:26 +0530805def get_bin_details_and_serial_nos(item_code, warehouse, has_batch_no=None, stock_qty=None, serial_no=None):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530806 bin_details_and_serial_nos = {}
807 bin_details_and_serial_nos.update(get_bin_details(item_code, warehouse))
Rushabh Mehta49f97472018-08-30 18:50:48 +0530808 if flt(stock_qty) > 0:
Shreyaa20157a2018-04-13 12:03:42 +0530809 if has_batch_no:
810 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty})
811 serial_no = get_serial_no(args)
812 bin_details_and_serial_nos.update({'serial_no': serial_no})
813 return bin_details_and_serial_nos
814
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530815 bin_details_and_serial_nos.update(get_serial_no_details(item_code, warehouse, stock_qty, serial_no))
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530816 return bin_details_and_serial_nos
Anand Doshidffec8f2014-07-01 17:45:15 +0530817
818@frappe.whitelist()
Shreyaa20157a2018-04-13 12:03:42 +0530819def get_batch_qty_and_serial_no(batch_no, stock_qty, warehouse, item_code, has_serial_no):
820 batch_qty_and_serial_no = {}
821 batch_qty_and_serial_no.update(get_batch_qty(batch_no, warehouse, item_code))
822
823 if (flt(batch_qty_and_serial_no.get('actual_batch_qty')) >= flt(stock_qty)) and has_serial_no:
824 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "batch_no":batch_no})
825 serial_no = get_serial_no(args)
826 batch_qty_and_serial_no.update({'serial_no': serial_no})
827 return batch_qty_and_serial_no
828
829@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530830def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +0700831 from erpnext.stock.doctype.batch import batch
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +0530832 if batch_no:
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530833 return {'actual_batch_qty': batch.get_batch_qty(batch_no, warehouse)}
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530834
Anand Doshidffec8f2014-07-01 17:45:15 +0530835@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530836def apply_price_list(args, as_doc=False):
837 """Apply pricelist on a document-like dict object and return as
838 {'parent': dict, 'children': list}
839
840 :param args: See below
841 :param as_doc: Updates value in the passed dict
842
Anand Doshidffec8f2014-07-01 17:45:15 +0530843 args = {
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530844 "doctype": "",
845 "name": "",
846 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
Anand Doshidffec8f2014-07-01 17:45:15 +0530847 "conversion_rate": 1.0,
848 "selling_price_list": None,
849 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530850 "price_list_uom_dependant": None,
Anand Doshidffec8f2014-07-01 17:45:15 +0530851 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530852 "doctype": "",
853 "name": "",
Anand Doshidffec8f2014-07-01 17:45:15 +0530854 "supplier": None,
855 "transaction_date": None,
856 "conversion_rate": 1.0,
857 "buying_price_list": None,
Anand Doshidffec8f2014-07-01 17:45:15 +0530858 "ignore_pricing_rule": 0/1
859 }
860 """
861 args = process_args(args)
862
863 parent = get_price_list_currency_and_exchange_rate(args)
864 children = []
865
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530866 if "items" in args:
867 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +0530868 args.update(parent)
869
870 for item in item_list:
871 args_copy = frappe._dict(args.copy())
872 args_copy.update(item)
873 item_details = apply_price_list_on_item(args_copy)
874 children.append(item_details)
875
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530876 if as_doc:
Shreya Shahb13a54a2017-12-06 19:17:04 +0530877 args.price_list_currency = parent.price_list_currency,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530878 args.plc_conversion_rate = parent.plc_conversion_rate
879 if args.get('items'):
880 for i, item in enumerate(args.get('items')):
881 for fieldname in children[i]:
882 # if the field exists in the original doc
883 # update the value
884 if fieldname in item and fieldname not in ("name", "doctype"):
885 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530886 return args
887 else:
888 return {
889 "parent": parent,
890 "children": children
891 }
Anand Doshidffec8f2014-07-01 17:45:15 +0530892
893def apply_price_list_on_item(args):
894 item_details = frappe._dict()
895 item_doc = frappe.get_doc("Item", args.item_code)
896 get_price_list_rate(args, item_doc, item_details)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530897
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530898 item_details.update(get_pricing_rule_for_item(args, item_details.price_list_rate))
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530899
Anand Doshidffec8f2014-07-01 17:45:15 +0530900 return item_details
901
Anand Doshidffec8f2014-07-01 17:45:15 +0530902def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +0530903 if not args.price_list:
904 return {}
905
Shreya3f778522018-05-15 16:59:20 +0530906 if args.doctype in ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']:
907 args.update({"exchange_rate": "for_selling"})
908 elif args.doctype in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']:
909 args.update({"exchange_rate": "for_buying"})
910
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530911 price_list_details = get_price_list_details(args.price_list)
912
913 price_list_currency = price_list_details.get("currency")
914 price_list_uom_dependant = price_list_details.get("price_list_uom_dependant")
915
Anand Doshidffec8f2014-07-01 17:45:15 +0530916 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +0100917 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +0530918
Nabin Haitdd82bf22015-05-11 16:49:17 +0530919 if (not plc_conversion_rate) or (price_list_currency and args.price_list_currency \
920 and price_list_currency != args.price_list_currency):
Rushabh Mehta6b537922017-03-14 16:59:11 +0530921 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
tundebabzy6e90f492018-02-12 10:48:57 +0100922 plc_conversion_rate = get_exchange_rate(price_list_currency, company_currency,
Shreya3f778522018-05-15 16:59:20 +0530923 args.transaction_date, args.exchange_rate) or plc_conversion_rate
Anand Doshidffec8f2014-07-01 17:45:15 +0530924
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530925 return frappe._dict({
Anand Doshidffec8f2014-07-01 17:45:15 +0530926 "price_list_currency": price_list_currency,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530927 "price_list_uom_dependant": price_list_uom_dependant,
Anand Doshidffec8f2014-07-01 17:45:15 +0530928 "plc_conversion_rate": plc_conversion_rate
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530929 })
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530930
931@frappe.whitelist()
932def get_default_bom(item_code=None):
933 if item_code:
934 bom = frappe.db.get_value("BOM", {"docstatus": 1, "is_default": 1, "is_active": 1, "item": item_code})
935 if bom:
936 return bom
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530937
Manas Solanki087a2252018-05-04 16:02:38 +0530938def get_valuation_rate(item_code, company, warehouse=None):
Manas Solankib16a4ec2018-05-04 16:49:33 +0530939 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530940 item_group = get_item_group_defaults(item_code, company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500941 brand = get_brand_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +0530942 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +0530943 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +0530944 if not warehouse:
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500945 warehouse = item.get("default_warehouse") or item_group.get("default_warehouse") or brand.get("default_warehouse")
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530946
947 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Saurabhbd01a812016-03-07 14:32:23 +0530948 ["valuation_rate"], as_dict=True) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530949
Manas Solankie3910fb2018-05-16 15:50:17 +0530950 elif not item.get("is_stock_item"):
Nabin Haitfe876c02017-03-06 16:32:57 +0530951 valuation_rate =frappe.db.sql("""select sum(base_net_amount) / sum(qty*conversion_factor)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530952 from `tabPurchase Invoice Item`
Saurabhbd01a812016-03-07 14:32:23 +0530953 where item_code = %s and docstatus=1""", item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530954
Saurabhbd01a812016-03-07 14:32:23 +0530955 if valuation_rate:
956 return {"valuation_rate": valuation_rate[0][0] or 0.0}
957 else:
958 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530959
Saurabh2d7af632016-02-26 11:09:20 +0530960def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +0530961 if out.valuation_rate:
962 out.update({
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530963 "gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)
Saurabh5ada14b2016-02-26 18:02:55 +0530964 })
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530965
Saurabhd3135532016-02-25 18:59:20 +0530966 return out
mbauskar6f603392016-01-21 16:10:22 +0530967
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530968@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530969def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +0530970 serial_no = None
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530971 if isinstance(args, string_types):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530972 args = json.loads(args)
973 args = frappe._dict(args)
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530974 if args.get('doctype') == 'Sales Invoice' and not args.get('update_stock'):
975 return ""
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530976 if args.get('warehouse') and args.get('stock_qty') and args.get('item_code'):
Shreyaa20157a2018-04-13 12:03:42 +0530977 has_serial_no = frappe.get_value('Item', {'item_code': args.item_code}, "has_serial_no")
Shreyaa20157a2018-04-13 12:03:42 +0530978 if args.get('batch_no') and has_serial_no == 1:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530979 return get_serial_no_batchwise(args, sales_order)
Shreyaa20157a2018-04-13 12:03:42 +0530980 elif has_serial_no == 1:
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530981 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 +0530982 args = process_args(args)
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530983 serial_no = get_serial_nos_by_fifo(args, sales_order)
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +0530984
985 if not serial_no and serial_nos:
986 # For POS
987 serial_no = serial_nos
988
989 return serial_no
Manas Solankie5e87f72018-05-28 20:07:08 +0530990
991
992def update_party_blanket_order(args, out):
993 blanket_order_details = get_blanket_order_details(args)
994 if blanket_order_details:
995 out.update(blanket_order_details)
996
997@frappe.whitelist()
998def get_blanket_order_details(args):
999 if isinstance(args, string_types):
1000 args = frappe._dict(json.loads(args))
1001
1002 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +05301003 condition = ''
Manas Solankie5e87f72018-05-28 20:07:08 +05301004 if args.item_code:
1005 if args.customer and args.doctype == "Sales Order":
Nabin Hait2737b082018-06-14 18:07:22 +05301006 condition = ' and bo.customer=%(customer)s'
Manas Solankie5e87f72018-05-28 20:07:08 +05301007 elif args.supplier and args.doctype == "Purchase Order":
Nabin Hait2737b082018-06-14 18:07:22 +05301008 condition = ' and bo.supplier=%(supplier)s'
Manas Solankie5e87f72018-05-28 20:07:08 +05301009 if args.blanket_order:
Nabin Hait2737b082018-06-14 18:07:22 +05301010 condition += ' and bo.name =%(blanket_order)s'
1011 if args.transaction_date:
1012 condition += ' and bo.to_date>=%(transaction_date)s'
1013
Manas Solankie5e87f72018-05-28 20:07:08 +05301014 blanket_order_details = frappe.db.sql('''
1015 select boi.rate as blanket_order_rate, bo.name as blanket_order
1016 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
Nabin Hait2737b082018-06-14 18:07:22 +05301017 where bo.company=%(company)s and boi.item_code=%(item_code)s
1018 and bo.docstatus=1 and bo.name = boi.parent {0}
1019 '''.format(condition), args, as_dict=True)
1020
Manas Solankie5e87f72018-05-28 20:07:08 +05301021 blanket_order_details = blanket_order_details[0] if blanket_order_details else ''
1022 return blanket_order_details
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301023
1024def get_so_reservation_for_item(args):
1025 reserved_so = None
1026 if args.get('against_sales_order'):
1027 if get_reserved_qty_for_so(args.get('against_sales_order'), args.get('item_code')):
1028 reserved_so = args.get('against_sales_order')
1029 elif args.get('against_sales_invoice'):
1030 sales_order = frappe.db.sql("""select sales_order from `tabSales Invoice Item` where
1031 parent=%s and item_code=%s""", (args.get('against_sales_invoice'), args.get('item_code')))
1032 if sales_order and sales_order[0]:
1033 if get_reserved_qty_for_so(sales_order[0][0], args.get('item_code')):
1034 reserved_so = sales_order[0]
1035 elif args.get("sales_order"):
1036 if get_reserved_qty_for_so(args.get('sales_order'), args.get('item_code')):
1037 reserved_so = args.get('sales_order')
1038 return reserved_so
1039
1040def get_reserved_qty_for_so(sales_order, item_code):
1041 reserved_qty = frappe.db.sql("""select sum(qty) from `tabSales Order Item`
1042 where parent=%s and item_code=%s and ensure_delivery_based_on_produced_serial_no=1
1043 """, (sales_order, item_code))
1044 if reserved_qty and reserved_qty[0][0]:
1045 return reserved_qty[0][0]
1046 else:
1047 return 0