blob: fe2e0a43f1de70d43362d2a3ec5e9bdf368dcb88 [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
Shreya Shah3c9839f2018-07-17 18:01:44 +053015from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +050016from erpnext.setup.doctype.brand.brand import get_brand_defaults
Rohit Waghchaure3cf24362019-06-02 16:03:05 +053017from erpnext.stock.doctype.item_manufacturer.item_manufacturer import get_item_manufacturer_part_no
Nabin Hait98c2a052014-05-05 18:41:41 +053018
Achilles Rasquinha714c7462018-02-15 11:28:55 +053019from six import string_types, iteritems
tundebabzyacccdb32017-11-23 08:35:15 +010020
Nabin Hait0d1ccc32019-02-14 18:30:10 +053021sales_doctypes = ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']
22purchase_doctypes = ['Material Request', 'Supplier Quotation', 'Purchase Order', 'Purchase Receipt', 'Purchase Invoice']
23
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053024@frappe.whitelist()
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +053025def get_item_details(args, doc=None):
Nabin Hait436f5262014-02-10 14:47:54 +053026 """
27 args = {
28 "item_code": "",
29 "warehouse": None,
30 "customer": "",
31 "conversion_rate": 1.0,
32 "selling_price_list": None,
33 "price_list_currency": None,
Nabin Hait615d3422014-02-25 19:01:20 +053034 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +053035 "doctype": "",
36 "name": "",
Nabin Hait436f5262014-02-10 14:47:54 +053037 "supplier": None,
38 "transaction_date": None,
39 "conversion_rate": 1.0,
40 "buying_price_list": None,
41 "is_subcontracted": "Yes" / "No",
Nabin Hait444f9562014-06-20 15:59:49 +053042 "ignore_pricing_rule": 0/1
Neil Trini Lasrado6e343e22016-03-09 17:02:59 +053043 "project": ""
Saif Ur Rehman2689dea2019-01-09 13:43:06 +050044 "set_warehouse": ""
Nabin Hait436f5262014-02-10 14:47:54 +053045 }
46 """
Anand Doshidffec8f2014-07-01 17:45:15 +053047 args = process_args(args)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053048 item = frappe.get_cached_doc("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053049 validate_item_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053050
Rushabh Mehta1a763742014-10-03 16:36:43 +053051 out = get_basic_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053052
Saif Ur Rehman67786682018-12-27 02:11:07 +050053 get_item_tax_template(args, item, out)
Saif Ur Rehman648bd152019-01-03 03:48:01 +050054 out["item_tax_rate"] = get_item_tax_map(args.company, args.get("item_tax_template") if out.get("item_tax_template") is None \
55 else out.get("item_tax_template"), as_json=True)
Saif Ur Rehman67786682018-12-27 02:11:07 +050056
Rushabh Mehta708e47a2018-08-08 16:37:31 +053057 get_party_item_code(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053058
Rushabh Mehta708e47a2018-08-08 16:37:31 +053059 set_valuation_rate(out, args)
Anand Doshibd67e872014-04-11 16:51:27 +053060
Manas Solankie5e87f72018-05-28 20:07:08 +053061 update_party_blanket_order(args, out)
62
Rushabh Mehta708e47a2018-08-08 16:37:31 +053063 get_price_list_rate(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053064
Rushabh Mehtab46069d2016-01-15 16:59:26 +053065 if args.customer and cint(args.is_pos):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +053066 out.update(get_pos_profile_item_details(args.company, args))
Rushabh Mehta6b537922017-03-14 16:59:11 +053067
Nabin Hait0287d312017-01-11 10:31:33 +053068 if out.get("warehouse"):
69 out.update(get_bin_details(args.item_code, out.warehouse))
Anand Doshibd67e872014-04-11 16:51:27 +053070
Nabin Haita3dd72a2014-05-28 12:49:20 +053071 # update args with out, if key or value not exists
Achilles Rasquinha714c7462018-02-15 11:28:55 +053072 for key, value in iteritems(out):
Nabin Haita3dd72a2014-05-28 12:49:20 +053073 if args.get(key) is None:
74 args[key] = value
75
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +053076 data = get_pricing_rule_for_item(args, out.price_list_rate, doc)
77 out.update(data)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053078
79 update_stock(args, out)
80
81 if args.transaction_date and item.lead_time_days:
82 out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
83 item.lead_time_days)
84
85 if args.get("is_subcontracted") == "Yes":
86 out.bom = args.get('bom') or get_default_bom(args.item_code)
87
88 get_gross_profit(out)
89 if args.doctype == 'Material Request':
90 out.rate = args.rate or out.price_list_rate
91 out.amount = flt(args.qty * out.rate)
92
93 return out
94
95def update_stock(args, out):
pratu16x7577e4c42017-06-23 11:39:03 +053096 if (args.get("doctype") == "Delivery Note" or
Nabin Hait3ce41d62017-05-03 18:22:24 +053097 (args.get("doctype") == "Sales Invoice" and args.get('update_stock'))) \
98 and out.warehouse and out.stock_qty > 0:
pratu16x7577e4c42017-06-23 11:39:03 +053099
Nabin Hait8fac2ad2017-05-18 11:54:24 +0530100 if out.has_batch_no and not args.get("batch_no"):
Rushabh Mehta551406a2017-04-21 12:40:19 +0530101 out.batch_no = get_batch_no(out.item_code, out.warehouse, out.qty)
rohitwaghchaure2fb8cc52017-11-29 13:50:04 +0530102 actual_batch_qty = get_batch_qty(out.batch_no, out.warehouse, out.item_code)
103 if actual_batch_qty:
104 out.update(actual_batch_qty)
Shreya14bd43d2018-04-27 16:24:05 +0530105
106 if out.has_serial_no and args.get('batch_no'):
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530107 reserved_so = get_so_reservation_for_item(args)
Shreya14bd43d2018-04-27 16:24:05 +0530108 out.batch_no = args.get('batch_no')
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530109 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Shreya14bd43d2018-04-27 16:24:05 +0530110
111 elif out.has_serial_no:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530112 reserved_so = get_so_reservation_for_item(args)
113 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Rushabh Mehta551406a2017-04-21 12:40:19 +0530114
Anand Doshibd67e872014-04-11 16:51:27 +0530115
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530116def set_valuation_rate(out, args):
Nabin Hait50238c32018-08-08 18:43:04 +0530117 if frappe.db.exists("Product Bundle", args.item_code, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530118 valuation_rate = 0.0
119 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530120
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530121 for bundle_item in bundled_items.items:
122 valuation_rate += \
123 flt(get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get("valuation_rate") \
124 * bundle_item.qty)
Anand Doshi70f57eb2015-11-27 14:37:40 +0530125
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530126 out.update({
127 "valuation_rate": valuation_rate
128 })
129
130 else:
131 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
132
Nabin Hait436f5262014-02-10 14:47:54 +0530133
Anand Doshidffec8f2014-07-01 17:45:15 +0530134def process_args(args):
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530135 if isinstance(args, string_types):
Anand Doshidffec8f2014-07-01 17:45:15 +0530136 args = json.loads(args)
137
138 args = frappe._dict(args)
139
Anand Doshidffec8f2014-07-01 17:45:15 +0530140 if not args.get("price_list"):
141 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
142
143 if args.barcode:
144 args.item_code = get_item_code(barcode=args.barcode)
145 elif not args.item_code and args.serial_no:
146 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530147
mbauskar6f603392016-01-21 16:10:22 +0530148 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530149 return args
150
tundebabzyacccdb32017-11-23 08:35:15 +0100151
Neil Trini Lasrado4abda672015-02-25 17:34:27 +0530152@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530153def get_item_code(barcode=None, serial_no=None):
154 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100155 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530156 if not item_code:
157 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530158 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530159 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530160 if not item_code:
161 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530162
Nabin Hait436f5262014-02-10 14:47:54 +0530163 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530164
tundebabzyacccdb32017-11-23 08:35:15 +0100165
Nabin Hait436f5262014-02-10 14:47:54 +0530166def validate_item_details(args, item):
167 if not args.company:
168 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530169
Nabin Hait436f5262014-02-10 14:47:54 +0530170 from erpnext.stock.doctype.item.item import validate_end_of_life
Anand Doshi21e09a22015-10-29 12:21:41 +0530171 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530172
tundebabzyacccdb32017-11-23 08:35:15 +0100173 if args.transaction_type == "selling" and cint(item.has_variants):
Umair Sayyed72534de2016-04-15 12:52:12 +0530174 throw(_("Item {0} is a template, please select one of its variants").format(item.name))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530175
tundebabzyacccdb32017-11-23 08:35:15 +0100176 elif args.transaction_type == "buying" and args.doctype != "Material Request":
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530177 if args.get("is_subcontracted") == "Yes" and item.is_sub_contracted_item != 1:
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530178 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530179
tundebabzyacccdb32017-11-23 08:35:15 +0100180
Rushabh Mehta1a763742014-10-03 16:36:43 +0530181def get_basic_details(args, item):
tundebabzyacccdb32017-11-23 08:35:15 +0100182 """
183 :param args: {
184 "item_code": "",
185 "warehouse": None,
186 "customer": "",
187 "conversion_rate": 1.0,
188 "selling_price_list": None,
189 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530190 "price_list_uom_dependant": None,
tundebabzyacccdb32017-11-23 08:35:15 +0100191 "plc_conversion_rate": 1.0,
192 "doctype": "",
193 "name": "",
194 "supplier": None,
195 "transaction_date": None,
196 "conversion_rate": 1.0,
197 "buying_price_list": None,
198 "is_subcontracted": "Yes" / "No",
199 "ignore_pricing_rule": 0/1
200 "project": "",
201 barcode: "",
202 serial_no: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100203 currency: "",
204 update_stock: "",
205 price_list: "",
206 company: "",
207 order_type: "",
208 is_pos: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100209 project: "",
210 qty: "",
211 stock_qty: "",
212 conversion_factor: ""
213 }
214 :param item: `item_code` of Item object
215 :return: frappe._dict
216 """
217
Rushabh Mehta1a763742014-10-03 16:36:43 +0530218 if not item:
219 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530220
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530221 if item.variant_of:
222 item.update_template_tables()
223
Manas Solankib16a4ec2018-05-04 16:49:33 +0530224 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530225 item_group_defaults = get_item_group_defaults(item.name, args.company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500226 brand_defaults = get_brand_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530227
Rohit Waghchaurec41118b2019-05-21 15:19:03 +0530228 warehouse = (args.get("set_warehouse") or item_defaults.get("default_warehouse") or
229 item_group_defaults.get("default_warehouse") or brand_defaults.get("default_warehouse") or args.warehouse)
230
231 if not warehouse:
232 defaults = frappe.defaults.get_defaults() or {}
233 if defaults.get("default_warehouse") and frappe.db.exists("Warehouse",
234 {'name': defaults.default_warehouse, 'company': args.company}):
235 warehouse = defaults.default_warehouse
Nabin Hait36028bf2014-02-12 19:09:28 +0530236
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530237 if args.get('doctype') == "Material Request" and not args.get('material_request_type'):
238 args['material_request_type'] = frappe.db.get_value('Material Request',
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530239 args.get('name'), 'material_request_type', cache=True)
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530240
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530241 #Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
242 if not args.uom:
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530243 if args.get('doctype') in sales_doctypes:
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530244 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530245 elif (args.get('doctype') in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']) or \
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530246 (args.get('doctype') == 'Material Request' and args.get('material_request_type') == 'Purchase'):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530247 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
248 else:
249 args.uom = item.stock_uom
250
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530251 out = frappe._dict({
Nabin Hait139dc7b2014-02-12 14:53:18 +0530252 "item_code": item.name,
253 "item_name": item.item_name,
Neil Trini Lasradoc48f06c2015-02-10 16:49:16 +0530254 "description": cstr(item.description).strip(),
255 "image": cstr(item.image).strip(),
Saurabhd3135532016-02-25 18:59:20 +0530256 "warehouse": warehouse,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500257 "income_account": get_default_income_account(args, item_defaults, item_group_defaults, brand_defaults),
258 "expense_account": get_default_expense_account(args, item_defaults, item_group_defaults, brand_defaults),
259 "cost_center": get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults),
Rushabh Mehta551406a2017-04-21 12:40:19 +0530260 'has_serial_no': item.has_serial_no,
261 'has_batch_no': item.has_batch_no,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530262 "batch_no": None,
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530263 "uom": args.uom,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530264 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
Fisher Yu2cd49f52019-01-11 18:01:33 +0800265 "qty": flt(args.qty) or 1.0,
266 "stock_qty": flt(args.qty) or 1.0,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530267 "price_list_rate": 0.0,
268 "base_price_list_rate": 0.0,
269 "rate": 0.0,
270 "base_rate": 0.0,
271 "amount": 0.0,
272 "base_amount": 0.0,
Nabin Hait82e3e252015-02-23 16:58:30 +0530273 "net_rate": 0.0,
274 "net_amount": 0.0,
Saurabhc6dbe702015-10-19 14:17:52 +0530275 "discount_percentage": 0.0,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500276 "supplier": get_default_supplier(args, item_defaults, item_group_defaults, brand_defaults),
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530277 "update_stock": args.get("update_stock") if args.get('doctype') in ['Sales Invoice', 'Purchase Invoice'] else 0,
Rohit Waghchaurec858d522016-12-12 13:01:43 +0530278 "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 +0530279 "is_fixed_asset": item.is_fixed_asset,
280 "weight_per_unit":item.weight_per_unit,
281 "weight_uom":item.weight_uom,
Nabin Haite45ec662018-08-01 17:44:34 +0530282 "last_purchase_rate": item.last_purchase_rate if args.get("doctype") in ["Purchase Order"] else 0,
283 "transaction_date": args.get("transaction_date")
Nabin Hait139dc7b2014-02-12 14:53:18 +0530284 })
Anand Doshibd67e872014-04-11 16:51:27 +0530285
Zlash65627be1d2019-01-15 14:16:32 +0530286 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zlash6580f5cb02018-08-29 11:39:08 +0530287 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530288
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530289 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530290 if item.stock_uom == args.uom:
291 out.conversion_factor = 1.0
292 else:
293 out.conversion_factor = args.conversion_factor or \
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530294 get_conversion_factor(item.name, args.uom).get("conversion_factor")
mbauskar287fe812017-04-10 19:15:57 +0530295
296 args.conversion_factor = out.conversion_factor
297 out.stock_qty = out.qty * out.conversion_factor
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530298
Shreya Shah44fa9a62018-01-08 14:58:20 +0530299 # calculate last purchase rate
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530300 if args.get('doctype') in purchase_doctypes:
301 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
302 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 +0530303
Nabin Haitb09ed412015-02-17 10:33:58 +0530304 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530305 for d in [
306 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530307 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530308 ["Cost Center", "cost_center", "cost_center"],
309 ["Warehouse", "warehouse", ""]]:
Nabin Hait33df0b42018-05-26 09:09:02 +0530310 if not out[d[1]]:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530311 out[d[1]] = frappe.get_cached_value('Company', args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530312
Giovanni2144e022017-12-10 17:27:09 +0100313 for fieldname in ("item_name", "item_group", "barcodes", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530314 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530315
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530316 if args.get("manufacturer"):
317 part_no = get_item_manufacturer_part_no(args.get("item_code"), args.get("manufacturer"))
318 if part_no:
319 out["manufacturer_part_no"] = part_no
320 else:
321 out["manufacturer_part_no"] = None
322 out["manufacturer"] = None
323
Nabin Hait436f5262014-02-10 14:47:54 +0530324 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530325
Zlash6580f5cb02018-08-29 11:39:08 +0530326@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500327def get_item_tax_info(company, tax_category, item_codes):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500328 out = {}
329 if isinstance(item_codes, string_types):
330 item_codes = json.loads(item_codes)
331
332 for item_code in item_codes:
333 if not item_code or item_code in out:
334 continue
335 out[item_code] = {}
336 item = frappe.get_cached_doc("Item", item_code)
337 get_item_tax_template({"tax_category": tax_category}, item, out[item_code])
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500338 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 +0500339
340 return out
341
342def get_item_tax_template(args, item, out):
343 """
344 args = {
345 "tax_category": None
346 "item_tax_template": None
347 }
348 """
349 item_tax_template = args.get("item_tax_template")
350
351 if not item_tax_template:
352 item_tax_template = _get_item_tax_template(args, item.taxes, out)
353
354 if not item_tax_template:
355 item_group = item.item_group
356 while item_group and not item_tax_template:
357 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
358 item_tax_template = _get_item_tax_template(args, item_group_doc.taxes, out)
359 item_group = item_group_doc.parent_item_group
360
361def _get_item_tax_template(args, taxes, out):
362 for tax in taxes:
363 if cstr(tax.tax_category) == cstr(args.get("tax_category")):
364 out["item_tax_template"] = tax.item_tax_template
365 return tax.item_tax_template
366 return None
367
368@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500369def get_item_tax_map(company, item_tax_template, as_json=True):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500370 item_tax_map = {}
371 if item_tax_template:
372 template = frappe.get_cached_doc("Item Tax Template", item_tax_template)
373 for d in template.taxes:
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500374 if frappe.get_cached_value("Account", d.tax_type, "company") == company:
375 item_tax_map[d.tax_type] = d.tax_rate
Saif Ur Rehman67786682018-12-27 02:11:07 +0500376
377 return json.dumps(item_tax_map) if as_json else item_tax_map
378
379@frappe.whitelist()
Zlash6580f5cb02018-08-29 11:39:08 +0530380def calculate_service_end_date(args, item=None):
381 args = process_args(args)
382 if not item:
383 item = frappe.get_cached_doc("Item", args.item_code)
384
Zlash65627be1d2019-01-15 14:16:32 +0530385 doctype = args.get("parenttype") or args.get("doctype")
Zlash65a3dd7982019-01-15 14:36:11 +0530386 if doctype == "Sales Invoice":
387 enable_deferred = "enable_deferred_revenue"
388 no_of_months = "no_of_months"
389 account = "deferred_revenue_account"
390 else:
391 enable_deferred = "enable_deferred_expense"
392 no_of_months = "no_of_months_exp"
393 account = "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530394
Zlash6580f5cb02018-08-29 11:39:08 +0530395 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
Zarrare83ff382018-09-21 15:45:40 +0530396 service_end_date = add_months(service_start_date, item.get(no_of_months))
Zlash6580f5cb02018-08-29 11:39:08 +0530397 deferred_detail = {
Zlash6580f5cb02018-08-29 11:39:08 +0530398 "service_start_date": service_start_date,
399 "service_end_date": service_end_date
400 }
Zarrare83ff382018-09-21 15:45:40 +0530401 deferred_detail[enable_deferred] = item.get(enable_deferred)
402 deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)
Zlash6580f5cb02018-08-29 11:39:08 +0530403
404 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100405
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500406def get_default_income_account(args, item, item_group, brand):
Manas Solanki38667ab2018-05-16 16:55:23 +0530407 return (item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530408 or item_group.get("income_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500409 or brand.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530410 or args.income_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530411
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500412def get_default_expense_account(args, item, item_group, brand):
Manas Solanki38667ab2018-05-16 16:55:23 +0530413 return (item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530414 or item_group.get("expense_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500415 or brand.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530416 or args.expense_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530417
Zarrare83ff382018-09-21 15:45:40 +0530418def get_default_deferred_account(args, item, fieldname=None):
Zlash65627be1d2019-01-15 14:16:32 +0530419 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zarrare83ff382018-09-21 15:45:40 +0530420 return (item.get(fieldname)
421 or args.get(fieldname)
422 or frappe.get_cached_value('Company', args.company, "default_"+fieldname))
Manas Solanki03938482018-05-14 16:16:46 +0530423 else:
424 return None
425
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530426def get_default_cost_center(args, item, item_group, brand, company=None):
Nabin Hait50238c32018-08-08 18:43:04 +0530427 cost_center = None
428 if args.get('project'):
429 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530430
Nabin Hait50238c32018-08-08 18:43:04 +0530431 if not cost_center:
432 if args.get('customer'):
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500433 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 +0530434 else:
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500435 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 +0530436
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530437 cost_center = cost_center or args.get("cost_center")
438
439 if (company and cost_center
440 and frappe.get_cached_value("Cost Center", cost_center, "company") != company):
441 return None
442
443 return cost_center
Rushabh Mehta1a763742014-10-03 16:36:43 +0530444
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500445def get_default_supplier(args, item, item_group, brand):
Shreya Shah3c9839f2018-07-17 18:01:44 +0530446 return (item.get("default_supplier")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500447 or item_group.get("default_supplier")
448 or brand.get("default_supplier"))
Shreya Shah3c9839f2018-07-17 18:01:44 +0530449
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530450def get_price_list_rate(args, item_doc, out):
Anand Doshi39a28912016-02-15 11:42:18 +0530451 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530452
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530453 if meta.get_field("currency") or args.get('currency'):
Nabin Hait158e7dc2019-01-04 11:04:37 +0530454 pl_details = get_price_list_currency_and_exchange_rate(args)
455 args.update(pl_details)
Nabin Hait436f5262014-02-10 14:47:54 +0530456 validate_price_list(args)
Nabin Hait06c8cf42019-05-16 19:17:02 +0530457 if meta.get_field("currency"):
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530458 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530459
Nabin Haite45ec662018-08-01 17:44:34 +0530460 price_list_rate = get_price_list_rate_for(args, item_doc.name) or 0
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530461
hiousi1516e292019-01-08 18:34:08 +0100462 # variant
463 if not price_list_rate and item_doc.variant_of:
464 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530465
466 # insert in database
Rushabh Mehta1a763742014-10-03 16:36:43 +0530467 if not price_list_rate:
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530468 if args.price_list and args.rate:
469 insert_item_price(args)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530470 return {}
Anand Doshibd67e872014-04-11 16:51:27 +0530471
Nabin Hait436f5262014-02-10 14:47:54 +0530472 out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) \
473 / flt(args.conversion_rate)
mbauskar287fe812017-04-10 19:15:57 +0530474
Nabin Hait34d28222016-01-19 15:45:49 +0530475 if not out.price_list_rate and args.transaction_type=="buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530476 from erpnext.stock.doctype.item.item import get_last_purchase_details
Anand Doshibd67e872014-04-11 16:51:27 +0530477 out.update(get_last_purchase_details(item_doc.name,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530478 args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530479
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530480def insert_item_price(args):
481 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530482 if frappe.db.get_value("Price List", args.price_list, "currency", cache=True) == args.currency \
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530483 and cint(frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")):
484 if frappe.has_permission("Item Price", "write"):
Nabin Haite45ec662018-08-01 17:44:34 +0530485 price_list_rate = (args.rate / args.get('conversion_factor')
486 if args.get("conversion_factor") else args.rate)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530487
Nabin Haitb479a872018-09-07 13:17:11 +0530488 item_price = frappe.db.get_value('Item Price',
489 {'item_code': args.item_code, 'price_list': args.price_list, 'currency': args.currency},
490 ['name', 'price_list_rate'], as_dict=1)
491 if item_price and item_price.name:
492 if item_price.price_list_rate != price_list_rate:
493 frappe.db.set_value('Item Price', item_price.name, "price_list_rate", price_list_rate)
494 frappe.msgprint(_("Item Price updated for {0} in Price List {1}").format(args.item_code,
495 args.price_list), alert=True)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530496 else:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530497 item_price = frappe.get_doc({
498 "doctype": "Item Price",
499 "price_list": args.price_list,
500 "item_code": args.item_code,
501 "currency": args.currency,
502 "price_list_rate": price_list_rate
503 })
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530504 item_price.insert()
505 frappe.msgprint(_("Item Price added for {0} in Price List {1}").format(args.item_code,
Rushabh Mehta49f97472018-08-30 18:50:48 +0530506 args.price_list), alert=True)
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530507
Nabin Hait01ca3e52019-01-25 16:25:15 +0530508def get_item_price(args, item_code, ignore_party=False):
Nabin Haite45ec662018-08-01 17:44:34 +0530509 """
510 Get name, price_list_rate from Item Price based on conditions
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530511 Check if the desired qty is within the increment of the packing list.
Nabin Haite45ec662018-08-01 17:44:34 +0530512 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
513 optional fields min_qty, transaction_date, customer, supplier
514 :param item_code: str, Item Doctype field item_code
515 """
516
517 args['item_code'] = item_code
Nabin Haite45ec662018-08-01 17:44:34 +0530518
Nabin Hait01ca3e52019-01-25 16:25:15 +0530519 conditions = """where item_code=%(item_code)s
Nabin Haite45ec662018-08-01 17:44:34 +0530520 and price_list=%(price_list)s
521 and ifnull(uom, '') in ('', %(uom)s)"""
522
Nabin Hait01ca3e52019-01-25 16:25:15 +0530523 if not ignore_party:
Nabin Hait01ca3e52019-01-25 16:25:15 +0530524 if args.get("customer"):
525 conditions += " and customer=%(customer)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530526 elif args.get("supplier"):
Nabin Hait01ca3e52019-01-25 16:25:15 +0530527 conditions += " and supplier=%(supplier)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530528 else:
529 conditions += " and (customer is null or customer = '') and (supplier is null or supplier = '')"
Nabin Hait01ca3e52019-01-25 16:25:15 +0530530
Nabin Haite45ec662018-08-01 17:44:34 +0530531 if args.get('min_qty'):
532 conditions += " and ifnull(min_qty, 0) <= %(min_qty)s"
533
534 if args.get('transaction_date'):
535 conditions += """ and %(transaction_date)s between
536 ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
537
538 return frappe.db.sql(""" select name, price_list_rate, uom
539 from `tabItem Price` {conditions}
540 order by uom desc, min_qty desc """.format(conditions=conditions), args)
541
542def get_price_list_rate_for(args, item_code):
543 """
544 Return Price Rate based on min_qty of each Item Price Rate.\
545 For example, desired qty is 10 and Item Price Rates exists
546 for min_qty 9 and min_qty 20. It returns Item Price Rate for qty 9 as
547 the best fit in the range of avaliable min_qtyies
548
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530549 :param customer: link to Customer DocType
550 :param supplier: link to Supplier DocType
Nabin Haite45ec662018-08-01 17:44:34 +0530551 :param price_list: str (Standard Buying or Standard Selling)
552 :param item_code: str, Item Doctype field item_code
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530553 :param qty: Desired Qty
Nabin Haite45ec662018-08-01 17:44:34 +0530554 :param transaction_date: Date of the price
555 """
556 item_price_args = {
557 "item_code": item_code,
558 "price_list": args.get('price_list'),
559 "customer": args.get('customer'),
560 "supplier": args.get('supplier'),
561 "uom": args.get('uom'),
562 "min_qty": args.get('qty'),
563 "transaction_date": args.get('transaction_date'),
564 }
565
566 item_price_data = 0
567 price_list_rate = get_item_price(item_price_args, item_code)
568 if price_list_rate:
569 desired_qty = args.get("qty")
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530570 if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
Nabin Haite45ec662018-08-01 17:44:34 +0530571 item_price_data = price_list_rate
572 else:
573 for field in ["customer", "supplier", "min_qty"]:
574 del item_price_args[field]
575
Nabin Hait01ca3e52019-01-25 16:25:15 +0530576 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 +0530577 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530578 item_price_args["uom"] = args.get("stock_uom")
Nabin Hait01ca3e52019-01-25 16:25:15 +0530579 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 +0530580
581 if general_price_list_rate:
582 item_price_data = general_price_list_rate
583
584 if item_price_data:
585 if item_price_data[0][2] == args.get("uom"):
586 return item_price_data[0][1]
587 elif not args.get('price_list_uom_dependant'):
588 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
589 else:
590 return item_price_data[0][1]
591
592def check_packing_list(price_list_rate_name, desired_qty, item_code):
593 """
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530594 Check if the desired qty is within the increment of the packing list.
Nabin Haite45ec662018-08-01 17:44:34 +0530595 :param price_list_rate_name: Name of Item Price
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530596 :param desired_qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530597 :param item_code: str, Item Doctype field item_code
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530598 :param qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530599 """
600
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530601 flag = True
Nabin Haite45ec662018-08-01 17:44:34 +0530602 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530603 if item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +0530604 packing_increment = desired_qty % item_price.packing_unit
605
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530606 if packing_increment != 0:
607 flag = False
608
609 return flag
Rushabh Mehta1a763742014-10-03 16:36:43 +0530610
Nabin Hait436f5262014-02-10 14:47:54 +0530611def validate_price_list(args):
612 if args.get("price_list"):
Anand Doshibd67e872014-04-11 16:51:27 +0530613 if not frappe.db.get_value("Price List",
Nabin Hait34d28222016-01-19 15:45:49 +0530614 {"name": args.price_list, args.transaction_type: 1, "enabled": 1}):
Rushabh Mehta985cb822016-12-30 15:06:54 +0530615 throw(_("Price List {0} is disabled or does not exist").format(args.price_list))
mbauskar0b665ac2017-04-11 02:49:24 -0400616 elif not args.get("supplier"):
Nabin Hait436f5262014-02-10 14:47:54 +0530617 throw(_("Price List not selected"))
Anand Doshibd67e872014-04-11 16:51:27 +0530618
Nabin Hait436f5262014-02-10 14:47:54 +0530619def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +0530620 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +0530621
Anand Doshife13bfe2015-08-25 12:49:40 +0530622 if (not args.conversion_rate
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530623 and args.currency==frappe.get_cached_value('Company', args.company, "default_currency")):
Anand Doshife13bfe2015-08-25 12:49:40 +0530624 args.conversion_rate = 1.0
625
Nabin Hait436f5262014-02-10 14:47:54 +0530626 # validate currency conversion rate
Anand Doshibd67e872014-04-11 16:51:27 +0530627 validate_conversion_rate(args.currency, args.conversion_rate,
Nabin Hait436f5262014-02-10 14:47:54 +0530628 meta.get_label("conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530629
630 args.conversion_rate = flt(args.conversion_rate,
631 get_field_precision(meta.get_field("conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530632 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530633
Nabin Hait06c8cf42019-05-16 19:17:02 +0530634 if args.price_list:
635 if (not args.plc_conversion_rate
636 and args.price_list_currency==frappe.db.get_value("Price List", args.price_list, "currency", cache=True)):
637 args.plc_conversion_rate = 1.0
Manas Solanki3504a232018-06-06 12:46:06 +0530638
Nabin Hait06c8cf42019-05-16 19:17:02 +0530639 # validate price list currency conversion rate
640 if not args.get("price_list_currency"):
641 throw(_("Price List Currency not selected"))
642 else:
643 validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate,
644 meta.get_label("plc_conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530645
Nabin Hait06c8cf42019-05-16 19:17:02 +0530646 if meta.get_field("plc_conversion_rate"):
647 args.plc_conversion_rate = flt(args.plc_conversion_rate,
648 get_field_precision(meta.get_field("plc_conversion_rate"),
649 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530650
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530651def get_party_item_code(args, item_doc, out):
Nabin Hait34d28222016-01-19 15:45:49 +0530652 if args.transaction_type=="selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +0530653 out.customer_item_code = None
Nabin Hait79f091e2014-12-26 11:41:15 +0530654 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +0530655
656 if customer_item_code:
657 out.customer_item_code = customer_item_code[0].ref_code
658 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +0530659 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +0530660 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
661 if customer_group_item_code and not customer_group_item_code[0].customer_name:
662 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +0530663
Nabin Hait34d28222016-01-19 15:45:49 +0530664 if args.transaction_type=="buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +0530665 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +0530666 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +0530667
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530668def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530669 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +0530670
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530671 if not frappe.flags.pos_profile and not pos_profile:
672 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get('pos_profile'))
Anand Doshibd67e872014-04-11 16:51:27 +0530673
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530674 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +0530675 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530676 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530677 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530678
Nabin Hait436f5262014-02-10 14:47:54 +0530679 if res.get("warehouse"):
Saurabhd3135532016-02-25 18:59:20 +0530680 res.actual_qty = get_bin_details(args.item_code,
Nabin Hait436f5262014-02-10 14:47:54 +0530681 res.warehouse).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +0530682
Nabin Hait436f5262014-02-10 14:47:54 +0530683 return res
684
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530685@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530686def get_pos_profile(company, pos_profile=None, user=None):
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530687 if pos_profile: return frappe.get_cached_doc('POS Profile', pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530688
689 if not user:
690 user = frappe.session['user']
691
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530692 condition = "pfu.user = %(user)s AND pfu.default=1"
693 if user and company:
694 condition = "pfu.user = %(user)s AND pf.company = %(company)s AND pfu.default=1"
695
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530696 pos_profile = frappe.db.sql("""SELECT pf.*
697 FROM
698 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
699 ON
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530700 pf.name = pfu.parent
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530701 WHERE
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530702 {cond} AND pf.disabled = 0
703 """.format(cond = condition), {
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530704 'user': user,
705 'company': company
706 }, as_dict=1)
Anand Doshibd67e872014-04-11 16:51:27 +0530707
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530708 if not pos_profile and company:
709 pos_profile = frappe.db.sql("""SELECT pf.*
710 FROM
711 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
712 ON
713 pf.name = pfu.parent
714 WHERE
715 pf.company = %(company)s AND pf.disabled = 0
716 """, {
717 'company': company
718 }, as_dict=1)
719
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530720 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +0530721
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530722def get_serial_nos_by_fifo(args, sales_order=None):
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530723 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
724 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530725 where item_code=%(item_code)s and warehouse=%(warehouse)s and
726 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
727 order by timestamp(purchase_date, purchase_time)
728 asc limit %(qty)s""",
729 {
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530730 "item_code": args.item_code,
731 "warehouse": args.warehouse,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530732 "qty": abs(cint(args.stock_qty)),
733 "sales_order": sales_order
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530734 }))
Nabin Hait08222152014-02-28 11:30:47 +0530735
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530736def get_serial_no_batchwise(args, sales_order=None):
Shreyaa20157a2018-04-13 12:03:42 +0530737 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
738 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530739 where item_code=%(item_code)s and warehouse=%(warehouse)s and
740 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
741 and batch_no=IF(%(batch_no)s IS NULL, batch_no, %(batch_no)s) order
742 by timestamp(purchase_date, purchase_time) asc limit %(qty)s""", {
Shreyaa20157a2018-04-13 12:03:42 +0530743 "item_code": args.item_code,
744 "warehouse": args.warehouse,
745 "batch_no": args.batch_no,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530746 "qty": abs(cint(args.stock_qty)),
747 "sales_order": sales_order
Shreyaa20157a2018-04-13 12:03:42 +0530748 }))
749
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530750@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530751def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530752 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530753 filters = {"parent": item_code, "uom": uom}
754 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +0530755 filters["parent"] = ("in", (item_code, variant_of))
Sagar Vora508189e2018-09-11 17:22:25 +0530756 conversion_factor = frappe.db.get_value("UOM Conversion Detail",
757 filters, "conversion_factor")
758 if not conversion_factor:
759 stock_uom = frappe.db.get_value("Item", item_code, "stock_uom")
760 conversion_factor = get_uom_conv_factor(uom, stock_uom)
rohitwaghchaureffdadbf2019-01-08 16:21:25 +0530761 return {"conversion_factor": conversion_factor or 1.0}
Nabin Hait08222152014-02-28 11:30:47 +0530762
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530763@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530764def get_projected_qty(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530765 return {"projected_qty": frappe.db.get_value("Bin",
Nabin Hait436f5262014-02-10 14:47:54 +0530766 {"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
Nabin Hait08222152014-02-28 11:30:47 +0530767
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530768@frappe.whitelist()
Saurabhd3135532016-02-25 18:59:20 +0530769def get_bin_details(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530770 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Nabin Haita804d6d2018-08-29 13:34:58 +0530771 ["projected_qty", "actual_qty", "reserved_qty"], as_dict=True, cache=True) \
Shreya Shahbe770332018-08-22 14:45:22 +0530772 or {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530773
774@frappe.whitelist()
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530775def get_serial_no_details(item_code, warehouse, stock_qty, serial_no):
776 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "serial_no":serial_no})
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530777 serial_no = get_serial_no(args)
778 return {'serial_no': serial_no}
Rushabh Mehta985cb822016-12-30 15:06:54 +0530779
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530780@frappe.whitelist()
Shreyaa20157a2018-04-13 12:03:42 +0530781def 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 +0530782 bin_details_and_serial_nos = {}
783 bin_details_and_serial_nos.update(get_bin_details(item_code, warehouse))
Rushabh Mehta49f97472018-08-30 18:50:48 +0530784 if flt(stock_qty) > 0:
Shreyaa20157a2018-04-13 12:03:42 +0530785 if has_batch_no:
786 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty})
787 serial_no = get_serial_no(args)
788 bin_details_and_serial_nos.update({'serial_no': serial_no})
789 return bin_details_and_serial_nos
790
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530791 bin_details_and_serial_nos.update(get_serial_no_details(item_code, warehouse, stock_qty, serial_no))
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530792 return bin_details_and_serial_nos
Anand Doshidffec8f2014-07-01 17:45:15 +0530793
794@frappe.whitelist()
Shreyaa20157a2018-04-13 12:03:42 +0530795def get_batch_qty_and_serial_no(batch_no, stock_qty, warehouse, item_code, has_serial_no):
796 batch_qty_and_serial_no = {}
797 batch_qty_and_serial_no.update(get_batch_qty(batch_no, warehouse, item_code))
798
799 if (flt(batch_qty_and_serial_no.get('actual_batch_qty')) >= flt(stock_qty)) and has_serial_no:
800 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "batch_no":batch_no})
801 serial_no = get_serial_no(args)
802 batch_qty_and_serial_no.update({'serial_no': serial_no})
803 return batch_qty_and_serial_no
804
805@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530806def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +0700807 from erpnext.stock.doctype.batch import batch
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +0530808 if batch_no:
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530809 return {'actual_batch_qty': batch.get_batch_qty(batch_no, warehouse)}
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530810
Anand Doshidffec8f2014-07-01 17:45:15 +0530811@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530812def apply_price_list(args, as_doc=False):
813 """Apply pricelist on a document-like dict object and return as
814 {'parent': dict, 'children': list}
815
816 :param args: See below
817 :param as_doc: Updates value in the passed dict
818
Anand Doshidffec8f2014-07-01 17:45:15 +0530819 args = {
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530820 "doctype": "",
821 "name": "",
822 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
Anand Doshidffec8f2014-07-01 17:45:15 +0530823 "conversion_rate": 1.0,
824 "selling_price_list": None,
825 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530826 "price_list_uom_dependant": None,
Anand Doshidffec8f2014-07-01 17:45:15 +0530827 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530828 "doctype": "",
829 "name": "",
Anand Doshidffec8f2014-07-01 17:45:15 +0530830 "supplier": None,
831 "transaction_date": None,
832 "conversion_rate": 1.0,
833 "buying_price_list": None,
Anand Doshidffec8f2014-07-01 17:45:15 +0530834 "ignore_pricing_rule": 0/1
835 }
836 """
837 args = process_args(args)
838
839 parent = get_price_list_currency_and_exchange_rate(args)
840 children = []
841
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530842 if "items" in args:
843 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +0530844 args.update(parent)
845
846 for item in item_list:
847 args_copy = frappe._dict(args.copy())
848 args_copy.update(item)
849 item_details = apply_price_list_on_item(args_copy)
850 children.append(item_details)
851
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530852 if as_doc:
Shreya Shahb13a54a2017-12-06 19:17:04 +0530853 args.price_list_currency = parent.price_list_currency,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530854 args.plc_conversion_rate = parent.plc_conversion_rate
855 if args.get('items'):
856 for i, item in enumerate(args.get('items')):
857 for fieldname in children[i]:
858 # if the field exists in the original doc
859 # update the value
860 if fieldname in item and fieldname not in ("name", "doctype"):
861 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530862 return args
863 else:
864 return {
865 "parent": parent,
866 "children": children
867 }
Anand Doshidffec8f2014-07-01 17:45:15 +0530868
869def apply_price_list_on_item(args):
870 item_details = frappe._dict()
871 item_doc = frappe.get_doc("Item", args.item_code)
872 get_price_list_rate(args, item_doc, item_details)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530873
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530874 item_details.update(get_pricing_rule_for_item(args, item_details.price_list_rate))
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530875
Anand Doshidffec8f2014-07-01 17:45:15 +0530876 return item_details
877
878def get_price_list_currency(price_list):
Neil Trini Lasradoadb1b2c2015-03-18 11:40:39 +0530879 if price_list:
880 result = frappe.db.get_value("Price List", {"name": price_list,
881 "enabled": 1}, ["name", "currency"], as_dict=True)
Anand Doshidffec8f2014-07-01 17:45:15 +0530882
Neil Trini Lasradoadb1b2c2015-03-18 11:40:39 +0530883 if not result:
Rushabh Mehta985cb822016-12-30 15:06:54 +0530884 throw(_("Price List {0} is disabled or does not exist").format(price_list))
Anand Doshidffec8f2014-07-01 17:45:15 +0530885
Neil Trini Lasradoadb1b2c2015-03-18 11:40:39 +0530886 return result.currency
Anand Doshidffec8f2014-07-01 17:45:15 +0530887
Shreya Shahb13a54a2017-12-06 19:17:04 +0530888def get_price_list_uom_dependant(price_list):
889 if price_list:
890 result = frappe.db.get_value("Price List", {"name": price_list,
Mangesh-Khairnar558a5c12019-06-24 17:28:47 +0530891 "enabled": 1}, ["name", "price_not_uom_dependent"], as_dict=True)
Shreya Shahb13a54a2017-12-06 19:17:04 +0530892
893 if not result:
894 throw(_("Price List {0} is disabled or does not exist").format(price_list))
895
Mangesh-Khairnar558a5c12019-06-24 17:28:47 +0530896 return not result.price_not_uom_dependent
Shreya Shahb13a54a2017-12-06 19:17:04 +0530897
898
Anand Doshidffec8f2014-07-01 17:45:15 +0530899def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +0530900 if not args.price_list:
901 return {}
902
Shreya3f778522018-05-15 16:59:20 +0530903 if args.doctype in ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']:
904 args.update({"exchange_rate": "for_selling"})
905 elif args.doctype in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']:
906 args.update({"exchange_rate": "for_buying"})
907
Anand Doshidffec8f2014-07-01 17:45:15 +0530908 price_list_currency = get_price_list_currency(args.price_list)
Shreya Shahb13a54a2017-12-06 19:17:04 +0530909 price_list_uom_dependant = get_price_list_uom_dependant(args.price_list)
Anand Doshidffec8f2014-07-01 17:45:15 +0530910 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +0100911 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +0530912
Nabin Haitdd82bf22015-05-11 16:49:17 +0530913 if (not plc_conversion_rate) or (price_list_currency and args.price_list_currency \
914 and price_list_currency != args.price_list_currency):
Rushabh Mehta6b537922017-03-14 16:59:11 +0530915 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
tundebabzy6e90f492018-02-12 10:48:57 +0100916 plc_conversion_rate = get_exchange_rate(price_list_currency, company_currency,
Shreya3f778522018-05-15 16:59:20 +0530917 args.transaction_date, args.exchange_rate) or plc_conversion_rate
Anand Doshidffec8f2014-07-01 17:45:15 +0530918
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530919 return frappe._dict({
Anand Doshidffec8f2014-07-01 17:45:15 +0530920 "price_list_currency": price_list_currency,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530921 "price_list_uom_dependant": price_list_uom_dependant,
Anand Doshidffec8f2014-07-01 17:45:15 +0530922 "plc_conversion_rate": plc_conversion_rate
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530923 })
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +0530924
925@frappe.whitelist()
926def get_default_bom(item_code=None):
927 if item_code:
928 bom = frappe.db.get_value("BOM", {"docstatus": 1, "is_default": 1, "is_active": 1, "item": item_code})
929 if bom:
930 return bom
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530931
Manas Solanki087a2252018-05-04 16:02:38 +0530932def get_valuation_rate(item_code, company, warehouse=None):
Manas Solankib16a4ec2018-05-04 16:49:33 +0530933 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530934 item_group = get_item_group_defaults(item_code, company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500935 brand = get_brand_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +0530936 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +0530937 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +0530938 if not warehouse:
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500939 warehouse = item.get("default_warehouse") or item_group.get("default_warehouse") or brand.get("default_warehouse")
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530940
941 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Saurabhbd01a812016-03-07 14:32:23 +0530942 ["valuation_rate"], as_dict=True) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530943
Manas Solankie3910fb2018-05-16 15:50:17 +0530944 elif not item.get("is_stock_item"):
Nabin Haitfe876c02017-03-06 16:32:57 +0530945 valuation_rate =frappe.db.sql("""select sum(base_net_amount) / sum(qty*conversion_factor)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530946 from `tabPurchase Invoice Item`
Saurabhbd01a812016-03-07 14:32:23 +0530947 where item_code = %s and docstatus=1""", item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530948
Saurabhbd01a812016-03-07 14:32:23 +0530949 if valuation_rate:
950 return {"valuation_rate": valuation_rate[0][0] or 0.0}
951 else:
952 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530953
Saurabh2d7af632016-02-26 11:09:20 +0530954def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +0530955 if out.valuation_rate:
956 out.update({
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530957 "gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)
Saurabh5ada14b2016-02-26 18:02:55 +0530958 })
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530959
Saurabhd3135532016-02-25 18:59:20 +0530960 return out
mbauskar6f603392016-01-21 16:10:22 +0530961
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530962@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530963def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +0530964 serial_no = None
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530965 if isinstance(args, string_types):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530966 args = json.loads(args)
967 args = frappe._dict(args)
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530968 if args.get('doctype') == 'Sales Invoice' and not args.get('update_stock'):
969 return ""
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530970 if args.get('warehouse') and args.get('stock_qty') and args.get('item_code'):
Shreyaa20157a2018-04-13 12:03:42 +0530971 has_serial_no = frappe.get_value('Item', {'item_code': args.item_code}, "has_serial_no")
Shreyaa20157a2018-04-13 12:03:42 +0530972 if args.get('batch_no') and has_serial_no == 1:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530973 return get_serial_no_batchwise(args, sales_order)
Shreyaa20157a2018-04-13 12:03:42 +0530974 elif has_serial_no == 1:
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530975 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 +0530976 args = process_args(args)
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530977 serial_no = get_serial_nos_by_fifo(args, sales_order)
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +0530978
979 if not serial_no and serial_nos:
980 # For POS
981 serial_no = serial_nos
982
983 return serial_no
Manas Solankie5e87f72018-05-28 20:07:08 +0530984
985
986def update_party_blanket_order(args, out):
987 blanket_order_details = get_blanket_order_details(args)
988 if blanket_order_details:
989 out.update(blanket_order_details)
990
991@frappe.whitelist()
992def get_blanket_order_details(args):
993 if isinstance(args, string_types):
994 args = frappe._dict(json.loads(args))
995
996 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +0530997 condition = ''
Manas Solankie5e87f72018-05-28 20:07:08 +0530998 if args.item_code:
999 if args.customer and args.doctype == "Sales Order":
Nabin Hait2737b082018-06-14 18:07:22 +05301000 condition = ' and bo.customer=%(customer)s'
Manas Solankie5e87f72018-05-28 20:07:08 +05301001 elif args.supplier and args.doctype == "Purchase Order":
Nabin Hait2737b082018-06-14 18:07:22 +05301002 condition = ' and bo.supplier=%(supplier)s'
Manas Solankie5e87f72018-05-28 20:07:08 +05301003 if args.blanket_order:
Nabin Hait2737b082018-06-14 18:07:22 +05301004 condition += ' and bo.name =%(blanket_order)s'
1005 if args.transaction_date:
1006 condition += ' and bo.to_date>=%(transaction_date)s'
1007
Manas Solankie5e87f72018-05-28 20:07:08 +05301008 blanket_order_details = frappe.db.sql('''
1009 select boi.rate as blanket_order_rate, bo.name as blanket_order
1010 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
Nabin Hait2737b082018-06-14 18:07:22 +05301011 where bo.company=%(company)s and boi.item_code=%(item_code)s
1012 and bo.docstatus=1 and bo.name = boi.parent {0}
1013 '''.format(condition), args, as_dict=True)
1014
Manas Solankie5e87f72018-05-28 20:07:08 +05301015 blanket_order_details = blanket_order_details[0] if blanket_order_details else ''
1016 return blanket_order_details
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301017
1018def get_so_reservation_for_item(args):
1019 reserved_so = None
1020 if args.get('against_sales_order'):
1021 if get_reserved_qty_for_so(args.get('against_sales_order'), args.get('item_code')):
1022 reserved_so = args.get('against_sales_order')
1023 elif args.get('against_sales_invoice'):
1024 sales_order = frappe.db.sql("""select sales_order from `tabSales Invoice Item` where
1025 parent=%s and item_code=%s""", (args.get('against_sales_invoice'), args.get('item_code')))
1026 if sales_order and sales_order[0]:
1027 if get_reserved_qty_for_so(sales_order[0][0], args.get('item_code')):
1028 reserved_so = sales_order[0]
1029 elif args.get("sales_order"):
1030 if get_reserved_qty_for_so(args.get('sales_order'), args.get('item_code')):
1031 reserved_so = args.get('sales_order')
1032 return reserved_so
1033
1034def get_reserved_qty_for_so(sales_order, item_code):
1035 reserved_qty = frappe.db.sql("""select sum(qty) from `tabSales Order Item`
1036 where parent=%s and item_code=%s and ensure_delivery_based_on_produced_serial_no=1
1037 """, (sales_order, item_code))
1038 if reserved_qty and reserved_qty[0][0]:
1039 return reserved_qty[0][0]
1040 else:
1041 return 0