blob: 19597c3d993c955b75678373ea5a253ac1d61866 [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
Chillar Anand915b3432021-09-02 16:44:59 +05305
6import json
7
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05308import frappe
9from frappe import _, throw
Rushabh Mehta66e08e32014-09-29 12:17:03 +053010from frappe.model.meta import get_field_precision
Chillar Anand915b3432021-09-02 16:44:59 +053011from frappe.utils import add_days, add_months, cint, cstr, flt, getdate
12from six import iteritems, string_types
Nabin Hait98c2a052014-05-05 18:41:41 +053013
Chillar Anand915b3432021-09-02 16:44:59 +053014from erpnext import get_company_currency
15from erpnext.accounts.doctype.pricing_rule.pricing_rule import (
16 get_pricing_rule_for_item,
17 set_transaction_type,
18)
19from erpnext.setup.doctype.brand.brand import get_brand_defaults
20from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults
21from erpnext.setup.utils import get_exchange_rate
22from erpnext.stock.doctype.batch.batch import get_batch_no
23from erpnext.stock.doctype.item.item import get_item_defaults, get_uom_conv_factor
24from erpnext.stock.doctype.item_manufacturer.item_manufacturer import get_item_manufacturer_part_no
25from erpnext.stock.doctype.price_list.price_list import get_price_list_details
tundebabzyacccdb32017-11-23 08:35:15 +010026
Saqibac9e6ff2021-01-28 17:58:55 +053027sales_doctypes = ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice', 'POS Invoice']
Nabin Hait0d1ccc32019-02-14 18:30:10 +053028purchase_doctypes = ['Material Request', 'Supplier Quotation', 'Purchase Order', 'Purchase Receipt', 'Purchase Invoice']
29
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053030@frappe.whitelist()
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053031def get_item_details(args, doc=None, for_validate=False, overwrite_warehouse=True):
Nabin Hait436f5262014-02-10 14:47:54 +053032 """
33 args = {
34 "item_code": "",
35 "warehouse": None,
36 "customer": "",
37 "conversion_rate": 1.0,
38 "selling_price_list": None,
39 "price_list_currency": None,
Nabin Hait615d3422014-02-25 19:01:20 +053040 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +053041 "doctype": "",
42 "name": "",
Nabin Hait436f5262014-02-10 14:47:54 +053043 "supplier": None,
44 "transaction_date": None,
45 "conversion_rate": 1.0,
46 "buying_price_list": None,
47 "is_subcontracted": "Yes" / "No",
Nabin Hait444f9562014-06-20 15:59:49 +053048 "ignore_pricing_rule": 0/1
Neil Trini Lasrado6e343e22016-03-09 17:02:59 +053049 "project": ""
Saif Ur Rehman2689dea2019-01-09 13:43:06 +050050 "set_warehouse": ""
Nabin Hait436f5262014-02-10 14:47:54 +053051 }
52 """
Suraj Shetty182f4de2019-08-16 08:16:22 +053053
Anand Doshidffec8f2014-07-01 17:45:15 +053054 args = process_args(args)
marination392f3232020-07-14 17:03:17 +053055 for_validate = process_string_args(for_validate)
56 overwrite_warehouse = process_string_args(overwrite_warehouse)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053057 item = frappe.get_cached_doc("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053058 validate_item_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053059
Suraj Shetty182f4de2019-08-16 08:16:22 +053060 out = get_basic_details(args, item, overwrite_warehouse)
61
Deepesh Gargef0d26c2020-01-06 15:34:15 +053062 if isinstance(doc, string_types):
63 doc = json.loads(doc)
64
65 if doc and doc.get('doctype') == 'Purchase Invoice':
66 args['bill_date'] = doc.get('bill_date')
67
68 if doc:
69 args['posting_date'] = doc.get('posting_date')
70 args['transaction_date'] = doc.get('transaction_date')
71
Saif Ur Rehman67786682018-12-27 02:11:07 +050072 get_item_tax_template(args, item, out)
Saif Ur Rehman648bd152019-01-03 03:48:01 +050073 out["item_tax_rate"] = get_item_tax_map(args.company, args.get("item_tax_template") if out.get("item_tax_template") is None \
74 else out.get("item_tax_template"), as_json=True)
Saif Ur Rehman67786682018-12-27 02:11:07 +050075
Rushabh Mehta708e47a2018-08-08 16:37:31 +053076 get_party_item_code(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053077
Rushabh Mehta708e47a2018-08-08 16:37:31 +053078 set_valuation_rate(out, args)
Anand Doshibd67e872014-04-11 16:51:27 +053079
Manas Solankie5e87f72018-05-28 20:07:08 +053080 update_party_blanket_order(args, out)
81
Ankush16d4de52021-08-09 10:41:24 +053082 out.update(get_price_list_rate(args, item))
Nabin Hait436f5262014-02-10 14:47:54 +053083
Rushabh Mehtab46069d2016-01-15 16:59:26 +053084 if args.customer and cint(args.is_pos):
Anuja Pawarf132ed42021-05-07 12:11:09 +053085 out.update(get_pos_profile_item_details(args.company, args, update_data=True))
Rushabh Mehta6b537922017-03-14 16:59:11 +053086
Nabin Haitda17f9c2020-05-01 18:16:25 +053087 if (args.get("doctype") == "Material Request" and
88 args.get("material_request_type") == "Material Transfer"):
89 out.update(get_bin_details(args.item_code, args.get("from_warehouse")))
90
91 elif out.get("warehouse"):
Nabin Haitda0ba152021-04-30 18:38:41 +053092 out.update(get_bin_details(args.item_code, out.warehouse, args.company))
Anand Doshibd67e872014-04-11 16:51:27 +053093
Nabin Haita3dd72a2014-05-28 12:49:20 +053094 # update args with out, if key or value not exists
Achilles Rasquinha714c7462018-02-15 11:28:55 +053095 for key, value in iteritems(out):
Nabin Haita3dd72a2014-05-28 12:49:20 +053096 if args.get(key) is None:
97 args[key] = value
98
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053099 data = get_pricing_rule_for_item(args, out.price_list_rate,
100 doc, for_validate=for_validate)
101
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530102 out.update(data)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530103
104 update_stock(args, out)
105
106 if args.transaction_date and item.lead_time_days:
107 out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
108 item.lead_time_days)
109
110 if args.get("is_subcontracted") == "Yes":
111 out.bom = args.get('bom') or get_default_bom(args.item_code)
112
113 get_gross_profit(out)
114 if args.doctype == 'Material Request':
115 out.rate = args.rate or out.price_list_rate
Rohit Waghchaure1bc53a32021-03-31 15:28:26 +0530116 out.amount = flt(args.qty) * flt(out.rate)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530117
118 return out
119
120def update_stock(args, out):
pratu16x7577e4c42017-06-23 11:39:03 +0530121 if (args.get("doctype") == "Delivery Note" or
Nabin Hait3ce41d62017-05-03 18:22:24 +0530122 (args.get("doctype") == "Sales Invoice" and args.get('update_stock'))) \
123 and out.warehouse and out.stock_qty > 0:
pratu16x7577e4c42017-06-23 11:39:03 +0530124
Nabin Hait8fac2ad2017-05-18 11:54:24 +0530125 if out.has_batch_no and not args.get("batch_no"):
Rushabh Mehta551406a2017-04-21 12:40:19 +0530126 out.batch_no = get_batch_no(out.item_code, out.warehouse, out.qty)
rohitwaghchaure2fb8cc52017-11-29 13:50:04 +0530127 actual_batch_qty = get_batch_qty(out.batch_no, out.warehouse, out.item_code)
128 if actual_batch_qty:
129 out.update(actual_batch_qty)
Shreya14bd43d2018-04-27 16:24:05 +0530130
131 if out.has_serial_no and args.get('batch_no'):
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530132 reserved_so = get_so_reservation_for_item(args)
Shreya14bd43d2018-04-27 16:24:05 +0530133 out.batch_no = args.get('batch_no')
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530134 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Shreya14bd43d2018-04-27 16:24:05 +0530135
136 elif out.has_serial_no:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530137 reserved_so = get_so_reservation_for_item(args)
138 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Rushabh Mehta551406a2017-04-21 12:40:19 +0530139
Anand Doshibd67e872014-04-11 16:51:27 +0530140
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530141def set_valuation_rate(out, args):
Nabin Hait50238c32018-08-08 18:43:04 +0530142 if frappe.db.exists("Product Bundle", args.item_code, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530143 valuation_rate = 0.0
144 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530145
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530146 for bundle_item in bundled_items.items:
147 valuation_rate += \
148 flt(get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get("valuation_rate") \
149 * bundle_item.qty)
Anand Doshi70f57eb2015-11-27 14:37:40 +0530150
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530151 out.update({
152 "valuation_rate": valuation_rate
153 })
154
155 else:
156 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
157
Nabin Hait436f5262014-02-10 14:47:54 +0530158
Anand Doshidffec8f2014-07-01 17:45:15 +0530159def process_args(args):
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530160 if isinstance(args, string_types):
Anand Doshidffec8f2014-07-01 17:45:15 +0530161 args = json.loads(args)
162
163 args = frappe._dict(args)
164
Anand Doshidffec8f2014-07-01 17:45:15 +0530165 if not args.get("price_list"):
166 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
167
168 if args.barcode:
169 args.item_code = get_item_code(barcode=args.barcode)
170 elif not args.item_code and args.serial_no:
171 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530172
mbauskar6f603392016-01-21 16:10:22 +0530173 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530174 return args
175
marination392f3232020-07-14 17:03:17 +0530176def process_string_args(args):
177 if isinstance(args, string_types):
178 args = json.loads(args)
179 return args
tundebabzyacccdb32017-11-23 08:35:15 +0100180
Neil Trini Lasrado4abda672015-02-25 17:34:27 +0530181@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530182def get_item_code(barcode=None, serial_no=None):
183 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100184 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530185 if not item_code:
186 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530187 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530188 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530189 if not item_code:
190 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530191
Nabin Hait436f5262014-02-10 14:47:54 +0530192 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530193
tundebabzyacccdb32017-11-23 08:35:15 +0100194
Nabin Hait436f5262014-02-10 14:47:54 +0530195def validate_item_details(args, item):
196 if not args.company:
197 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530198
Nabin Hait436f5262014-02-10 14:47:54 +0530199 from erpnext.stock.doctype.item.item import validate_end_of_life
Anand Doshi21e09a22015-10-29 12:21:41 +0530200 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530201
tundebabzyacccdb32017-11-23 08:35:15 +0100202 if args.transaction_type == "selling" and cint(item.has_variants):
Umair Sayyed72534de2016-04-15 12:52:12 +0530203 throw(_("Item {0} is a template, please select one of its variants").format(item.name))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530204
tundebabzyacccdb32017-11-23 08:35:15 +0100205 elif args.transaction_type == "buying" and args.doctype != "Material Request":
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530206 if args.get("is_subcontracted") == "Yes" and item.is_sub_contracted_item != 1:
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530207 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530208
tundebabzyacccdb32017-11-23 08:35:15 +0100209
Suraj Shetty182f4de2019-08-16 08:16:22 +0530210def get_basic_details(args, item, overwrite_warehouse=True):
tundebabzyacccdb32017-11-23 08:35:15 +0100211 """
212 :param args: {
213 "item_code": "",
214 "warehouse": None,
215 "customer": "",
216 "conversion_rate": 1.0,
217 "selling_price_list": None,
218 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530219 "price_list_uom_dependant": None,
tundebabzyacccdb32017-11-23 08:35:15 +0100220 "plc_conversion_rate": 1.0,
221 "doctype": "",
222 "name": "",
223 "supplier": None,
224 "transaction_date": None,
225 "conversion_rate": 1.0,
226 "buying_price_list": None,
227 "is_subcontracted": "Yes" / "No",
228 "ignore_pricing_rule": 0/1
229 "project": "",
230 barcode: "",
231 serial_no: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100232 currency: "",
233 update_stock: "",
234 price_list: "",
235 company: "",
236 order_type: "",
237 is_pos: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100238 project: "",
239 qty: "",
240 stock_qty: "",
ronelvcabrera370cdc02019-12-04 18:37:11 +0800241 conversion_factor: "",
242 against_blanket_order: 0/1
tundebabzyacccdb32017-11-23 08:35:15 +0100243 }
244 :param item: `item_code` of Item object
245 :return: frappe._dict
246 """
247
Rushabh Mehta1a763742014-10-03 16:36:43 +0530248 if not item:
249 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530250
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530251 if item.variant_of:
252 item.update_template_tables()
253
Manas Solankib16a4ec2018-05-04 16:49:33 +0530254 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530255 item_group_defaults = get_item_group_defaults(item.name, args.company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500256 brand_defaults = get_brand_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530257
Saqib438e0432020-04-03 10:02:56 +0530258 defaults = frappe._dict({
259 'item_defaults': item_defaults,
260 'item_group_defaults': item_group_defaults,
261 'brand_defaults': brand_defaults
262 })
marinatione05013e2020-04-06 22:13:13 +0530263
Saqib438e0432020-04-03 10:02:56 +0530264 warehouse = get_item_warehouse(item, args, overwrite_warehouse, defaults)
Nabin Hait36028bf2014-02-12 19:09:28 +0530265
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530266 if args.get('doctype') == "Material Request" and not args.get('material_request_type'):
267 args['material_request_type'] = frappe.db.get_value('Material Request',
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530268 args.get('name'), 'material_request_type', cache=True)
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530269
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530270 expense_account = None
271
272 if args.get('doctype') == 'Purchase Invoice' and item.is_fixed_asset:
273 from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
274 expense_account = get_asset_category_account(fieldname = "fixed_asset_account", item = args.item_code, company= args.company)
275
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530276 #Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
Saqib438e0432020-04-03 10:02:56 +0530277 if not args.get('uom'):
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530278 if args.get('doctype') in sales_doctypes:
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530279 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530280 elif (args.get('doctype') in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']) or \
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530281 (args.get('doctype') == 'Material Request' and args.get('material_request_type') == 'Purchase'):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530282 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
283 else:
284 args.uom = item.stock_uom
285
Rohit Waghchauree1f07042021-08-23 14:27:55 +0530286 if (args.get("batch_no") and
287 item.name != frappe.get_cached_value('Batch', args.get("batch_no"), 'item')):
288 args['batch_no'] = ''
289
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530290 out = frappe._dict({
Nabin Hait139dc7b2014-02-12 14:53:18 +0530291 "item_code": item.name,
292 "item_name": item.item_name,
Neil Trini Lasradoc48f06c2015-02-10 16:49:16 +0530293 "description": cstr(item.description).strip(),
294 "image": cstr(item.image).strip(),
Saurabhd3135532016-02-25 18:59:20 +0530295 "warehouse": warehouse,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500296 "income_account": get_default_income_account(args, item_defaults, item_group_defaults, brand_defaults),
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530297 "expense_account": expense_account or get_default_expense_account(args, item_defaults, item_group_defaults, brand_defaults) ,
GangaManoj657e9b52021-07-06 16:51:12 +0530298 "discount_account": None or get_default_discount_account(args, item_defaults),
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500299 "cost_center": get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults),
Rushabh Mehta551406a2017-04-21 12:40:19 +0530300 'has_serial_no': item.has_serial_no,
301 'has_batch_no': item.has_batch_no,
marinatione05013e2020-04-06 22:13:13 +0530302 "batch_no": args.get("batch_no"),
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530303 "uom": args.uom,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530304 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
Fisher Yu2cd49f52019-01-11 18:01:33 +0800305 "qty": flt(args.qty) or 1.0,
306 "stock_qty": flt(args.qty) or 1.0,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530307 "price_list_rate": 0.0,
308 "base_price_list_rate": 0.0,
309 "rate": 0.0,
310 "base_rate": 0.0,
311 "amount": 0.0,
312 "base_amount": 0.0,
Nabin Hait82e3e252015-02-23 16:58:30 +0530313 "net_rate": 0.0,
314 "net_amount": 0.0,
Saurabhc6dbe702015-10-19 14:17:52 +0530315 "discount_percentage": 0.0,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500316 "supplier": get_default_supplier(args, item_defaults, item_group_defaults, brand_defaults),
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530317 "update_stock": args.get("update_stock") if args.get('doctype') in ['Sales Invoice', 'Purchase Invoice'] else 0,
Rohit Waghchaurec858d522016-12-12 13:01:43 +0530318 "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 +0530319 "is_fixed_asset": item.is_fixed_asset,
Nabin Haite45ec662018-08-01 17:44:34 +0530320 "last_purchase_rate": item.last_purchase_rate if args.get("doctype") in ["Purchase Order"] else 0,
ronelvcabrera370cdc02019-12-04 18:37:11 +0800321 "transaction_date": args.get("transaction_date"),
rohitwaghchaureaa85e512020-05-19 19:51:45 +0530322 "against_blanket_order": args.get("against_blanket_order"),
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530323 "bom_no": item.get("default_bom"),
rohitwaghchaure7b4a6542021-09-03 22:00:14 +0530324 "weight_per_unit": args.get("weight_per_unit") or item.get("weight_per_unit"),
325 "weight_uom": args.get("weight_uom") or item.get("weight_uom")
Nabin Hait139dc7b2014-02-12 14:53:18 +0530326 })
Anand Doshibd67e872014-04-11 16:51:27 +0530327
Zlash65627be1d2019-01-15 14:16:32 +0530328 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zlash6580f5cb02018-08-29 11:39:08 +0530329 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530330
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530331 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530332 if item.stock_uom == args.uom:
333 out.conversion_factor = 1.0
334 else:
335 out.conversion_factor = args.conversion_factor or \
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530336 get_conversion_factor(item.name, args.uom).get("conversion_factor")
mbauskar287fe812017-04-10 19:15:57 +0530337
338 args.conversion_factor = out.conversion_factor
339 out.stock_qty = out.qty * out.conversion_factor
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530340
Shreya Shah44fa9a62018-01-08 14:58:20 +0530341 # calculate last purchase rate
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530342 if args.get('doctype') in purchase_doctypes:
343 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
344 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 +0530345
Nabin Haitb09ed412015-02-17 10:33:58 +0530346 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530347 for d in [
348 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530349 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530350 ["Cost Center", "cost_center", "cost_center"],
351 ["Warehouse", "warehouse", ""]]:
Nabin Hait33df0b42018-05-26 09:09:02 +0530352 if not out[d[1]]:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530353 out[d[1]] = frappe.get_cached_value('Company', args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530354
Giovanni2144e022017-12-10 17:27:09 +0100355 for fieldname in ("item_name", "item_group", "barcodes", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530356 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530357
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530358 if args.get("manufacturer"):
359 part_no = get_item_manufacturer_part_no(args.get("item_code"), args.get("manufacturer"))
360 if part_no:
361 out["manufacturer_part_no"] = part_no
362 else:
363 out["manufacturer_part_no"] = None
364 out["manufacturer"] = None
marination3e7a8ab2020-04-07 21:00:57 +0530365 else:
rohitwaghchaurebe16e5c2020-05-01 10:50:17 +0530366 data = frappe.get_value("Item", item.name,
367 ["default_item_manufacturer", "default_manufacturer_part_no"] , as_dict=1)
368
369 if data:
370 out.update({
371 "manufacturer": data.default_item_manufacturer,
372 "manufacturer_part_no": data.default_manufacturer_part_no
373 })
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530374
Nabin Hait34c551d2019-07-03 10:34:31 +0530375 child_doctype = args.doctype + ' Item'
376 meta = frappe.get_meta(child_doctype)
377 if meta.get_field("barcode"):
378 update_barcode_value(out)
379
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530380 if out.get("weight_per_unit"):
381 out['total_weight'] = out.weight_per_unit * out.stock_qty
382
Nabin Hait436f5262014-02-10 14:47:54 +0530383 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530384
Saqib438e0432020-04-03 10:02:56 +0530385def get_item_warehouse(item, args, overwrite_warehouse, defaults={}):
386 if not defaults:
387 defaults = frappe._dict({
388 'item_defaults' : get_item_defaults(item.name, args.company),
389 'item_group_defaults' : get_item_group_defaults(item.name, args.company),
390 'brand_defaults' : get_brand_defaults(item.name, args.company)
391 })
392
393 if overwrite_warehouse or not args.warehouse:
394 warehouse = (
395 args.get("set_warehouse") or
396 defaults.item_defaults.get("default_warehouse") or
397 defaults.item_group_defaults.get("default_warehouse") or
398 defaults.brand_defaults.get("default_warehouse") or
399 args.get('warehouse')
400 )
401
402 if not warehouse:
403 defaults = frappe.defaults.get_defaults() or {}
404 warehouse_exists = frappe.db.exists("Warehouse", {
405 'name': defaults.default_warehouse,
406 'company': args.company
407 })
408 if defaults.get("default_warehouse") and warehouse_exists:
409 warehouse = defaults.default_warehouse
410
411 else:
412 warehouse = args.get('warehouse')
marinatione05013e2020-04-06 22:13:13 +0530413
Marica3b1be2b2020-10-22 17:04:31 +0530414 if not warehouse:
415 default_warehouse = frappe.db.get_single_value("Stock Settings", "default_warehouse")
416 if frappe.db.get_value("Warehouse", default_warehouse, "company") == args.company:
417 return default_warehouse
418
Saqib438e0432020-04-03 10:02:56 +0530419 return warehouse
420
Nabin Hait34c551d2019-07-03 10:34:31 +0530421def update_barcode_value(out):
Nabin Hait34c551d2019-07-03 10:34:31 +0530422 barcode_data = get_barcode_data([out])
423
424 # If item has one barcode then update the value of the barcode field
425 if barcode_data and len(barcode_data.get(out.item_code)) == 1:
426 out['barcode'] = barcode_data.get(out.item_code)[0]
427
Saqiba6f98d42020-07-23 18:51:26 +0530428def get_barcode_data(items_list):
429 # get itemwise batch no data
430 # exmaple: {'LED-GRE': [Batch001, Batch002]}
431 # where LED-GRE is item code, SN0001 is serial no and Pune is warehouse
432
433 itemwise_barcode = {}
434 for item in items_list:
435 barcodes = frappe.db.sql("""
436 select barcode from `tabItem Barcode` where parent = %s
437 """, item.item_code, as_dict=1)
438
439 for barcode in barcodes:
440 if item.item_code not in itemwise_barcode:
441 itemwise_barcode.setdefault(item.item_code, [])
442 itemwise_barcode[item.item_code].append(barcode.get("barcode"))
443
444 return itemwise_barcode
445
Zlash6580f5cb02018-08-29 11:39:08 +0530446@frappe.whitelist()
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530447def get_item_tax_info(company, tax_category, item_codes, item_rates=None, item_tax_templates=None):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500448 out = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530449
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530450 if item_tax_templates is None:
Deepesh Gargcae42b482021-06-25 13:34:00 +0530451 item_tax_templates = {}
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +0530452
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530453 if item_rates is None:
454 item_rates = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530455
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530456 if isinstance(item_codes, (str,)):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500457 item_codes = json.loads(item_codes)
458
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530459 if isinstance(item_rates, (str,)):
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530460 item_rates = json.loads(item_rates)
461
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530462 if isinstance(item_tax_templates, (str,)):
Deepesh Garg94d46042021-06-23 20:56:27 +0530463 item_tax_templates = json.loads(item_tax_templates)
464
Saif Ur Rehman67786682018-12-27 02:11:07 +0500465 for item_code in item_codes:
Deepesh Garg94d46042021-06-23 20:56:27 +0530466 if not item_code or item_code[1] in out or not item_tax_templates.get(item_code[1]):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500467 continue
Deepesh Garg94d46042021-06-23 20:56:27 +0530468
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530469 out[item_code[1]] = {}
470 item = frappe.get_cached_doc("Item", item_code[0])
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530471 args = {"company": company, "tax_category": tax_category, "net_rate": item_rates.get(item_code[1])}
Deepesh Garg269962a2021-06-23 22:52:51 +0530472
473 if item_tax_templates:
474 args.update({"item_tax_template": item_tax_templates.get(item_code[1])})
Deepesh Garg94d46042021-06-23 20:56:27 +0530475
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530476 get_item_tax_template(args, item, out[item_code[1]])
477 out[item_code[1]]["item_tax_rate"] = get_item_tax_map(company, out[item_code[1]].get("item_tax_template"), as_json=True)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500478
479 return out
480
481def get_item_tax_template(args, item, out):
482 """
483 args = {
484 "tax_category": None
485 "item_tax_template": None
486 }
487 """
488 item_tax_template = args.get("item_tax_template")
Deepesh Garg94d46042021-06-23 20:56:27 +0530489 item_tax_template = _get_item_tax_template(args, item.taxes, out)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500490
491 if not item_tax_template:
492 item_group = item.item_group
493 while item_group and not item_tax_template:
494 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
495 item_tax_template = _get_item_tax_template(args, item_group_doc.taxes, out)
496 item_group = item_group_doc.parent_item_group
497
18alantom308905b2021-05-03 23:34:34 +0530498def _get_item_tax_template(args, taxes, out=None, for_validate=False):
499 if out is None:
500 out = {}
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530501 taxes_with_validity = []
502 taxes_with_no_validity = []
503
504 for tax in taxes:
mohammadahmad1990261ecba2020-06-25 01:56:53 +0500505 tax_company = frappe.get_value("Item Tax Template", tax.item_tax_template, 'company')
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530506 if (tax.valid_from or tax.maximum_net_rate) and tax_company == args['company']:
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530507 # In purchase Invoice first preference will be given to supplier invoice date
508 # if supplier date is not present then posting date
509 validation_date = args.get('transaction_date') or args.get('bill_date') or args.get('posting_date')
510
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530511 if getdate(tax.valid_from) <= getdate(validation_date) \
512 and is_within_valid_range(args, tax):
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530513 taxes_with_validity.append(tax)
514 else:
mohammadahmad1990261ecba2020-06-25 01:56:53 +0500515 if tax_company == args['company']:
mohammadahmad1990e39649b2020-06-18 11:42:53 +0500516 taxes_with_no_validity.append(tax)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530517
518 if taxes_with_validity:
519 taxes = sorted(taxes_with_validity, key = lambda i: i.valid_from, reverse=True)
520 else:
521 taxes = taxes_with_no_validity
522
523 if for_validate:
524 return [tax.item_tax_template for tax in taxes if (cstr(tax.tax_category) == cstr(args.get('tax_category')) \
525 and (tax.item_tax_template not in taxes))]
526
527 # all templates have validity and no template is valid
528 if not taxes_with_validity and (not taxes_with_no_validity):
529 return None
530
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530531 # do not change if already a valid template
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530532 if args.get('item_tax_template') in {t.item_tax_template for t in taxes}:
Deepesh Garg94d46042021-06-23 20:56:27 +0530533 out["item_tax_template"] = args.get('item_tax_template')
Deepesh Garg3646c302021-06-05 13:21:03 +0530534 return args.get('item_tax_template')
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530535
Saif Ur Rehman67786682018-12-27 02:11:07 +0500536 for tax in taxes:
537 if cstr(tax.tax_category) == cstr(args.get("tax_category")):
538 out["item_tax_template"] = tax.item_tax_template
539 return tax.item_tax_template
540 return None
541
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530542def is_within_valid_range(args, tax):
543 if not flt(tax.maximum_net_rate):
544 # No range specified, just ignore
545 return True
546 elif flt(tax.minimum_net_rate) <= flt(args.get('net_rate')) <= flt(tax.maximum_net_rate):
547 return True
548
549 return False
550
Saif Ur Rehman67786682018-12-27 02:11:07 +0500551@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500552def get_item_tax_map(company, item_tax_template, as_json=True):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500553 item_tax_map = {}
554 if item_tax_template:
555 template = frappe.get_cached_doc("Item Tax Template", item_tax_template)
556 for d in template.taxes:
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500557 if frappe.get_cached_value("Account", d.tax_type, "company") == company:
558 item_tax_map[d.tax_type] = d.tax_rate
Saif Ur Rehman67786682018-12-27 02:11:07 +0500559
560 return json.dumps(item_tax_map) if as_json else item_tax_map
561
562@frappe.whitelist()
Zlash6580f5cb02018-08-29 11:39:08 +0530563def calculate_service_end_date(args, item=None):
564 args = process_args(args)
565 if not item:
566 item = frappe.get_cached_doc("Item", args.item_code)
567
Zlash65627be1d2019-01-15 14:16:32 +0530568 doctype = args.get("parenttype") or args.get("doctype")
Zlash65a3dd7982019-01-15 14:36:11 +0530569 if doctype == "Sales Invoice":
570 enable_deferred = "enable_deferred_revenue"
571 no_of_months = "no_of_months"
572 account = "deferred_revenue_account"
573 else:
574 enable_deferred = "enable_deferred_expense"
575 no_of_months = "no_of_months_exp"
576 account = "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530577
Zlash6580f5cb02018-08-29 11:39:08 +0530578 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
Zarrare83ff382018-09-21 15:45:40 +0530579 service_end_date = add_months(service_start_date, item.get(no_of_months))
Zlash6580f5cb02018-08-29 11:39:08 +0530580 deferred_detail = {
Zlash6580f5cb02018-08-29 11:39:08 +0530581 "service_start_date": service_start_date,
582 "service_end_date": service_end_date
583 }
Zarrare83ff382018-09-21 15:45:40 +0530584 deferred_detail[enable_deferred] = item.get(enable_deferred)
585 deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)
Zlash6580f5cb02018-08-29 11:39:08 +0530586
587 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100588
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500589def get_default_income_account(args, item, item_group, brand):
Manas Solanki38667ab2018-05-16 16:55:23 +0530590 return (item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530591 or item_group.get("income_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500592 or brand.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530593 or args.income_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530594
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500595def get_default_expense_account(args, item, item_group, brand):
Manas Solanki38667ab2018-05-16 16:55:23 +0530596 return (item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530597 or item_group.get("expense_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500598 or brand.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530599 or args.expense_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530600
GangaManoj0b7d8fb2021-07-13 01:37:30 +0530601def get_default_discount_account(args, item):
602 return (item.get("default_discount_account")
GangaManoj657e9b52021-07-06 16:51:12 +0530603 or args.discount_account)
604
Zarrare83ff382018-09-21 15:45:40 +0530605def get_default_deferred_account(args, item, fieldname=None):
Zlash65627be1d2019-01-15 14:16:32 +0530606 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zarrare83ff382018-09-21 15:45:40 +0530607 return (item.get(fieldname)
608 or args.get(fieldname)
609 or frappe.get_cached_value('Company', args.company, "default_"+fieldname))
Manas Solanki03938482018-05-14 16:16:46 +0530610 else:
611 return None
612
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530613def get_default_cost_center(args, item=None, item_group=None, brand=None, company=None):
Nabin Hait50238c32018-08-08 18:43:04 +0530614 cost_center = None
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530615
616 if not company and args.get("company"):
617 company = args.get("company")
618
Nabin Hait50238c32018-08-08 18:43:04 +0530619 if args.get('project'):
620 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530621
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530622 if not cost_center and (item and item_group and brand):
Nabin Hait50238c32018-08-08 18:43:04 +0530623 if args.get('customer'):
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500624 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 +0530625 else:
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500626 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 +0530627
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530628 elif not cost_center and args.get("item_code") and company:
629 for method in ["get_item_defaults", "get_item_group_defaults", "get_brand_defaults"]:
630 path = "erpnext.stock.get_item_details.{0}".format(method)
631 data = frappe.get_attr(path)(args.get("item_code"), company)
632
633 if data and (data.selling_cost_center or data.buying_cost_center):
634 return data.selling_cost_center or data.buying_cost_center
635
636 if not cost_center and args.get("cost_center"):
637 cost_center = args.get("cost_center")
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530638
639 if (company and cost_center
640 and frappe.get_cached_value("Cost Center", cost_center, "company") != company):
641 return None
642
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530643 if not cost_center and company:
644 cost_center = frappe.get_cached_value("Company",
645 company, "cost_center")
646
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530647 return cost_center
Rushabh Mehta1a763742014-10-03 16:36:43 +0530648
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500649def get_default_supplier(args, item, item_group, brand):
Shreya Shah3c9839f2018-07-17 18:01:44 +0530650 return (item.get("default_supplier")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500651 or item_group.get("default_supplier")
652 or brand.get("default_supplier"))
Shreya Shah3c9839f2018-07-17 18:01:44 +0530653
Ankush16d4de52021-08-09 10:41:24 +0530654def get_price_list_rate(args, item_doc, out=None):
655 if out is None:
656 out = frappe._dict()
657
Anand Doshi39a28912016-02-15 11:42:18 +0530658 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530659
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530660 if meta.get_field("currency") or args.get('currency'):
Maricae8bc9122021-04-19 11:05:21 +0530661 if not args.get("price_list_currency") or not args.get("plc_conversion_rate"):
662 # if currency and plc_conversion_rate exist then
663 # `get_price_list_currency_and_exchange_rate` has already been called
664 pl_details = get_price_list_currency_and_exchange_rate(args)
665 args.update(pl_details)
666
Nabin Hait06c8cf42019-05-16 19:17:02 +0530667 if meta.get_field("currency"):
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530668 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530669
Ankush16d4de52021-08-09 10:41:24 +0530670 price_list_rate = get_price_list_rate_for(args, item_doc.name)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530671
hiousi1516e292019-01-08 18:34:08 +0100672 # variant
Ankush16d4de52021-08-09 10:41:24 +0530673 if price_list_rate is None and item_doc.variant_of:
hiousi1516e292019-01-08 18:34:08 +0100674 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530675
676 # insert in database
Ankush16d4de52021-08-09 10:41:24 +0530677 if price_list_rate is None:
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530678 if args.price_list and args.rate:
679 insert_item_price(args)
Ankush16d4de52021-08-09 10:41:24 +0530680 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530681
Nabin Hait436f5262014-02-10 14:47:54 +0530682 out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) \
683 / flt(args.conversion_rate)
mbauskar287fe812017-04-10 19:15:57 +0530684
Nabin Hait34d28222016-01-19 15:45:49 +0530685 if not out.price_list_rate and args.transaction_type=="buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530686 from erpnext.stock.doctype.item.item import get_last_purchase_details
Anand Doshibd67e872014-04-11 16:51:27 +0530687 out.update(get_last_purchase_details(item_doc.name,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530688 args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530689
Ankush16d4de52021-08-09 10:41:24 +0530690 return out
691
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530692def insert_item_price(args):
693 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530694 if frappe.db.get_value("Price List", args.price_list, "currency", cache=True) == args.currency \
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530695 and cint(frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")):
696 if frappe.has_permission("Item Price", "write"):
Nabin Haite45ec662018-08-01 17:44:34 +0530697 price_list_rate = (args.rate / args.get('conversion_factor')
698 if args.get("conversion_factor") else args.rate)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530699
Nabin Haitb479a872018-09-07 13:17:11 +0530700 item_price = frappe.db.get_value('Item Price',
701 {'item_code': args.item_code, 'price_list': args.price_list, 'currency': args.currency},
702 ['name', 'price_list_rate'], as_dict=1)
703 if item_price and item_price.name:
704 if item_price.price_list_rate != price_list_rate:
705 frappe.db.set_value('Item Price', item_price.name, "price_list_rate", price_list_rate)
706 frappe.msgprint(_("Item Price updated for {0} in Price List {1}").format(args.item_code,
707 args.price_list), alert=True)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530708 else:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530709 item_price = frappe.get_doc({
710 "doctype": "Item Price",
711 "price_list": args.price_list,
712 "item_code": args.item_code,
713 "currency": args.currency,
714 "price_list_rate": price_list_rate
715 })
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530716 item_price.insert()
717 frappe.msgprint(_("Item Price added for {0} in Price List {1}").format(args.item_code,
Rushabh Mehta49f97472018-08-30 18:50:48 +0530718 args.price_list), alert=True)
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530719
Nabin Hait01ca3e52019-01-25 16:25:15 +0530720def get_item_price(args, item_code, ignore_party=False):
Nabin Haite45ec662018-08-01 17:44:34 +0530721 """
722 Get name, price_list_rate from Item Price based on conditions
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530723 Check if the desired qty is within the increment of the packing list.
Nabin Haite45ec662018-08-01 17:44:34 +0530724 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
Nabin Hait03b116d2020-01-20 15:45:04 +0530725 optional fields transaction_date, customer, supplier
Nabin Haite45ec662018-08-01 17:44:34 +0530726 :param item_code: str, Item Doctype field item_code
727 """
728
729 args['item_code'] = item_code
Nabin Haite45ec662018-08-01 17:44:34 +0530730
Nabin Hait01ca3e52019-01-25 16:25:15 +0530731 conditions = """where item_code=%(item_code)s
Nabin Haite45ec662018-08-01 17:44:34 +0530732 and price_list=%(price_list)s
733 and ifnull(uom, '') in ('', %(uom)s)"""
734
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530735 conditions += "and ifnull(batch_no, '') in ('', %(batch_no)s)"
736
Nabin Hait01ca3e52019-01-25 16:25:15 +0530737 if not ignore_party:
Nabin Hait01ca3e52019-01-25 16:25:15 +0530738 if args.get("customer"):
739 conditions += " and customer=%(customer)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530740 elif args.get("supplier"):
Nabin Hait01ca3e52019-01-25 16:25:15 +0530741 conditions += " and supplier=%(supplier)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530742 else:
Saqib41b47a62020-05-15 04:24:36 +0530743 conditions += "and (customer is null or customer = '') and (supplier is null or supplier = '')"
Nabin Hait01ca3e52019-01-25 16:25:15 +0530744
Nabin Haite45ec662018-08-01 17:44:34 +0530745 if args.get('transaction_date'):
746 conditions += """ and %(transaction_date)s between
747 ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
Deepesh Gargf15ff5f2020-07-11 13:58:53 +0530748
Andy Zhub60abb02020-07-03 14:13:15 +1200749 if args.get('posting_date'):
750 conditions += """ and %(posting_date)s between
751 ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
Nabin Haite45ec662018-08-01 17:44:34 +0530752
753 return frappe.db.sql(""" select name, price_list_rate, uom
754 from `tabItem Price` {conditions}
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530755 order by valid_from desc, batch_no desc, uom desc """.format(conditions=conditions), args)
Nabin Haite45ec662018-08-01 17:44:34 +0530756
757def get_price_list_rate_for(args, item_code):
758 """
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530759 :param customer: link to Customer DocType
760 :param supplier: link to Supplier DocType
Nabin Haite45ec662018-08-01 17:44:34 +0530761 :param price_list: str (Standard Buying or Standard Selling)
762 :param item_code: str, Item Doctype field item_code
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530763 :param qty: Desired Qty
Nabin Haite45ec662018-08-01 17:44:34 +0530764 :param transaction_date: Date of the price
765 """
766 item_price_args = {
767 "item_code": item_code,
768 "price_list": args.get('price_list'),
769 "customer": args.get('customer'),
770 "supplier": args.get('supplier'),
771 "uom": args.get('uom'),
Nabin Haite45ec662018-08-01 17:44:34 +0530772 "transaction_date": args.get('transaction_date'),
Andy Zhub60abb02020-07-03 14:13:15 +1200773 "posting_date": args.get('posting_date'),
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530774 "batch_no": args.get('batch_no')
Nabin Haite45ec662018-08-01 17:44:34 +0530775 }
776
777 item_price_data = 0
778 price_list_rate = get_item_price(item_price_args, item_code)
779 if price_list_rate:
780 desired_qty = args.get("qty")
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530781 if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
Nabin Haite45ec662018-08-01 17:44:34 +0530782 item_price_data = price_list_rate
783 else:
Don-Leopardoccdf1932020-01-09 03:54:43 -0300784 for field in ["customer", "supplier"]:
Nabin Haite45ec662018-08-01 17:44:34 +0530785 del item_price_args[field]
786
Nabin Haite321fbb2020-01-16 13:37:25 +0530787 general_price_list_rate = get_item_price(item_price_args, item_code,
788 ignore_party=args.get("ignore_party"))
Don-Leopardoccdf1932020-01-09 03:54:43 -0300789
Nabin Haite45ec662018-08-01 17:44:34 +0530790 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530791 item_price_args["uom"] = args.get("stock_uom")
Nabin Hait01ca3e52019-01-25 16:25:15 +0530792 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 +0530793
794 if general_price_list_rate:
795 item_price_data = general_price_list_rate
796
797 if item_price_data:
798 if item_price_data[0][2] == args.get("uom"):
799 return item_price_data[0][1]
800 elif not args.get('price_list_uom_dependant'):
801 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
802 else:
803 return item_price_data[0][1]
804
805def check_packing_list(price_list_rate_name, desired_qty, item_code):
806 """
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530807 Check if the desired qty is within the increment of the packing list.
Nabin Haite45ec662018-08-01 17:44:34 +0530808 :param price_list_rate_name: Name of Item Price
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530809 :param desired_qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530810 :param item_code: str, Item Doctype field item_code
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530811 :param qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530812 """
813
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530814 flag = True
Nabin Haite45ec662018-08-01 17:44:34 +0530815 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530816 if item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +0530817 packing_increment = desired_qty % item_price.packing_unit
818
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530819 if packing_increment != 0:
820 flag = False
821
822 return flag
Rushabh Mehta1a763742014-10-03 16:36:43 +0530823
Nabin Hait436f5262014-02-10 14:47:54 +0530824def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +0530825 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +0530826
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +0530827 company_currency = frappe.get_cached_value('Company', args.company, "default_currency")
828 if (not args.conversion_rate and args.currency==company_currency):
Anand Doshife13bfe2015-08-25 12:49:40 +0530829 args.conversion_rate = 1.0
830
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +0530831 if (not args.ignore_conversion_rate and args.conversion_rate == 1 and args.currency!=company_currency):
832 args.conversion_rate = get_exchange_rate(args.currency,
833 company_currency, args.transaction_date, "for_buying") or 1.0
834
Nabin Hait436f5262014-02-10 14:47:54 +0530835 # validate currency conversion rate
Anand Doshibd67e872014-04-11 16:51:27 +0530836 validate_conversion_rate(args.currency, args.conversion_rate,
Nabin Hait436f5262014-02-10 14:47:54 +0530837 meta.get_label("conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530838
839 args.conversion_rate = flt(args.conversion_rate,
840 get_field_precision(meta.get_field("conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530841 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530842
Nabin Hait06c8cf42019-05-16 19:17:02 +0530843 if args.price_list:
844 if (not args.plc_conversion_rate
845 and args.price_list_currency==frappe.db.get_value("Price List", args.price_list, "currency", cache=True)):
846 args.plc_conversion_rate = 1.0
Manas Solanki3504a232018-06-06 12:46:06 +0530847
Nabin Hait06c8cf42019-05-16 19:17:02 +0530848 # validate price list currency conversion rate
849 if not args.get("price_list_currency"):
850 throw(_("Price List Currency not selected"))
851 else:
852 validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate,
853 meta.get_label("plc_conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530854
Nabin Hait06c8cf42019-05-16 19:17:02 +0530855 if meta.get_field("plc_conversion_rate"):
856 args.plc_conversion_rate = flt(args.plc_conversion_rate,
857 get_field_precision(meta.get_field("plc_conversion_rate"),
858 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530859
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530860def get_party_item_code(args, item_doc, out):
Nabin Hait34d28222016-01-19 15:45:49 +0530861 if args.transaction_type=="selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +0530862 out.customer_item_code = None
Nabin Hait34c551d2019-07-03 10:34:31 +0530863
864 if args.quotation_to and args.quotation_to != 'Customer':
865 return
866
Nabin Hait79f091e2014-12-26 11:41:15 +0530867 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +0530868
869 if customer_item_code:
870 out.customer_item_code = customer_item_code[0].ref_code
871 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +0530872 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +0530873 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
874 if customer_group_item_code and not customer_group_item_code[0].customer_name:
875 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +0530876
Nabin Hait34d28222016-01-19 15:45:49 +0530877 if args.transaction_type=="buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +0530878 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +0530879 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +0530880
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530881def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530882 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +0530883
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530884 if not frappe.flags.pos_profile and not pos_profile:
885 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get('pos_profile'))
Anand Doshibd67e872014-04-11 16:51:27 +0530886
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530887 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +0530888 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530889 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530890 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530891
Nabin Hait436f5262014-02-10 14:47:54 +0530892 if res.get("warehouse"):
Saurabhd3135532016-02-25 18:59:20 +0530893 res.actual_qty = get_bin_details(args.item_code,
Nabin Hait436f5262014-02-10 14:47:54 +0530894 res.warehouse).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +0530895
Nabin Hait436f5262014-02-10 14:47:54 +0530896 return res
897
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530898@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530899def get_pos_profile(company, pos_profile=None, user=None):
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530900 if pos_profile: return frappe.get_cached_doc('POS Profile', pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530901
902 if not user:
903 user = frappe.session['user']
904
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530905 condition = "pfu.user = %(user)s AND pfu.default=1"
906 if user and company:
907 condition = "pfu.user = %(user)s AND pf.company = %(company)s AND pfu.default=1"
908
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530909 pos_profile = frappe.db.sql("""SELECT pf.*
910 FROM
911 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
912 ON
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530913 pf.name = pfu.parent
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530914 WHERE
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530915 {cond} AND pf.disabled = 0
916 """.format(cond = condition), {
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530917 'user': user,
918 'company': company
919 }, as_dict=1)
Anand Doshibd67e872014-04-11 16:51:27 +0530920
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530921 if not pos_profile and company:
922 pos_profile = frappe.db.sql("""SELECT pf.*
923 FROM
924 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
925 ON
926 pf.name = pfu.parent
927 WHERE
928 pf.company = %(company)s AND pf.disabled = 0
929 """, {
930 'company': company
931 }, as_dict=1)
932
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530933 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +0530934
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530935def get_serial_nos_by_fifo(args, sales_order=None):
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530936 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
937 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530938 where item_code=%(item_code)s and warehouse=%(warehouse)s and
939 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
940 order by timestamp(purchase_date, purchase_time)
941 asc limit %(qty)s""",
942 {
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530943 "item_code": args.item_code,
944 "warehouse": args.warehouse,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530945 "qty": abs(cint(args.stock_qty)),
946 "sales_order": sales_order
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530947 }))
Nabin Hait08222152014-02-28 11:30:47 +0530948
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530949def get_serial_no_batchwise(args, sales_order=None):
Shreyaa20157a2018-04-13 12:03:42 +0530950 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
951 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530952 where item_code=%(item_code)s and warehouse=%(warehouse)s and
953 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
954 and batch_no=IF(%(batch_no)s IS NULL, batch_no, %(batch_no)s) order
955 by timestamp(purchase_date, purchase_time) asc limit %(qty)s""", {
Shreyaa20157a2018-04-13 12:03:42 +0530956 "item_code": args.item_code,
957 "warehouse": args.warehouse,
958 "batch_no": args.batch_no,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530959 "qty": abs(cint(args.stock_qty)),
960 "sales_order": sales_order
Shreyaa20157a2018-04-13 12:03:42 +0530961 }))
962
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530963@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530964def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530965 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530966 filters = {"parent": item_code, "uom": uom}
967 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +0530968 filters["parent"] = ("in", (item_code, variant_of))
Sagar Vora508189e2018-09-11 17:22:25 +0530969 conversion_factor = frappe.db.get_value("UOM Conversion Detail",
970 filters, "conversion_factor")
971 if not conversion_factor:
972 stock_uom = frappe.db.get_value("Item", item_code, "stock_uom")
973 conversion_factor = get_uom_conv_factor(uom, stock_uom)
rohitwaghchaureffdadbf2019-01-08 16:21:25 +0530974 return {"conversion_factor": conversion_factor or 1.0}
Nabin Hait08222152014-02-28 11:30:47 +0530975
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530976@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530977def get_projected_qty(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530978 return {"projected_qty": frappe.db.get_value("Bin",
Nabin Hait436f5262014-02-10 14:47:54 +0530979 {"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
Nabin Hait08222152014-02-28 11:30:47 +0530980
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530981@frappe.whitelist()
Anupam4980dd62021-03-15 11:37:46 +0530982def get_bin_details(item_code, warehouse, company=None):
983 bin_details = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Nabin Haita804d6d2018-08-29 13:34:58 +0530984 ["projected_qty", "actual_qty", "reserved_qty"], as_dict=True, cache=True) \
Shreya Shahbe770332018-08-22 14:45:22 +0530985 or {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
Anupam4980dd62021-03-15 11:37:46 +0530986 if company:
987 bin_details['company_total_stock'] = get_company_total_stock(item_code, company)
988 return bin_details
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530989
Anupam4980dd62021-03-15 11:37:46 +0530990def get_company_total_stock(item_code, company):
Anuja Pawarf132ed42021-05-07 12:11:09 +0530991 return frappe.db.sql("""SELECT sum(actual_qty) from
992 (`tabBin` INNER JOIN `tabWarehouse` ON `tabBin`.warehouse = `tabWarehouse`.name)
18alantome36f3032021-05-03 19:49:22 +0530993 WHERE `tabWarehouse`.company = %s and `tabBin`.item_code = %s""",
994 (company, item_code))[0][0]
Anupam4980dd62021-03-15 11:37:46 +0530995
996@frappe.whitelist()
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530997def get_serial_no_details(item_code, warehouse, stock_qty, serial_no):
998 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "serial_no":serial_no})
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530999 serial_no = get_serial_no(args)
1000 return {'serial_no': serial_no}
Rushabh Mehta985cb822016-12-30 15:06:54 +05301001
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301002@frappe.whitelist()
Rohit Waghchaure6daab3c2019-09-19 17:01:26 +05301003def 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 +05301004 bin_details_and_serial_nos = {}
1005 bin_details_and_serial_nos.update(get_bin_details(item_code, warehouse))
Rushabh Mehta49f97472018-08-30 18:50:48 +05301006 if flt(stock_qty) > 0:
Shreyaa20157a2018-04-13 12:03:42 +05301007 if has_batch_no:
1008 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty})
1009 serial_no = get_serial_no(args)
1010 bin_details_and_serial_nos.update({'serial_no': serial_no})
1011 return bin_details_and_serial_nos
1012
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301013 bin_details_and_serial_nos.update(get_serial_no_details(item_code, warehouse, stock_qty, serial_no))
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301014 return bin_details_and_serial_nos
Anand Doshidffec8f2014-07-01 17:45:15 +05301015
1016@frappe.whitelist()
Shreyaa20157a2018-04-13 12:03:42 +05301017def get_batch_qty_and_serial_no(batch_no, stock_qty, warehouse, item_code, has_serial_no):
1018 batch_qty_and_serial_no = {}
1019 batch_qty_and_serial_no.update(get_batch_qty(batch_no, warehouse, item_code))
1020
1021 if (flt(batch_qty_and_serial_no.get('actual_batch_qty')) >= flt(stock_qty)) and has_serial_no:
1022 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "batch_no":batch_no})
1023 serial_no = get_serial_no(args)
1024 batch_qty_and_serial_no.update({'serial_no': serial_no})
1025 return batch_qty_and_serial_no
1026
1027@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +05301028def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +07001029 from erpnext.stock.doctype.batch import batch
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +05301030 if batch_no:
Rushabh Mehtae385b5b2017-04-20 15:21:01 +05301031 return {'actual_batch_qty': batch.get_batch_qty(batch_no, warehouse)}
Rushabh Mehta1e8025b2015-07-24 15:16:25 +05301032
Anand Doshidffec8f2014-07-01 17:45:15 +05301033@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301034def apply_price_list(args, as_doc=False):
1035 """Apply pricelist on a document-like dict object and return as
1036 {'parent': dict, 'children': list}
1037
1038 :param args: See below
1039 :param as_doc: Updates value in the passed dict
1040
Anand Doshidffec8f2014-07-01 17:45:15 +05301041 args = {
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301042 "doctype": "",
1043 "name": "",
1044 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
Anand Doshidffec8f2014-07-01 17:45:15 +05301045 "conversion_rate": 1.0,
1046 "selling_price_list": None,
1047 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +05301048 "price_list_uom_dependant": None,
Anand Doshidffec8f2014-07-01 17:45:15 +05301049 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301050 "doctype": "",
1051 "name": "",
Anand Doshidffec8f2014-07-01 17:45:15 +05301052 "supplier": None,
1053 "transaction_date": None,
1054 "conversion_rate": 1.0,
1055 "buying_price_list": None,
Anand Doshidffec8f2014-07-01 17:45:15 +05301056 "ignore_pricing_rule": 0/1
1057 }
1058 """
1059 args = process_args(args)
1060
1061 parent = get_price_list_currency_and_exchange_rate(args)
Maricae8bc9122021-04-19 11:05:21 +05301062 args.update(parent)
1063
Anand Doshidffec8f2014-07-01 17:45:15 +05301064 children = []
1065
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301066 if "items" in args:
1067 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +05301068 args.update(parent)
1069
1070 for item in item_list:
1071 args_copy = frappe._dict(args.copy())
1072 args_copy.update(item)
1073 item_details = apply_price_list_on_item(args_copy)
1074 children.append(item_details)
1075
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301076 if as_doc:
Shreya Shahb13a54a2017-12-06 19:17:04 +05301077 args.price_list_currency = parent.price_list_currency,
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301078 args.plc_conversion_rate = parent.plc_conversion_rate
1079 if args.get('items'):
1080 for i, item in enumerate(args.get('items')):
1081 for fieldname in children[i]:
1082 # if the field exists in the original doc
1083 # update the value
1084 if fieldname in item and fieldname not in ("name", "doctype"):
1085 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301086 return args
1087 else:
1088 return {
1089 "parent": parent,
1090 "children": children
1091 }
Anand Doshidffec8f2014-07-01 17:45:15 +05301092
1093def apply_price_list_on_item(args):
Anand Doshidffec8f2014-07-01 17:45:15 +05301094 item_doc = frappe.get_doc("Item", args.item_code)
Ankush16d4de52021-08-09 10:41:24 +05301095 item_details = get_price_list_rate(args, item_doc)
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301096
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +05301097 item_details.update(get_pricing_rule_for_item(args, item_details.price_list_rate))
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301098
Anand Doshidffec8f2014-07-01 17:45:15 +05301099 return item_details
1100
Anand Doshidffec8f2014-07-01 17:45:15 +05301101def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +05301102 if not args.price_list:
1103 return {}
1104
Shreya3f778522018-05-15 16:59:20 +05301105 if args.doctype in ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']:
1106 args.update({"exchange_rate": "for_selling"})
1107 elif args.doctype in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']:
1108 args.update({"exchange_rate": "for_buying"})
1109
rohitwaghchaurea85ddf22019-11-19 18:47:48 +05301110 price_list_details = get_price_list_details(args.price_list)
1111
1112 price_list_currency = price_list_details.get("currency")
1113 price_list_uom_dependant = price_list_details.get("price_list_uom_dependant")
1114
Anand Doshidffec8f2014-07-01 17:45:15 +05301115 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +01001116 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +05301117
Nabin Haitdd82bf22015-05-11 16:49:17 +05301118 if (not plc_conversion_rate) or (price_list_currency and args.price_list_currency \
1119 and price_list_currency != args.price_list_currency):
Rushabh Mehta6b537922017-03-14 16:59:11 +05301120 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
tundebabzy6e90f492018-02-12 10:48:57 +01001121 plc_conversion_rate = get_exchange_rate(price_list_currency, company_currency,
Shreya3f778522018-05-15 16:59:20 +05301122 args.transaction_date, args.exchange_rate) or plc_conversion_rate
Anand Doshidffec8f2014-07-01 17:45:15 +05301123
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301124 return frappe._dict({
Anand Doshidffec8f2014-07-01 17:45:15 +05301125 "price_list_currency": price_list_currency,
Shreya Shahb13a54a2017-12-06 19:17:04 +05301126 "price_list_uom_dependant": price_list_uom_dependant,
Maricae8bc9122021-04-19 11:05:21 +05301127 "plc_conversion_rate": plc_conversion_rate or 1
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301128 })
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +05301129
1130@frappe.whitelist()
1131def get_default_bom(item_code=None):
1132 if item_code:
1133 bom = frappe.db.get_value("BOM", {"docstatus": 1, "is_default": 1, "is_active": 1, "item": item_code})
1134 if bom:
1135 return bom
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301136
Deepesh Garg15ff6a52020-02-18 12:28:41 +05301137@frappe.whitelist()
Manas Solanki087a2252018-05-04 16:02:38 +05301138def get_valuation_rate(item_code, company, warehouse=None):
Manas Solankib16a4ec2018-05-04 16:49:33 +05301139 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +05301140 item_group = get_item_group_defaults(item_code, company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001141 brand = get_brand_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +05301142 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +05301143 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +05301144 if not warehouse:
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001145 warehouse = item.get("default_warehouse") or item_group.get("default_warehouse") or brand.get("default_warehouse")
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301146
1147 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Saurabhbd01a812016-03-07 14:32:23 +05301148 ["valuation_rate"], as_dict=True) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301149
Manas Solankie3910fb2018-05-16 15:50:17 +05301150 elif not item.get("is_stock_item"):
Nabin Haitfe876c02017-03-06 16:32:57 +05301151 valuation_rate =frappe.db.sql("""select sum(base_net_amount) / sum(qty*conversion_factor)
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301152 from `tabPurchase Invoice Item`
Saurabhbd01a812016-03-07 14:32:23 +05301153 where item_code = %s and docstatus=1""", item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301154
Saurabhbd01a812016-03-07 14:32:23 +05301155 if valuation_rate:
1156 return {"valuation_rate": valuation_rate[0][0] or 0.0}
1157 else:
1158 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301159
Saurabh2d7af632016-02-26 11:09:20 +05301160def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +05301161 if out.valuation_rate:
1162 out.update({
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301163 "gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)
Saurabh5ada14b2016-02-26 18:02:55 +05301164 })
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301165
Saurabhd3135532016-02-25 18:59:20 +05301166 return out
mbauskar6f603392016-01-21 16:10:22 +05301167
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301168@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301169def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +05301170 serial_no = None
Achilles Rasquinha56b2e122018-02-13 14:42:40 +05301171 if isinstance(args, string_types):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301172 args = json.loads(args)
1173 args = frappe._dict(args)
Rohit Waghchauredc981dc2017-04-03 14:17:08 +05301174 if args.get('doctype') == 'Sales Invoice' and not args.get('update_stock'):
1175 return ""
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301176 if args.get('warehouse') and args.get('stock_qty') and args.get('item_code'):
Shreyaa20157a2018-04-13 12:03:42 +05301177 has_serial_no = frappe.get_value('Item', {'item_code': args.item_code}, "has_serial_no")
Shreyaa20157a2018-04-13 12:03:42 +05301178 if args.get('batch_no') and has_serial_no == 1:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301179 return get_serial_no_batchwise(args, sales_order)
Shreyaa20157a2018-04-13 12:03:42 +05301180 elif has_serial_no == 1:
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301181 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 +05301182 args = process_args(args)
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301183 serial_no = get_serial_nos_by_fifo(args, sales_order)
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +05301184
1185 if not serial_no and serial_nos:
1186 # For POS
1187 serial_no = serial_nos
1188
1189 return serial_no
Manas Solankie5e87f72018-05-28 20:07:08 +05301190
1191
1192def update_party_blanket_order(args, out):
ronelvcabrera370cdc02019-12-04 18:37:11 +08001193 if out["against_blanket_order"]:
1194 blanket_order_details = get_blanket_order_details(args)
1195 if blanket_order_details:
1196 out.update(blanket_order_details)
Manas Solankie5e87f72018-05-28 20:07:08 +05301197
1198@frappe.whitelist()
1199def get_blanket_order_details(args):
1200 if isinstance(args, string_types):
1201 args = frappe._dict(json.loads(args))
1202
1203 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +05301204 condition = ''
Manas Solankie5e87f72018-05-28 20:07:08 +05301205 if args.item_code:
1206 if args.customer and args.doctype == "Sales Order":
Nabin Hait2737b082018-06-14 18:07:22 +05301207 condition = ' and bo.customer=%(customer)s'
Manas Solankie5e87f72018-05-28 20:07:08 +05301208 elif args.supplier and args.doctype == "Purchase Order":
Nabin Hait2737b082018-06-14 18:07:22 +05301209 condition = ' and bo.supplier=%(supplier)s'
Manas Solankie5e87f72018-05-28 20:07:08 +05301210 if args.blanket_order:
Nabin Hait2737b082018-06-14 18:07:22 +05301211 condition += ' and bo.name =%(blanket_order)s'
1212 if args.transaction_date:
1213 condition += ' and bo.to_date>=%(transaction_date)s'
1214
Manas Solankie5e87f72018-05-28 20:07:08 +05301215 blanket_order_details = frappe.db.sql('''
1216 select boi.rate as blanket_order_rate, bo.name as blanket_order
1217 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
Nabin Hait2737b082018-06-14 18:07:22 +05301218 where bo.company=%(company)s and boi.item_code=%(item_code)s
1219 and bo.docstatus=1 and bo.name = boi.parent {0}
1220 '''.format(condition), args, as_dict=True)
1221
Manas Solankie5e87f72018-05-28 20:07:08 +05301222 blanket_order_details = blanket_order_details[0] if blanket_order_details else ''
1223 return blanket_order_details
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301224
1225def get_so_reservation_for_item(args):
1226 reserved_so = None
1227 if args.get('against_sales_order'):
1228 if get_reserved_qty_for_so(args.get('against_sales_order'), args.get('item_code')):
1229 reserved_so = args.get('against_sales_order')
1230 elif args.get('against_sales_invoice'):
1231 sales_order = frappe.db.sql("""select sales_order from `tabSales Invoice Item` where
1232 parent=%s and item_code=%s""", (args.get('against_sales_invoice'), args.get('item_code')))
1233 if sales_order and sales_order[0]:
1234 if get_reserved_qty_for_so(sales_order[0][0], args.get('item_code')):
1235 reserved_so = sales_order[0]
1236 elif args.get("sales_order"):
1237 if get_reserved_qty_for_so(args.get('sales_order'), args.get('item_code')):
1238 reserved_so = args.get('sales_order')
1239 return reserved_so
1240
1241def get_reserved_qty_for_so(sales_order, item_code):
1242 reserved_qty = frappe.db.sql("""select sum(qty) from `tabSales Order Item`
1243 where parent=%s and item_code=%s and ensure_delivery_based_on_produced_serial_no=1
1244 """, (sales_order, item_code))
1245 if reserved_qty and reserved_qty[0][0]:
1246 return reserved_qty[0][0]
1247 else:
1248 return 0