blob: 3832415db6208ea9fd5ae21fe68e492a799a79c8 [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
Deepesh Gargef0d26c2020-01-06 15:34:15 +05307from frappe.utils import flt, cint, add_days, cstr, add_months, getdate
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +05308import json, copy
Nabin Hait34d28222016-01-19 15:45:49 +05309from erpnext.accounts.doctype.pricing_rule.pricing_rule import get_pricing_rule_for_item, set_transaction_type
Anand Doshidffec8f2014-07-01 17:45:15 +053010from erpnext.setup.utils import get_exchange_rate
Rushabh Mehta66e08e32014-09-29 12:17:03 +053011from frappe.model.meta import get_field_precision
Rushabh Mehta551406a2017-04-21 12:40:19 +053012from erpnext.stock.doctype.batch.batch import get_batch_no
tundebabzy6e90f492018-02-12 10:48:57 +010013from erpnext import get_company_currency
Sagar Vora508189e2018-09-11 17:22:25 +053014from erpnext.stock.doctype.item.item import get_item_defaults, get_uom_conv_factor
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053015from erpnext.stock.doctype.price_list.price_list import get_price_list_details
Shreya Shah3c9839f2018-07-17 18:01:44 +053016from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +050017from erpnext.setup.doctype.brand.brand import get_brand_defaults
Rohit Waghchaure3cf24362019-06-02 16:03:05 +053018from erpnext.stock.doctype.item_manufacturer.item_manufacturer import get_item_manufacturer_part_no
Nabin Hait98c2a052014-05-05 18:41:41 +053019
Achilles Rasquinha714c7462018-02-15 11:28:55 +053020from six import string_types, iteritems
tundebabzyacccdb32017-11-23 08:35:15 +010021
Saqibac9e6ff2021-01-28 17:58:55 +053022sales_doctypes = ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice', 'POS Invoice']
Nabin Hait0d1ccc32019-02-14 18:30:10 +053023purchase_doctypes = ['Material Request', 'Supplier Quotation', 'Purchase Order', 'Purchase Receipt', 'Purchase Invoice']
24
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053025@frappe.whitelist()
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053026def get_item_details(args, doc=None, for_validate=False, overwrite_warehouse=True):
Nabin Hait436f5262014-02-10 14:47:54 +053027 """
28 args = {
29 "item_code": "",
30 "warehouse": None,
31 "customer": "",
32 "conversion_rate": 1.0,
33 "selling_price_list": None,
34 "price_list_currency": None,
Nabin Hait615d3422014-02-25 19:01:20 +053035 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +053036 "doctype": "",
37 "name": "",
Nabin Hait436f5262014-02-10 14:47:54 +053038 "supplier": None,
39 "transaction_date": None,
40 "conversion_rate": 1.0,
41 "buying_price_list": None,
42 "is_subcontracted": "Yes" / "No",
Nabin Hait444f9562014-06-20 15:59:49 +053043 "ignore_pricing_rule": 0/1
Neil Trini Lasrado6e343e22016-03-09 17:02:59 +053044 "project": ""
Saif Ur Rehman2689dea2019-01-09 13:43:06 +050045 "set_warehouse": ""
Nabin Hait436f5262014-02-10 14:47:54 +053046 }
47 """
Suraj Shetty182f4de2019-08-16 08:16:22 +053048
Anand Doshidffec8f2014-07-01 17:45:15 +053049 args = process_args(args)
marination392f3232020-07-14 17:03:17 +053050 for_validate = process_string_args(for_validate)
51 overwrite_warehouse = process_string_args(overwrite_warehouse)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053052 item = frappe.get_cached_doc("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053053 validate_item_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053054
Suraj Shetty182f4de2019-08-16 08:16:22 +053055 out = get_basic_details(args, item, overwrite_warehouse)
56
Deepesh Gargef0d26c2020-01-06 15:34:15 +053057 if isinstance(doc, string_types):
58 doc = json.loads(doc)
59
60 if doc and doc.get('doctype') == 'Purchase Invoice':
61 args['bill_date'] = doc.get('bill_date')
62
63 if doc:
64 args['posting_date'] = doc.get('posting_date')
65 args['transaction_date'] = doc.get('transaction_date')
66
Saif Ur Rehman67786682018-12-27 02:11:07 +050067 get_item_tax_template(args, item, out)
Saif Ur Rehman648bd152019-01-03 03:48:01 +050068 out["item_tax_rate"] = get_item_tax_map(args.company, args.get("item_tax_template") if out.get("item_tax_template") is None \
69 else out.get("item_tax_template"), as_json=True)
Saif Ur Rehman67786682018-12-27 02:11:07 +050070
Rushabh Mehta708e47a2018-08-08 16:37:31 +053071 get_party_item_code(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053072
Rushabh Mehta708e47a2018-08-08 16:37:31 +053073 set_valuation_rate(out, args)
Anand Doshibd67e872014-04-11 16:51:27 +053074
Manas Solankie5e87f72018-05-28 20:07:08 +053075 update_party_blanket_order(args, out)
76
Saqib1f591ab2021-01-05 13:53:51 +053077 if not doc or cint(doc.get('is_return')) == 0:
78 # get price list rate only if the invoice is not a credit or debit note
79 get_price_list_rate(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053080
Rushabh Mehtab46069d2016-01-15 16:59:26 +053081 if args.customer and cint(args.is_pos):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +053082 out.update(get_pos_profile_item_details(args.company, args))
Rushabh Mehta6b537922017-03-14 16:59:11 +053083
Nabin Haitda17f9c2020-05-01 18:16:25 +053084 if (args.get("doctype") == "Material Request" and
85 args.get("material_request_type") == "Material Transfer"):
86 out.update(get_bin_details(args.item_code, args.get("from_warehouse")))
87
88 elif out.get("warehouse"):
Nabin Haitda0ba152021-04-30 18:38:41 +053089 out.update(get_bin_details(args.item_code, out.warehouse, args.company))
Anand Doshibd67e872014-04-11 16:51:27 +053090
Nabin Haita3dd72a2014-05-28 12:49:20 +053091 # update args with out, if key or value not exists
Achilles Rasquinha714c7462018-02-15 11:28:55 +053092 for key, value in iteritems(out):
Nabin Haita3dd72a2014-05-28 12:49:20 +053093 if args.get(key) is None:
94 args[key] = value
95
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053096 data = get_pricing_rule_for_item(args, out.price_list_rate,
97 doc, for_validate=for_validate)
98
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +053099 out.update(data)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530100
101 update_stock(args, out)
102
103 if args.transaction_date and item.lead_time_days:
104 out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
105 item.lead_time_days)
106
107 if args.get("is_subcontracted") == "Yes":
108 out.bom = args.get('bom') or get_default_bom(args.item_code)
109
110 get_gross_profit(out)
111 if args.doctype == 'Material Request':
112 out.rate = args.rate or out.price_list_rate
Rohit Waghchaure1bc53a32021-03-31 15:28:26 +0530113 out.amount = flt(args.qty) * flt(out.rate)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530114
115 return out
116
117def update_stock(args, out):
pratu16x7577e4c42017-06-23 11:39:03 +0530118 if (args.get("doctype") == "Delivery Note" or
Nabin Hait3ce41d62017-05-03 18:22:24 +0530119 (args.get("doctype") == "Sales Invoice" and args.get('update_stock'))) \
120 and out.warehouse and out.stock_qty > 0:
pratu16x7577e4c42017-06-23 11:39:03 +0530121
Nabin Hait8fac2ad2017-05-18 11:54:24 +0530122 if out.has_batch_no and not args.get("batch_no"):
Rushabh Mehta551406a2017-04-21 12:40:19 +0530123 out.batch_no = get_batch_no(out.item_code, out.warehouse, out.qty)
rohitwaghchaure2fb8cc52017-11-29 13:50:04 +0530124 actual_batch_qty = get_batch_qty(out.batch_no, out.warehouse, out.item_code)
125 if actual_batch_qty:
126 out.update(actual_batch_qty)
Shreya14bd43d2018-04-27 16:24:05 +0530127
128 if out.has_serial_no and args.get('batch_no'):
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530129 reserved_so = get_so_reservation_for_item(args)
Shreya14bd43d2018-04-27 16:24:05 +0530130 out.batch_no = args.get('batch_no')
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530131 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Shreya14bd43d2018-04-27 16:24:05 +0530132
133 elif out.has_serial_no:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530134 reserved_so = get_so_reservation_for_item(args)
135 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Rushabh Mehta551406a2017-04-21 12:40:19 +0530136
Anand Doshibd67e872014-04-11 16:51:27 +0530137
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530138def set_valuation_rate(out, args):
Nabin Hait50238c32018-08-08 18:43:04 +0530139 if frappe.db.exists("Product Bundle", args.item_code, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530140 valuation_rate = 0.0
141 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530142
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530143 for bundle_item in bundled_items.items:
144 valuation_rate += \
145 flt(get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get("valuation_rate") \
146 * bundle_item.qty)
Anand Doshi70f57eb2015-11-27 14:37:40 +0530147
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530148 out.update({
149 "valuation_rate": valuation_rate
150 })
151
152 else:
153 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
154
Nabin Hait436f5262014-02-10 14:47:54 +0530155
Anand Doshidffec8f2014-07-01 17:45:15 +0530156def process_args(args):
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530157 if isinstance(args, string_types):
Anand Doshidffec8f2014-07-01 17:45:15 +0530158 args = json.loads(args)
159
160 args = frappe._dict(args)
161
Anand Doshidffec8f2014-07-01 17:45:15 +0530162 if not args.get("price_list"):
163 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
164
165 if args.barcode:
166 args.item_code = get_item_code(barcode=args.barcode)
167 elif not args.item_code and args.serial_no:
168 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530169
mbauskar6f603392016-01-21 16:10:22 +0530170 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530171 return args
172
marination392f3232020-07-14 17:03:17 +0530173def process_string_args(args):
174 if isinstance(args, string_types):
175 args = json.loads(args)
176 return args
tundebabzyacccdb32017-11-23 08:35:15 +0100177
Neil Trini Lasrado4abda672015-02-25 17:34:27 +0530178@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530179def get_item_code(barcode=None, serial_no=None):
180 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100181 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530182 if not item_code:
183 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530184 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530185 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530186 if not item_code:
187 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530188
Nabin Hait436f5262014-02-10 14:47:54 +0530189 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530190
tundebabzyacccdb32017-11-23 08:35:15 +0100191
Nabin Hait436f5262014-02-10 14:47:54 +0530192def validate_item_details(args, item):
193 if not args.company:
194 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530195
Nabin Hait436f5262014-02-10 14:47:54 +0530196 from erpnext.stock.doctype.item.item import validate_end_of_life
Anand Doshi21e09a22015-10-29 12:21:41 +0530197 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530198
tundebabzyacccdb32017-11-23 08:35:15 +0100199 if args.transaction_type == "selling" and cint(item.has_variants):
Umair Sayyed72534de2016-04-15 12:52:12 +0530200 throw(_("Item {0} is a template, please select one of its variants").format(item.name))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530201
tundebabzyacccdb32017-11-23 08:35:15 +0100202 elif args.transaction_type == "buying" and args.doctype != "Material Request":
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530203 if args.get("is_subcontracted") == "Yes" and item.is_sub_contracted_item != 1:
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530204 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530205
tundebabzyacccdb32017-11-23 08:35:15 +0100206
Suraj Shetty182f4de2019-08-16 08:16:22 +0530207def get_basic_details(args, item, overwrite_warehouse=True):
tundebabzyacccdb32017-11-23 08:35:15 +0100208 """
209 :param args: {
210 "item_code": "",
211 "warehouse": None,
212 "customer": "",
213 "conversion_rate": 1.0,
214 "selling_price_list": None,
215 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530216 "price_list_uom_dependant": None,
tundebabzyacccdb32017-11-23 08:35:15 +0100217 "plc_conversion_rate": 1.0,
218 "doctype": "",
219 "name": "",
220 "supplier": None,
221 "transaction_date": None,
222 "conversion_rate": 1.0,
223 "buying_price_list": None,
224 "is_subcontracted": "Yes" / "No",
225 "ignore_pricing_rule": 0/1
226 "project": "",
227 barcode: "",
228 serial_no: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100229 currency: "",
230 update_stock: "",
231 price_list: "",
232 company: "",
233 order_type: "",
234 is_pos: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100235 project: "",
236 qty: "",
237 stock_qty: "",
ronelvcabrera370cdc02019-12-04 18:37:11 +0800238 conversion_factor: "",
239 against_blanket_order: 0/1
tundebabzyacccdb32017-11-23 08:35:15 +0100240 }
241 :param item: `item_code` of Item object
242 :return: frappe._dict
243 """
244
Rushabh Mehta1a763742014-10-03 16:36:43 +0530245 if not item:
246 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530247
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530248 if item.variant_of:
249 item.update_template_tables()
250
Manas Solankib16a4ec2018-05-04 16:49:33 +0530251 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530252 item_group_defaults = get_item_group_defaults(item.name, args.company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500253 brand_defaults = get_brand_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530254
Saqib438e0432020-04-03 10:02:56 +0530255 defaults = frappe._dict({
256 'item_defaults': item_defaults,
257 'item_group_defaults': item_group_defaults,
258 'brand_defaults': brand_defaults
259 })
marinatione05013e2020-04-06 22:13:13 +0530260
Saqib438e0432020-04-03 10:02:56 +0530261 warehouse = get_item_warehouse(item, args, overwrite_warehouse, defaults)
Nabin Hait36028bf2014-02-12 19:09:28 +0530262
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530263 if args.get('doctype') == "Material Request" and not args.get('material_request_type'):
264 args['material_request_type'] = frappe.db.get_value('Material Request',
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530265 args.get('name'), 'material_request_type', cache=True)
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530266
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530267 expense_account = None
268
269 if args.get('doctype') == 'Purchase Invoice' and item.is_fixed_asset:
270 from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
271 expense_account = get_asset_category_account(fieldname = "fixed_asset_account", item = args.item_code, company= args.company)
272
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530273 #Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
Saqib438e0432020-04-03 10:02:56 +0530274 if not args.get('uom'):
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530275 if args.get('doctype') in sales_doctypes:
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530276 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530277 elif (args.get('doctype') in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']) or \
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530278 (args.get('doctype') == 'Material Request' and args.get('material_request_type') == 'Purchase'):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530279 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
280 else:
281 args.uom = item.stock_uom
282
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530283 out = frappe._dict({
Nabin Hait139dc7b2014-02-12 14:53:18 +0530284 "item_code": item.name,
285 "item_name": item.item_name,
Neil Trini Lasradoc48f06c2015-02-10 16:49:16 +0530286 "description": cstr(item.description).strip(),
287 "image": cstr(item.image).strip(),
Saurabhd3135532016-02-25 18:59:20 +0530288 "warehouse": warehouse,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500289 "income_account": get_default_income_account(args, item_defaults, item_group_defaults, brand_defaults),
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530290 "expense_account": expense_account or get_default_expense_account(args, item_defaults, item_group_defaults, brand_defaults) ,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500291 "cost_center": get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults),
Rushabh Mehta551406a2017-04-21 12:40:19 +0530292 'has_serial_no': item.has_serial_no,
293 'has_batch_no': item.has_batch_no,
marinatione05013e2020-04-06 22:13:13 +0530294 "batch_no": args.get("batch_no"),
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530295 "uom": args.uom,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530296 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
Fisher Yu2cd49f52019-01-11 18:01:33 +0800297 "qty": flt(args.qty) or 1.0,
298 "stock_qty": flt(args.qty) or 1.0,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530299 "price_list_rate": 0.0,
300 "base_price_list_rate": 0.0,
301 "rate": 0.0,
302 "base_rate": 0.0,
303 "amount": 0.0,
304 "base_amount": 0.0,
Nabin Hait82e3e252015-02-23 16:58:30 +0530305 "net_rate": 0.0,
306 "net_amount": 0.0,
Saurabhc6dbe702015-10-19 14:17:52 +0530307 "discount_percentage": 0.0,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500308 "supplier": get_default_supplier(args, item_defaults, item_group_defaults, brand_defaults),
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530309 "update_stock": args.get("update_stock") if args.get('doctype') in ['Sales Invoice', 'Purchase Invoice'] else 0,
Rohit Waghchaurec858d522016-12-12 13:01:43 +0530310 "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 +0530311 "is_fixed_asset": item.is_fixed_asset,
Nabin Haite45ec662018-08-01 17:44:34 +0530312 "last_purchase_rate": item.last_purchase_rate if args.get("doctype") in ["Purchase Order"] else 0,
ronelvcabrera370cdc02019-12-04 18:37:11 +0800313 "transaction_date": args.get("transaction_date"),
rohitwaghchaureaa85e512020-05-19 19:51:45 +0530314 "against_blanket_order": args.get("against_blanket_order"),
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530315 "bom_no": item.get("default_bom"),
316 "weight_per_unit": args.get("weight_per_unit") or item.get("weight_per_unit"),
317 "weight_uom": args.get("weight_uom") or item.get("weight_uom")
Nabin Hait139dc7b2014-02-12 14:53:18 +0530318 })
Anand Doshibd67e872014-04-11 16:51:27 +0530319
Zlash65627be1d2019-01-15 14:16:32 +0530320 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zlash6580f5cb02018-08-29 11:39:08 +0530321 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530322
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530323 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530324 if item.stock_uom == args.uom:
325 out.conversion_factor = 1.0
326 else:
327 out.conversion_factor = args.conversion_factor or \
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530328 get_conversion_factor(item.name, args.uom).get("conversion_factor")
mbauskar287fe812017-04-10 19:15:57 +0530329
330 args.conversion_factor = out.conversion_factor
331 out.stock_qty = out.qty * out.conversion_factor
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530332
Shreya Shah44fa9a62018-01-08 14:58:20 +0530333 # calculate last purchase rate
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530334 if args.get('doctype') in purchase_doctypes:
335 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
336 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 +0530337
Nabin Haitb09ed412015-02-17 10:33:58 +0530338 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530339 for d in [
340 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530341 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530342 ["Cost Center", "cost_center", "cost_center"],
343 ["Warehouse", "warehouse", ""]]:
Nabin Hait33df0b42018-05-26 09:09:02 +0530344 if not out[d[1]]:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530345 out[d[1]] = frappe.get_cached_value('Company', args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530346
Giovanni2144e022017-12-10 17:27:09 +0100347 for fieldname in ("item_name", "item_group", "barcodes", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530348 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530349
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530350 if args.get("manufacturer"):
351 part_no = get_item_manufacturer_part_no(args.get("item_code"), args.get("manufacturer"))
352 if part_no:
353 out["manufacturer_part_no"] = part_no
354 else:
355 out["manufacturer_part_no"] = None
356 out["manufacturer"] = None
marination3e7a8ab2020-04-07 21:00:57 +0530357 else:
rohitwaghchaurebe16e5c2020-05-01 10:50:17 +0530358 data = frappe.get_value("Item", item.name,
359 ["default_item_manufacturer", "default_manufacturer_part_no"] , as_dict=1)
360
361 if data:
362 out.update({
363 "manufacturer": data.default_item_manufacturer,
364 "manufacturer_part_no": data.default_manufacturer_part_no
365 })
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530366
Nabin Hait34c551d2019-07-03 10:34:31 +0530367 child_doctype = args.doctype + ' Item'
368 meta = frappe.get_meta(child_doctype)
369 if meta.get_field("barcode"):
370 update_barcode_value(out)
371
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530372 if out.get("weight_per_unit"):
373 out['total_weight'] = out.weight_per_unit * out.stock_qty
374
Nabin Hait436f5262014-02-10 14:47:54 +0530375 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530376
Saqib438e0432020-04-03 10:02:56 +0530377def get_item_warehouse(item, args, overwrite_warehouse, defaults={}):
378 if not defaults:
379 defaults = frappe._dict({
380 'item_defaults' : get_item_defaults(item.name, args.company),
381 'item_group_defaults' : get_item_group_defaults(item.name, args.company),
382 'brand_defaults' : get_brand_defaults(item.name, args.company)
383 })
384
385 if overwrite_warehouse or not args.warehouse:
386 warehouse = (
387 args.get("set_warehouse") or
388 defaults.item_defaults.get("default_warehouse") or
389 defaults.item_group_defaults.get("default_warehouse") or
390 defaults.brand_defaults.get("default_warehouse") or
391 args.get('warehouse')
392 )
393
394 if not warehouse:
395 defaults = frappe.defaults.get_defaults() or {}
396 warehouse_exists = frappe.db.exists("Warehouse", {
397 'name': defaults.default_warehouse,
398 'company': args.company
399 })
400 if defaults.get("default_warehouse") and warehouse_exists:
401 warehouse = defaults.default_warehouse
402
403 else:
404 warehouse = args.get('warehouse')
marinatione05013e2020-04-06 22:13:13 +0530405
Marica3b1be2b2020-10-22 17:04:31 +0530406 if not warehouse:
407 default_warehouse = frappe.db.get_single_value("Stock Settings", "default_warehouse")
408 if frappe.db.get_value("Warehouse", default_warehouse, "company") == args.company:
409 return default_warehouse
410
Saqib438e0432020-04-03 10:02:56 +0530411 return warehouse
412
Nabin Hait34c551d2019-07-03 10:34:31 +0530413def update_barcode_value(out):
Nabin Hait34c551d2019-07-03 10:34:31 +0530414 barcode_data = get_barcode_data([out])
415
416 # If item has one barcode then update the value of the barcode field
417 if barcode_data and len(barcode_data.get(out.item_code)) == 1:
418 out['barcode'] = barcode_data.get(out.item_code)[0]
419
Saqiba6f98d42020-07-23 18:51:26 +0530420def get_barcode_data(items_list):
421 # get itemwise batch no data
422 # exmaple: {'LED-GRE': [Batch001, Batch002]}
423 # where LED-GRE is item code, SN0001 is serial no and Pune is warehouse
424
425 itemwise_barcode = {}
426 for item in items_list:
427 barcodes = frappe.db.sql("""
428 select barcode from `tabItem Barcode` where parent = %s
429 """, item.item_code, as_dict=1)
430
431 for barcode in barcodes:
432 if item.item_code not in itemwise_barcode:
433 itemwise_barcode.setdefault(item.item_code, [])
434 itemwise_barcode[item.item_code].append(barcode.get("barcode"))
435
436 return itemwise_barcode
437
Zlash6580f5cb02018-08-29 11:39:08 +0530438@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500439def get_item_tax_info(company, tax_category, item_codes):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500440 out = {}
441 if isinstance(item_codes, string_types):
442 item_codes = json.loads(item_codes)
443
444 for item_code in item_codes:
445 if not item_code or item_code in out:
446 continue
447 out[item_code] = {}
448 item = frappe.get_cached_doc("Item", item_code)
mohammadahmad1990ad3d44d2020-06-18 23:16:16 +0500449 get_item_tax_template({"company": company, "tax_category": tax_category}, item, out[item_code])
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500450 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 +0500451
452 return out
453
454def get_item_tax_template(args, item, out):
455 """
456 args = {
457 "tax_category": None
458 "item_tax_template": None
459 }
460 """
461 item_tax_template = args.get("item_tax_template")
462
463 if not item_tax_template:
464 item_tax_template = _get_item_tax_template(args, item.taxes, out)
465
466 if not item_tax_template:
467 item_group = item.item_group
468 while item_group and not item_tax_template:
469 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
470 item_tax_template = _get_item_tax_template(args, item_group_doc.taxes, out)
471 item_group = item_group_doc.parent_item_group
472
18alantom308905b2021-05-03 23:34:34 +0530473def _get_item_tax_template(args, taxes, out=None, for_validate=False):
474 if out is None:
475 out = {}
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530476 taxes_with_validity = []
477 taxes_with_no_validity = []
478
479 for tax in taxes:
mohammadahmad1990261ecba2020-06-25 01:56:53 +0500480 tax_company = frappe.get_value("Item Tax Template", tax.item_tax_template, 'company')
481 if tax.valid_from and tax_company == args['company']:
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530482 # In purchase Invoice first preference will be given to supplier invoice date
483 # if supplier date is not present then posting date
484 validation_date = args.get('transaction_date') or args.get('bill_date') or args.get('posting_date')
485
486 if getdate(tax.valid_from) <= getdate(validation_date):
487 taxes_with_validity.append(tax)
488 else:
mohammadahmad1990261ecba2020-06-25 01:56:53 +0500489 if tax_company == args['company']:
mohammadahmad1990e39649b2020-06-18 11:42:53 +0500490 taxes_with_no_validity.append(tax)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530491
492 if taxes_with_validity:
493 taxes = sorted(taxes_with_validity, key = lambda i: i.valid_from, reverse=True)
494 else:
495 taxes = taxes_with_no_validity
496
497 if for_validate:
498 return [tax.item_tax_template for tax in taxes if (cstr(tax.tax_category) == cstr(args.get('tax_category')) \
499 and (tax.item_tax_template not in taxes))]
500
501 # all templates have validity and no template is valid
502 if not taxes_with_validity and (not taxes_with_no_validity):
503 return None
504
Saif Ur Rehman67786682018-12-27 02:11:07 +0500505 for tax in taxes:
506 if cstr(tax.tax_category) == cstr(args.get("tax_category")):
507 out["item_tax_template"] = tax.item_tax_template
508 return tax.item_tax_template
509 return None
510
511@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500512def get_item_tax_map(company, item_tax_template, as_json=True):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500513 item_tax_map = {}
514 if item_tax_template:
515 template = frappe.get_cached_doc("Item Tax Template", item_tax_template)
516 for d in template.taxes:
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500517 if frappe.get_cached_value("Account", d.tax_type, "company") == company:
518 item_tax_map[d.tax_type] = d.tax_rate
Saif Ur Rehman67786682018-12-27 02:11:07 +0500519
520 return json.dumps(item_tax_map) if as_json else item_tax_map
521
522@frappe.whitelist()
Zlash6580f5cb02018-08-29 11:39:08 +0530523def calculate_service_end_date(args, item=None):
524 args = process_args(args)
525 if not item:
526 item = frappe.get_cached_doc("Item", args.item_code)
527
Zlash65627be1d2019-01-15 14:16:32 +0530528 doctype = args.get("parenttype") or args.get("doctype")
Zlash65a3dd7982019-01-15 14:36:11 +0530529 if doctype == "Sales Invoice":
530 enable_deferred = "enable_deferred_revenue"
531 no_of_months = "no_of_months"
532 account = "deferred_revenue_account"
533 else:
534 enable_deferred = "enable_deferred_expense"
535 no_of_months = "no_of_months_exp"
536 account = "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530537
Zlash6580f5cb02018-08-29 11:39:08 +0530538 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
Zarrare83ff382018-09-21 15:45:40 +0530539 service_end_date = add_months(service_start_date, item.get(no_of_months))
Zlash6580f5cb02018-08-29 11:39:08 +0530540 deferred_detail = {
Zlash6580f5cb02018-08-29 11:39:08 +0530541 "service_start_date": service_start_date,
542 "service_end_date": service_end_date
543 }
Zarrare83ff382018-09-21 15:45:40 +0530544 deferred_detail[enable_deferred] = item.get(enable_deferred)
545 deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)
Zlash6580f5cb02018-08-29 11:39:08 +0530546
547 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100548
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500549def get_default_income_account(args, item, item_group, brand):
Manas Solanki38667ab2018-05-16 16:55:23 +0530550 return (item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530551 or item_group.get("income_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500552 or brand.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530553 or args.income_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530554
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500555def get_default_expense_account(args, item, item_group, brand):
Manas Solanki38667ab2018-05-16 16:55:23 +0530556 return (item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530557 or item_group.get("expense_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500558 or brand.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530559 or args.expense_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530560
Zarrare83ff382018-09-21 15:45:40 +0530561def get_default_deferred_account(args, item, fieldname=None):
Zlash65627be1d2019-01-15 14:16:32 +0530562 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zarrare83ff382018-09-21 15:45:40 +0530563 return (item.get(fieldname)
564 or args.get(fieldname)
565 or frappe.get_cached_value('Company', args.company, "default_"+fieldname))
Manas Solanki03938482018-05-14 16:16:46 +0530566 else:
567 return None
568
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530569def get_default_cost_center(args, item=None, item_group=None, brand=None, company=None):
Nabin Hait50238c32018-08-08 18:43:04 +0530570 cost_center = None
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530571
572 if not company and args.get("company"):
573 company = args.get("company")
574
Nabin Hait50238c32018-08-08 18:43:04 +0530575 if args.get('project'):
576 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530577
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530578 if not cost_center and (item and item_group and brand):
Nabin Hait50238c32018-08-08 18:43:04 +0530579 if args.get('customer'):
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500580 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 +0530581 else:
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500582 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 +0530583
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530584 elif not cost_center and args.get("item_code") and company:
585 for method in ["get_item_defaults", "get_item_group_defaults", "get_brand_defaults"]:
586 path = "erpnext.stock.get_item_details.{0}".format(method)
587 data = frappe.get_attr(path)(args.get("item_code"), company)
588
589 if data and (data.selling_cost_center or data.buying_cost_center):
590 return data.selling_cost_center or data.buying_cost_center
591
592 if not cost_center and args.get("cost_center"):
593 cost_center = args.get("cost_center")
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530594
595 if (company and cost_center
596 and frappe.get_cached_value("Cost Center", cost_center, "company") != company):
597 return None
598
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530599 if not cost_center and company:
600 cost_center = frappe.get_cached_value("Company",
601 company, "cost_center")
602
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530603 return cost_center
Rushabh Mehta1a763742014-10-03 16:36:43 +0530604
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500605def get_default_supplier(args, item, item_group, brand):
Shreya Shah3c9839f2018-07-17 18:01:44 +0530606 return (item.get("default_supplier")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500607 or item_group.get("default_supplier")
608 or brand.get("default_supplier"))
Shreya Shah3c9839f2018-07-17 18:01:44 +0530609
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530610def get_price_list_rate(args, item_doc, out):
Anand Doshi39a28912016-02-15 11:42:18 +0530611 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530612
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530613 if meta.get_field("currency") or args.get('currency'):
Maricae8bc9122021-04-19 11:05:21 +0530614 if not args.get("price_list_currency") or not args.get("plc_conversion_rate"):
615 # if currency and plc_conversion_rate exist then
616 # `get_price_list_currency_and_exchange_rate` has already been called
617 pl_details = get_price_list_currency_and_exchange_rate(args)
618 args.update(pl_details)
619
Nabin Hait06c8cf42019-05-16 19:17:02 +0530620 if meta.get_field("currency"):
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530621 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530622
Nabin Haite45ec662018-08-01 17:44:34 +0530623 price_list_rate = get_price_list_rate_for(args, item_doc.name) or 0
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530624
hiousi1516e292019-01-08 18:34:08 +0100625 # variant
626 if not price_list_rate and item_doc.variant_of:
627 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530628
629 # insert in database
Rushabh Mehta1a763742014-10-03 16:36:43 +0530630 if not price_list_rate:
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530631 if args.price_list and args.rate:
632 insert_item_price(args)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530633 return {}
Anand Doshibd67e872014-04-11 16:51:27 +0530634
Nabin Hait436f5262014-02-10 14:47:54 +0530635 out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) \
636 / flt(args.conversion_rate)
mbauskar287fe812017-04-10 19:15:57 +0530637
Nabin Hait34d28222016-01-19 15:45:49 +0530638 if not out.price_list_rate and args.transaction_type=="buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530639 from erpnext.stock.doctype.item.item import get_last_purchase_details
Anand Doshibd67e872014-04-11 16:51:27 +0530640 out.update(get_last_purchase_details(item_doc.name,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530641 args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530642
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530643def insert_item_price(args):
644 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530645 if frappe.db.get_value("Price List", args.price_list, "currency", cache=True) == args.currency \
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530646 and cint(frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")):
647 if frappe.has_permission("Item Price", "write"):
Nabin Haite45ec662018-08-01 17:44:34 +0530648 price_list_rate = (args.rate / args.get('conversion_factor')
649 if args.get("conversion_factor") else args.rate)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530650
Nabin Haitb479a872018-09-07 13:17:11 +0530651 item_price = frappe.db.get_value('Item Price',
652 {'item_code': args.item_code, 'price_list': args.price_list, 'currency': args.currency},
653 ['name', 'price_list_rate'], as_dict=1)
654 if item_price and item_price.name:
655 if item_price.price_list_rate != price_list_rate:
656 frappe.db.set_value('Item Price', item_price.name, "price_list_rate", price_list_rate)
657 frappe.msgprint(_("Item Price updated for {0} in Price List {1}").format(args.item_code,
658 args.price_list), alert=True)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530659 else:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530660 item_price = frappe.get_doc({
661 "doctype": "Item Price",
662 "price_list": args.price_list,
663 "item_code": args.item_code,
664 "currency": args.currency,
665 "price_list_rate": price_list_rate
666 })
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530667 item_price.insert()
668 frappe.msgprint(_("Item Price added for {0} in Price List {1}").format(args.item_code,
Rushabh Mehta49f97472018-08-30 18:50:48 +0530669 args.price_list), alert=True)
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530670
Nabin Hait01ca3e52019-01-25 16:25:15 +0530671def get_item_price(args, item_code, ignore_party=False):
Nabin Haite45ec662018-08-01 17:44:34 +0530672 """
673 Get name, price_list_rate from Item Price based on conditions
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530674 Check if the desired qty is within the increment of the packing list.
Nabin Haite45ec662018-08-01 17:44:34 +0530675 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
Nabin Hait03b116d2020-01-20 15:45:04 +0530676 optional fields transaction_date, customer, supplier
Nabin Haite45ec662018-08-01 17:44:34 +0530677 :param item_code: str, Item Doctype field item_code
678 """
679
680 args['item_code'] = item_code
Nabin Haite45ec662018-08-01 17:44:34 +0530681
Nabin Hait01ca3e52019-01-25 16:25:15 +0530682 conditions = """where item_code=%(item_code)s
Nabin Haite45ec662018-08-01 17:44:34 +0530683 and price_list=%(price_list)s
684 and ifnull(uom, '') in ('', %(uom)s)"""
685
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530686 conditions += "and ifnull(batch_no, '') in ('', %(batch_no)s)"
687
Nabin Hait01ca3e52019-01-25 16:25:15 +0530688 if not ignore_party:
Nabin Hait01ca3e52019-01-25 16:25:15 +0530689 if args.get("customer"):
690 conditions += " and customer=%(customer)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530691 elif args.get("supplier"):
Nabin Hait01ca3e52019-01-25 16:25:15 +0530692 conditions += " and supplier=%(supplier)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530693 else:
Saqib41b47a62020-05-15 04:24:36 +0530694 conditions += "and (customer is null or customer = '') and (supplier is null or supplier = '')"
Nabin Hait01ca3e52019-01-25 16:25:15 +0530695
Nabin Haite45ec662018-08-01 17:44:34 +0530696 if args.get('transaction_date'):
697 conditions += """ and %(transaction_date)s between
698 ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
Deepesh Gargf15ff5f2020-07-11 13:58:53 +0530699
Andy Zhub60abb02020-07-03 14:13:15 +1200700 if args.get('posting_date'):
701 conditions += """ and %(posting_date)s between
702 ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
Nabin Haite45ec662018-08-01 17:44:34 +0530703
704 return frappe.db.sql(""" select name, price_list_rate, uom
705 from `tabItem Price` {conditions}
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530706 order by valid_from desc, batch_no desc, uom desc """.format(conditions=conditions), args)
Nabin Haite45ec662018-08-01 17:44:34 +0530707
708def get_price_list_rate_for(args, item_code):
709 """
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530710 :param customer: link to Customer DocType
711 :param supplier: link to Supplier DocType
Nabin Haite45ec662018-08-01 17:44:34 +0530712 :param price_list: str (Standard Buying or Standard Selling)
713 :param item_code: str, Item Doctype field item_code
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530714 :param qty: Desired Qty
Nabin Haite45ec662018-08-01 17:44:34 +0530715 :param transaction_date: Date of the price
716 """
717 item_price_args = {
718 "item_code": item_code,
719 "price_list": args.get('price_list'),
720 "customer": args.get('customer'),
721 "supplier": args.get('supplier'),
722 "uom": args.get('uom'),
Nabin Haite45ec662018-08-01 17:44:34 +0530723 "transaction_date": args.get('transaction_date'),
Andy Zhub60abb02020-07-03 14:13:15 +1200724 "posting_date": args.get('posting_date'),
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530725 "batch_no": args.get('batch_no')
Nabin Haite45ec662018-08-01 17:44:34 +0530726 }
727
728 item_price_data = 0
729 price_list_rate = get_item_price(item_price_args, item_code)
730 if price_list_rate:
731 desired_qty = args.get("qty")
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530732 if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
Nabin Haite45ec662018-08-01 17:44:34 +0530733 item_price_data = price_list_rate
734 else:
Don-Leopardoccdf1932020-01-09 03:54:43 -0300735 for field in ["customer", "supplier"]:
Nabin Haite45ec662018-08-01 17:44:34 +0530736 del item_price_args[field]
737
Nabin Haite321fbb2020-01-16 13:37:25 +0530738 general_price_list_rate = get_item_price(item_price_args, item_code,
739 ignore_party=args.get("ignore_party"))
Don-Leopardoccdf1932020-01-09 03:54:43 -0300740
Nabin Haite45ec662018-08-01 17:44:34 +0530741 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530742 item_price_args["uom"] = args.get("stock_uom")
Nabin Hait01ca3e52019-01-25 16:25:15 +0530743 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 +0530744
745 if general_price_list_rate:
746 item_price_data = general_price_list_rate
747
748 if item_price_data:
749 if item_price_data[0][2] == args.get("uom"):
750 return item_price_data[0][1]
751 elif not args.get('price_list_uom_dependant'):
752 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
753 else:
754 return item_price_data[0][1]
755
756def check_packing_list(price_list_rate_name, desired_qty, item_code):
757 """
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530758 Check if the desired qty is within the increment of the packing list.
Nabin Haite45ec662018-08-01 17:44:34 +0530759 :param price_list_rate_name: Name of Item Price
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530760 :param desired_qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530761 :param item_code: str, Item Doctype field item_code
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530762 :param qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530763 """
764
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530765 flag = True
Nabin Haite45ec662018-08-01 17:44:34 +0530766 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530767 if item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +0530768 packing_increment = desired_qty % item_price.packing_unit
769
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530770 if packing_increment != 0:
771 flag = False
772
773 return flag
Rushabh Mehta1a763742014-10-03 16:36:43 +0530774
Nabin Hait436f5262014-02-10 14:47:54 +0530775def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +0530776 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +0530777
Anand Doshife13bfe2015-08-25 12:49:40 +0530778 if (not args.conversion_rate
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530779 and args.currency==frappe.get_cached_value('Company', args.company, "default_currency")):
Anand Doshife13bfe2015-08-25 12:49:40 +0530780 args.conversion_rate = 1.0
781
Nabin Hait436f5262014-02-10 14:47:54 +0530782 # validate currency conversion rate
Anand Doshibd67e872014-04-11 16:51:27 +0530783 validate_conversion_rate(args.currency, args.conversion_rate,
Nabin Hait436f5262014-02-10 14:47:54 +0530784 meta.get_label("conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530785
786 args.conversion_rate = flt(args.conversion_rate,
787 get_field_precision(meta.get_field("conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530788 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530789
Nabin Hait06c8cf42019-05-16 19:17:02 +0530790 if args.price_list:
791 if (not args.plc_conversion_rate
792 and args.price_list_currency==frappe.db.get_value("Price List", args.price_list, "currency", cache=True)):
793 args.plc_conversion_rate = 1.0
Manas Solanki3504a232018-06-06 12:46:06 +0530794
Nabin Hait06c8cf42019-05-16 19:17:02 +0530795 # validate price list currency conversion rate
796 if not args.get("price_list_currency"):
797 throw(_("Price List Currency not selected"))
798 else:
799 validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate,
800 meta.get_label("plc_conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530801
Nabin Hait06c8cf42019-05-16 19:17:02 +0530802 if meta.get_field("plc_conversion_rate"):
803 args.plc_conversion_rate = flt(args.plc_conversion_rate,
804 get_field_precision(meta.get_field("plc_conversion_rate"),
805 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530806
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530807def get_party_item_code(args, item_doc, out):
Nabin Hait34d28222016-01-19 15:45:49 +0530808 if args.transaction_type=="selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +0530809 out.customer_item_code = None
Nabin Hait34c551d2019-07-03 10:34:31 +0530810
811 if args.quotation_to and args.quotation_to != 'Customer':
812 return
813
Nabin Hait79f091e2014-12-26 11:41:15 +0530814 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +0530815
816 if customer_item_code:
817 out.customer_item_code = customer_item_code[0].ref_code
818 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +0530819 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +0530820 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
821 if customer_group_item_code and not customer_group_item_code[0].customer_name:
822 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +0530823
Nabin Hait34d28222016-01-19 15:45:49 +0530824 if args.transaction_type=="buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +0530825 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +0530826 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +0530827
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530828def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530829 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +0530830
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530831 if not frappe.flags.pos_profile and not pos_profile:
832 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get('pos_profile'))
Anand Doshibd67e872014-04-11 16:51:27 +0530833
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530834 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +0530835 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530836 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530837 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530838
Nabin Hait436f5262014-02-10 14:47:54 +0530839 if res.get("warehouse"):
Saurabhd3135532016-02-25 18:59:20 +0530840 res.actual_qty = get_bin_details(args.item_code,
Nabin Hait436f5262014-02-10 14:47:54 +0530841 res.warehouse).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +0530842
Nabin Hait436f5262014-02-10 14:47:54 +0530843 return res
844
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530845@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530846def get_pos_profile(company, pos_profile=None, user=None):
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530847 if pos_profile: return frappe.get_cached_doc('POS Profile', pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530848
849 if not user:
850 user = frappe.session['user']
851
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530852 condition = "pfu.user = %(user)s AND pfu.default=1"
853 if user and company:
854 condition = "pfu.user = %(user)s AND pf.company = %(company)s AND pfu.default=1"
855
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530856 pos_profile = frappe.db.sql("""SELECT pf.*
857 FROM
858 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
859 ON
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530860 pf.name = pfu.parent
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530861 WHERE
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530862 {cond} AND pf.disabled = 0
863 """.format(cond = condition), {
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530864 'user': user,
865 'company': company
866 }, as_dict=1)
Anand Doshibd67e872014-04-11 16:51:27 +0530867
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530868 if not pos_profile and company:
869 pos_profile = frappe.db.sql("""SELECT pf.*
870 FROM
871 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
872 ON
873 pf.name = pfu.parent
874 WHERE
875 pf.company = %(company)s AND pf.disabled = 0
876 """, {
877 'company': company
878 }, as_dict=1)
879
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530880 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +0530881
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530882def get_serial_nos_by_fifo(args, sales_order=None):
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530883 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
884 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530885 where item_code=%(item_code)s and warehouse=%(warehouse)s and
886 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
887 order by timestamp(purchase_date, purchase_time)
888 asc limit %(qty)s""",
889 {
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530890 "item_code": args.item_code,
891 "warehouse": args.warehouse,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530892 "qty": abs(cint(args.stock_qty)),
893 "sales_order": sales_order
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530894 }))
Nabin Hait08222152014-02-28 11:30:47 +0530895
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530896def get_serial_no_batchwise(args, sales_order=None):
Shreyaa20157a2018-04-13 12:03:42 +0530897 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
898 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530899 where item_code=%(item_code)s and warehouse=%(warehouse)s and
900 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
901 and batch_no=IF(%(batch_no)s IS NULL, batch_no, %(batch_no)s) order
902 by timestamp(purchase_date, purchase_time) asc limit %(qty)s""", {
Shreyaa20157a2018-04-13 12:03:42 +0530903 "item_code": args.item_code,
904 "warehouse": args.warehouse,
905 "batch_no": args.batch_no,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530906 "qty": abs(cint(args.stock_qty)),
907 "sales_order": sales_order
Shreyaa20157a2018-04-13 12:03:42 +0530908 }))
909
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530910@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530911def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530912 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530913 filters = {"parent": item_code, "uom": uom}
914 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +0530915 filters["parent"] = ("in", (item_code, variant_of))
Sagar Vora508189e2018-09-11 17:22:25 +0530916 conversion_factor = frappe.db.get_value("UOM Conversion Detail",
917 filters, "conversion_factor")
918 if not conversion_factor:
919 stock_uom = frappe.db.get_value("Item", item_code, "stock_uom")
920 conversion_factor = get_uom_conv_factor(uom, stock_uom)
rohitwaghchaureffdadbf2019-01-08 16:21:25 +0530921 return {"conversion_factor": conversion_factor or 1.0}
Nabin Hait08222152014-02-28 11:30:47 +0530922
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530923@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530924def get_projected_qty(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530925 return {"projected_qty": frappe.db.get_value("Bin",
Nabin Hait436f5262014-02-10 14:47:54 +0530926 {"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
Nabin Hait08222152014-02-28 11:30:47 +0530927
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530928@frappe.whitelist()
Anupam4980dd62021-03-15 11:37:46 +0530929def get_bin_details(item_code, warehouse, company=None):
930 bin_details = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Nabin Haita804d6d2018-08-29 13:34:58 +0530931 ["projected_qty", "actual_qty", "reserved_qty"], as_dict=True, cache=True) \
Shreya Shahbe770332018-08-22 14:45:22 +0530932 or {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
Anupam4980dd62021-03-15 11:37:46 +0530933 if company:
934 bin_details['company_total_stock'] = get_company_total_stock(item_code, company)
935 return bin_details
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530936
Anupam4980dd62021-03-15 11:37:46 +0530937def get_company_total_stock(item_code, company):
938 return frappe.db.sql("""SELECT sum(actual_qty) from
939 (`tabBin` INNER JOIN `tabWarehouse` ON `tabBin`.warehouse = `tabWarehouse`.name)
18alantome36f3032021-05-03 19:49:22 +0530940 WHERE `tabWarehouse`.company = %s and `tabBin`.item_code = %s""",
941 (company, item_code))[0][0]
Anupam4980dd62021-03-15 11:37:46 +0530942
943@frappe.whitelist()
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530944def get_serial_no_details(item_code, warehouse, stock_qty, serial_no):
945 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "serial_no":serial_no})
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530946 serial_no = get_serial_no(args)
947 return {'serial_no': serial_no}
Rushabh Mehta985cb822016-12-30 15:06:54 +0530948
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530949@frappe.whitelist()
Rohit Waghchaure6daab3c2019-09-19 17:01:26 +0530950def 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 +0530951 bin_details_and_serial_nos = {}
952 bin_details_and_serial_nos.update(get_bin_details(item_code, warehouse))
Rushabh Mehta49f97472018-08-30 18:50:48 +0530953 if flt(stock_qty) > 0:
Shreyaa20157a2018-04-13 12:03:42 +0530954 if has_batch_no:
955 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty})
956 serial_no = get_serial_no(args)
957 bin_details_and_serial_nos.update({'serial_no': serial_no})
958 return bin_details_and_serial_nos
959
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530960 bin_details_and_serial_nos.update(get_serial_no_details(item_code, warehouse, stock_qty, serial_no))
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530961 return bin_details_and_serial_nos
Anand Doshidffec8f2014-07-01 17:45:15 +0530962
963@frappe.whitelist()
Shreyaa20157a2018-04-13 12:03:42 +0530964def get_batch_qty_and_serial_no(batch_no, stock_qty, warehouse, item_code, has_serial_no):
965 batch_qty_and_serial_no = {}
966 batch_qty_and_serial_no.update(get_batch_qty(batch_no, warehouse, item_code))
967
968 if (flt(batch_qty_and_serial_no.get('actual_batch_qty')) >= flt(stock_qty)) and has_serial_no:
969 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "batch_no":batch_no})
970 serial_no = get_serial_no(args)
971 batch_qty_and_serial_no.update({'serial_no': serial_no})
972 return batch_qty_and_serial_no
973
974@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530975def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +0700976 from erpnext.stock.doctype.batch import batch
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +0530977 if batch_no:
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530978 return {'actual_batch_qty': batch.get_batch_qty(batch_no, warehouse)}
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530979
Anand Doshidffec8f2014-07-01 17:45:15 +0530980@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530981def apply_price_list(args, as_doc=False):
982 """Apply pricelist on a document-like dict object and return as
983 {'parent': dict, 'children': list}
984
985 :param args: See below
986 :param as_doc: Updates value in the passed dict
987
Anand Doshidffec8f2014-07-01 17:45:15 +0530988 args = {
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530989 "doctype": "",
990 "name": "",
991 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
Anand Doshidffec8f2014-07-01 17:45:15 +0530992 "conversion_rate": 1.0,
993 "selling_price_list": None,
994 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530995 "price_list_uom_dependant": None,
Anand Doshidffec8f2014-07-01 17:45:15 +0530996 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530997 "doctype": "",
998 "name": "",
Anand Doshidffec8f2014-07-01 17:45:15 +0530999 "supplier": None,
1000 "transaction_date": None,
1001 "conversion_rate": 1.0,
1002 "buying_price_list": None,
Anand Doshidffec8f2014-07-01 17:45:15 +05301003 "ignore_pricing_rule": 0/1
1004 }
1005 """
1006 args = process_args(args)
1007
1008 parent = get_price_list_currency_and_exchange_rate(args)
Maricae8bc9122021-04-19 11:05:21 +05301009 args.update(parent)
1010
Anand Doshidffec8f2014-07-01 17:45:15 +05301011 children = []
1012
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301013 if "items" in args:
1014 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +05301015 args.update(parent)
1016
1017 for item in item_list:
1018 args_copy = frappe._dict(args.copy())
1019 args_copy.update(item)
1020 item_details = apply_price_list_on_item(args_copy)
1021 children.append(item_details)
1022
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301023 if as_doc:
Shreya Shahb13a54a2017-12-06 19:17:04 +05301024 args.price_list_currency = parent.price_list_currency,
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301025 args.plc_conversion_rate = parent.plc_conversion_rate
1026 if args.get('items'):
1027 for i, item in enumerate(args.get('items')):
1028 for fieldname in children[i]:
1029 # if the field exists in the original doc
1030 # update the value
1031 if fieldname in item and fieldname not in ("name", "doctype"):
1032 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301033 return args
1034 else:
1035 return {
1036 "parent": parent,
1037 "children": children
1038 }
Anand Doshidffec8f2014-07-01 17:45:15 +05301039
1040def apply_price_list_on_item(args):
1041 item_details = frappe._dict()
1042 item_doc = frappe.get_doc("Item", args.item_code)
1043 get_price_list_rate(args, item_doc, item_details)
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301044
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +05301045 item_details.update(get_pricing_rule_for_item(args, item_details.price_list_rate))
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301046
Anand Doshidffec8f2014-07-01 17:45:15 +05301047 return item_details
1048
Anand Doshidffec8f2014-07-01 17:45:15 +05301049def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +05301050 if not args.price_list:
1051 return {}
1052
Shreya3f778522018-05-15 16:59:20 +05301053 if args.doctype in ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']:
1054 args.update({"exchange_rate": "for_selling"})
1055 elif args.doctype in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']:
1056 args.update({"exchange_rate": "for_buying"})
1057
rohitwaghchaurea85ddf22019-11-19 18:47:48 +05301058 price_list_details = get_price_list_details(args.price_list)
1059
1060 price_list_currency = price_list_details.get("currency")
1061 price_list_uom_dependant = price_list_details.get("price_list_uom_dependant")
1062
Anand Doshidffec8f2014-07-01 17:45:15 +05301063 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +01001064 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +05301065
Nabin Haitdd82bf22015-05-11 16:49:17 +05301066 if (not plc_conversion_rate) or (price_list_currency and args.price_list_currency \
1067 and price_list_currency != args.price_list_currency):
Rushabh Mehta6b537922017-03-14 16:59:11 +05301068 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
tundebabzy6e90f492018-02-12 10:48:57 +01001069 plc_conversion_rate = get_exchange_rate(price_list_currency, company_currency,
Shreya3f778522018-05-15 16:59:20 +05301070 args.transaction_date, args.exchange_rate) or plc_conversion_rate
Anand Doshidffec8f2014-07-01 17:45:15 +05301071
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301072 return frappe._dict({
Anand Doshidffec8f2014-07-01 17:45:15 +05301073 "price_list_currency": price_list_currency,
Shreya Shahb13a54a2017-12-06 19:17:04 +05301074 "price_list_uom_dependant": price_list_uom_dependant,
Maricae8bc9122021-04-19 11:05:21 +05301075 "plc_conversion_rate": plc_conversion_rate or 1
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301076 })
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +05301077
1078@frappe.whitelist()
1079def get_default_bom(item_code=None):
1080 if item_code:
1081 bom = frappe.db.get_value("BOM", {"docstatus": 1, "is_default": 1, "is_active": 1, "item": item_code})
1082 if bom:
1083 return bom
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301084
Deepesh Garg15ff6a52020-02-18 12:28:41 +05301085@frappe.whitelist()
Manas Solanki087a2252018-05-04 16:02:38 +05301086def get_valuation_rate(item_code, company, warehouse=None):
Manas Solankib16a4ec2018-05-04 16:49:33 +05301087 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +05301088 item_group = get_item_group_defaults(item_code, company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001089 brand = get_brand_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +05301090 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +05301091 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +05301092 if not warehouse:
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001093 warehouse = item.get("default_warehouse") or item_group.get("default_warehouse") or brand.get("default_warehouse")
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301094
1095 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Saurabhbd01a812016-03-07 14:32:23 +05301096 ["valuation_rate"], as_dict=True) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301097
Manas Solankie3910fb2018-05-16 15:50:17 +05301098 elif not item.get("is_stock_item"):
Nabin Haitfe876c02017-03-06 16:32:57 +05301099 valuation_rate =frappe.db.sql("""select sum(base_net_amount) / sum(qty*conversion_factor)
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301100 from `tabPurchase Invoice Item`
Saurabhbd01a812016-03-07 14:32:23 +05301101 where item_code = %s and docstatus=1""", item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301102
Saurabhbd01a812016-03-07 14:32:23 +05301103 if valuation_rate:
1104 return {"valuation_rate": valuation_rate[0][0] or 0.0}
1105 else:
1106 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301107
Saurabh2d7af632016-02-26 11:09:20 +05301108def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +05301109 if out.valuation_rate:
1110 out.update({
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301111 "gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)
Saurabh5ada14b2016-02-26 18:02:55 +05301112 })
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301113
Saurabhd3135532016-02-25 18:59:20 +05301114 return out
mbauskar6f603392016-01-21 16:10:22 +05301115
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301116@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301117def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +05301118 serial_no = None
Achilles Rasquinha56b2e122018-02-13 14:42:40 +05301119 if isinstance(args, string_types):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301120 args = json.loads(args)
1121 args = frappe._dict(args)
Rohit Waghchauredc981dc2017-04-03 14:17:08 +05301122 if args.get('doctype') == 'Sales Invoice' and not args.get('update_stock'):
1123 return ""
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301124 if args.get('warehouse') and args.get('stock_qty') and args.get('item_code'):
Shreyaa20157a2018-04-13 12:03:42 +05301125 has_serial_no = frappe.get_value('Item', {'item_code': args.item_code}, "has_serial_no")
Shreyaa20157a2018-04-13 12:03:42 +05301126 if args.get('batch_no') and has_serial_no == 1:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301127 return get_serial_no_batchwise(args, sales_order)
Shreyaa20157a2018-04-13 12:03:42 +05301128 elif has_serial_no == 1:
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301129 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 +05301130 args = process_args(args)
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301131 serial_no = get_serial_nos_by_fifo(args, sales_order)
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +05301132
1133 if not serial_no and serial_nos:
1134 # For POS
1135 serial_no = serial_nos
1136
1137 return serial_no
Manas Solankie5e87f72018-05-28 20:07:08 +05301138
1139
1140def update_party_blanket_order(args, out):
ronelvcabrera370cdc02019-12-04 18:37:11 +08001141 if out["against_blanket_order"]:
1142 blanket_order_details = get_blanket_order_details(args)
1143 if blanket_order_details:
1144 out.update(blanket_order_details)
Manas Solankie5e87f72018-05-28 20:07:08 +05301145
1146@frappe.whitelist()
1147def get_blanket_order_details(args):
1148 if isinstance(args, string_types):
1149 args = frappe._dict(json.loads(args))
1150
1151 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +05301152 condition = ''
Manas Solankie5e87f72018-05-28 20:07:08 +05301153 if args.item_code:
1154 if args.customer and args.doctype == "Sales Order":
Nabin Hait2737b082018-06-14 18:07:22 +05301155 condition = ' and bo.customer=%(customer)s'
Manas Solankie5e87f72018-05-28 20:07:08 +05301156 elif args.supplier and args.doctype == "Purchase Order":
Nabin Hait2737b082018-06-14 18:07:22 +05301157 condition = ' and bo.supplier=%(supplier)s'
Manas Solankie5e87f72018-05-28 20:07:08 +05301158 if args.blanket_order:
Nabin Hait2737b082018-06-14 18:07:22 +05301159 condition += ' and bo.name =%(blanket_order)s'
1160 if args.transaction_date:
1161 condition += ' and bo.to_date>=%(transaction_date)s'
1162
Manas Solankie5e87f72018-05-28 20:07:08 +05301163 blanket_order_details = frappe.db.sql('''
1164 select boi.rate as blanket_order_rate, bo.name as blanket_order
1165 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
Nabin Hait2737b082018-06-14 18:07:22 +05301166 where bo.company=%(company)s and boi.item_code=%(item_code)s
1167 and bo.docstatus=1 and bo.name = boi.parent {0}
1168 '''.format(condition), args, as_dict=True)
1169
Manas Solankie5e87f72018-05-28 20:07:08 +05301170 blanket_order_details = blanket_order_details[0] if blanket_order_details else ''
1171 return blanket_order_details
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301172
1173def get_so_reservation_for_item(args):
1174 reserved_so = None
1175 if args.get('against_sales_order'):
1176 if get_reserved_qty_for_so(args.get('against_sales_order'), args.get('item_code')):
1177 reserved_so = args.get('against_sales_order')
1178 elif args.get('against_sales_invoice'):
1179 sales_order = frappe.db.sql("""select sales_order from `tabSales Invoice Item` where
1180 parent=%s and item_code=%s""", (args.get('against_sales_invoice'), args.get('item_code')))
1181 if sales_order and sales_order[0]:
1182 if get_reserved_qty_for_so(sales_order[0][0], args.get('item_code')):
1183 reserved_so = sales_order[0]
1184 elif args.get("sales_order"):
1185 if get_reserved_qty_for_so(args.get('sales_order'), args.get('item_code')):
1186 reserved_so = args.get('sales_order')
1187 return reserved_so
1188
1189def get_reserved_qty_for_so(sales_order, item_code):
1190 reserved_qty = frappe.db.sql("""select sum(qty) from `tabSales Order Item`
1191 where parent=%s and item_code=%s and ensure_delivery_based_on_produced_serial_no=1
1192 """, (sales_order, item_code))
1193 if reserved_qty and reserved_qty[0][0]:
1194 return reserved_qty[0][0]
1195 else:
1196 return 0