blob: c72073c6143b44e31587e468c17256d5d8a5aa0a [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
Ankush16d4de52021-08-09 10:41:24 +053077 out.update(get_price_list_rate(args, item))
Nabin Hait436f5262014-02-10 14:47:54 +053078
Rushabh Mehtab46069d2016-01-15 16:59:26 +053079 if args.customer and cint(args.is_pos):
Anuja Pawarf132ed42021-05-07 12:11:09 +053080 out.update(get_pos_profile_item_details(args.company, args, update_data=True))
Rushabh Mehta6b537922017-03-14 16:59:11 +053081
Nabin Haitda17f9c2020-05-01 18:16:25 +053082 if (args.get("doctype") == "Material Request" and
83 args.get("material_request_type") == "Material Transfer"):
84 out.update(get_bin_details(args.item_code, args.get("from_warehouse")))
85
86 elif out.get("warehouse"):
Nabin Haitda0ba152021-04-30 18:38:41 +053087 out.update(get_bin_details(args.item_code, out.warehouse, args.company))
Anand Doshibd67e872014-04-11 16:51:27 +053088
Nabin Haita3dd72a2014-05-28 12:49:20 +053089 # update args with out, if key or value not exists
Achilles Rasquinha714c7462018-02-15 11:28:55 +053090 for key, value in iteritems(out):
Nabin Haita3dd72a2014-05-28 12:49:20 +053091 if args.get(key) is None:
92 args[key] = value
93
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053094 data = get_pricing_rule_for_item(args, out.price_list_rate,
95 doc, for_validate=for_validate)
96
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +053097 out.update(data)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053098
99 update_stock(args, out)
100
101 if args.transaction_date and item.lead_time_days:
102 out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
103 item.lead_time_days)
104
105 if args.get("is_subcontracted") == "Yes":
106 out.bom = args.get('bom') or get_default_bom(args.item_code)
107
108 get_gross_profit(out)
109 if args.doctype == 'Material Request':
110 out.rate = args.rate or out.price_list_rate
Rohit Waghchaure1bc53a32021-03-31 15:28:26 +0530111 out.amount = flt(args.qty) * flt(out.rate)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530112
113 return out
114
115def update_stock(args, out):
pratu16x7577e4c42017-06-23 11:39:03 +0530116 if (args.get("doctype") == "Delivery Note" or
Nabin Hait3ce41d62017-05-03 18:22:24 +0530117 (args.get("doctype") == "Sales Invoice" and args.get('update_stock'))) \
118 and out.warehouse and out.stock_qty > 0:
pratu16x7577e4c42017-06-23 11:39:03 +0530119
Nabin Hait8fac2ad2017-05-18 11:54:24 +0530120 if out.has_batch_no and not args.get("batch_no"):
Rushabh Mehta551406a2017-04-21 12:40:19 +0530121 out.batch_no = get_batch_no(out.item_code, out.warehouse, out.qty)
rohitwaghchaure2fb8cc52017-11-29 13:50:04 +0530122 actual_batch_qty = get_batch_qty(out.batch_no, out.warehouse, out.item_code)
123 if actual_batch_qty:
124 out.update(actual_batch_qty)
Shreya14bd43d2018-04-27 16:24:05 +0530125
126 if out.has_serial_no and args.get('batch_no'):
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530127 reserved_so = get_so_reservation_for_item(args)
Shreya14bd43d2018-04-27 16:24:05 +0530128 out.batch_no = args.get('batch_no')
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530129 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Shreya14bd43d2018-04-27 16:24:05 +0530130
131 elif out.has_serial_no:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530132 reserved_so = get_so_reservation_for_item(args)
133 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Rushabh Mehta551406a2017-04-21 12:40:19 +0530134
Anand Doshibd67e872014-04-11 16:51:27 +0530135
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530136def set_valuation_rate(out, args):
Nabin Hait50238c32018-08-08 18:43:04 +0530137 if frappe.db.exists("Product Bundle", args.item_code, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530138 valuation_rate = 0.0
139 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530140
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530141 for bundle_item in bundled_items.items:
142 valuation_rate += \
143 flt(get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get("valuation_rate") \
144 * bundle_item.qty)
Anand Doshi70f57eb2015-11-27 14:37:40 +0530145
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530146 out.update({
147 "valuation_rate": valuation_rate
148 })
149
150 else:
151 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
152
Nabin Hait436f5262014-02-10 14:47:54 +0530153
Anand Doshidffec8f2014-07-01 17:45:15 +0530154def process_args(args):
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530155 if isinstance(args, string_types):
Anand Doshidffec8f2014-07-01 17:45:15 +0530156 args = json.loads(args)
157
158 args = frappe._dict(args)
159
Anand Doshidffec8f2014-07-01 17:45:15 +0530160 if not args.get("price_list"):
161 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
162
163 if args.barcode:
164 args.item_code = get_item_code(barcode=args.barcode)
165 elif not args.item_code and args.serial_no:
166 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530167
mbauskar6f603392016-01-21 16:10:22 +0530168 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530169 return args
170
marination392f3232020-07-14 17:03:17 +0530171def process_string_args(args):
172 if isinstance(args, string_types):
173 args = json.loads(args)
174 return args
tundebabzyacccdb32017-11-23 08:35:15 +0100175
Neil Trini Lasrado4abda672015-02-25 17:34:27 +0530176@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530177def get_item_code(barcode=None, serial_no=None):
178 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100179 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530180 if not item_code:
181 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530182 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530183 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530184 if not item_code:
185 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530186
Nabin Hait436f5262014-02-10 14:47:54 +0530187 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530188
tundebabzyacccdb32017-11-23 08:35:15 +0100189
Nabin Hait436f5262014-02-10 14:47:54 +0530190def validate_item_details(args, item):
191 if not args.company:
192 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530193
Nabin Hait436f5262014-02-10 14:47:54 +0530194 from erpnext.stock.doctype.item.item import validate_end_of_life
Anand Doshi21e09a22015-10-29 12:21:41 +0530195 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530196
tundebabzyacccdb32017-11-23 08:35:15 +0100197 if args.transaction_type == "selling" and cint(item.has_variants):
Umair Sayyed72534de2016-04-15 12:52:12 +0530198 throw(_("Item {0} is a template, please select one of its variants").format(item.name))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530199
tundebabzyacccdb32017-11-23 08:35:15 +0100200 elif args.transaction_type == "buying" and args.doctype != "Material Request":
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530201 if args.get("is_subcontracted") == "Yes" and item.is_sub_contracted_item != 1:
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530202 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530203
tundebabzyacccdb32017-11-23 08:35:15 +0100204
Suraj Shetty182f4de2019-08-16 08:16:22 +0530205def get_basic_details(args, item, overwrite_warehouse=True):
tundebabzyacccdb32017-11-23 08:35:15 +0100206 """
207 :param args: {
208 "item_code": "",
209 "warehouse": None,
210 "customer": "",
211 "conversion_rate": 1.0,
212 "selling_price_list": None,
213 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530214 "price_list_uom_dependant": None,
tundebabzyacccdb32017-11-23 08:35:15 +0100215 "plc_conversion_rate": 1.0,
216 "doctype": "",
217 "name": "",
218 "supplier": None,
219 "transaction_date": None,
220 "conversion_rate": 1.0,
221 "buying_price_list": None,
222 "is_subcontracted": "Yes" / "No",
223 "ignore_pricing_rule": 0/1
224 "project": "",
225 barcode: "",
226 serial_no: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100227 currency: "",
228 update_stock: "",
229 price_list: "",
230 company: "",
231 order_type: "",
232 is_pos: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100233 project: "",
234 qty: "",
235 stock_qty: "",
ronelvcabrera370cdc02019-12-04 18:37:11 +0800236 conversion_factor: "",
237 against_blanket_order: 0/1
tundebabzyacccdb32017-11-23 08:35:15 +0100238 }
239 :param item: `item_code` of Item object
240 :return: frappe._dict
241 """
242
Rushabh Mehta1a763742014-10-03 16:36:43 +0530243 if not item:
244 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530245
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530246 if item.variant_of:
247 item.update_template_tables()
248
Manas Solankib16a4ec2018-05-04 16:49:33 +0530249 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530250 item_group_defaults = get_item_group_defaults(item.name, args.company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500251 brand_defaults = get_brand_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530252
Saqib438e0432020-04-03 10:02:56 +0530253 defaults = frappe._dict({
254 'item_defaults': item_defaults,
255 'item_group_defaults': item_group_defaults,
256 'brand_defaults': brand_defaults
257 })
marinatione05013e2020-04-06 22:13:13 +0530258
Saqib438e0432020-04-03 10:02:56 +0530259 warehouse = get_item_warehouse(item, args, overwrite_warehouse, defaults)
Nabin Hait36028bf2014-02-12 19:09:28 +0530260
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530261 if args.get('doctype') == "Material Request" and not args.get('material_request_type'):
262 args['material_request_type'] = frappe.db.get_value('Material Request',
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530263 args.get('name'), 'material_request_type', cache=True)
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530264
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530265 expense_account = None
266
267 if args.get('doctype') == 'Purchase Invoice' and item.is_fixed_asset:
268 from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
269 expense_account = get_asset_category_account(fieldname = "fixed_asset_account", item = args.item_code, company= args.company)
270
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530271 #Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
Saqib438e0432020-04-03 10:02:56 +0530272 if not args.get('uom'):
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530273 if args.get('doctype') in sales_doctypes:
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530274 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530275 elif (args.get('doctype') in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']) or \
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530276 (args.get('doctype') == 'Material Request' and args.get('material_request_type') == 'Purchase'):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530277 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
278 else:
279 args.uom = item.stock_uom
280
Rohit Waghchauree1f07042021-08-23 14:27:55 +0530281 if (args.get("batch_no") and
282 item.name != frappe.get_cached_value('Batch', args.get("batch_no"), 'item')):
283 args['batch_no'] = ''
284
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530285 out = frappe._dict({
Nabin Hait139dc7b2014-02-12 14:53:18 +0530286 "item_code": item.name,
287 "item_name": item.item_name,
Neil Trini Lasradoc48f06c2015-02-10 16:49:16 +0530288 "description": cstr(item.description).strip(),
289 "image": cstr(item.image).strip(),
Saurabhd3135532016-02-25 18:59:20 +0530290 "warehouse": warehouse,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500291 "income_account": get_default_income_account(args, item_defaults, item_group_defaults, brand_defaults),
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530292 "expense_account": expense_account or get_default_expense_account(args, item_defaults, item_group_defaults, brand_defaults) ,
GangaManoj657e9b52021-07-06 16:51:12 +0530293 "discount_account": None or get_default_discount_account(args, item_defaults),
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500294 "cost_center": get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults),
Rushabh Mehta551406a2017-04-21 12:40:19 +0530295 'has_serial_no': item.has_serial_no,
296 'has_batch_no': item.has_batch_no,
marinatione05013e2020-04-06 22:13:13 +0530297 "batch_no": args.get("batch_no"),
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530298 "uom": args.uom,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530299 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
Fisher Yu2cd49f52019-01-11 18:01:33 +0800300 "qty": flt(args.qty) or 1.0,
301 "stock_qty": flt(args.qty) or 1.0,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530302 "price_list_rate": 0.0,
303 "base_price_list_rate": 0.0,
304 "rate": 0.0,
305 "base_rate": 0.0,
306 "amount": 0.0,
307 "base_amount": 0.0,
Nabin Hait82e3e252015-02-23 16:58:30 +0530308 "net_rate": 0.0,
309 "net_amount": 0.0,
Saurabhc6dbe702015-10-19 14:17:52 +0530310 "discount_percentage": 0.0,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500311 "supplier": get_default_supplier(args, item_defaults, item_group_defaults, brand_defaults),
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530312 "update_stock": args.get("update_stock") if args.get('doctype') in ['Sales Invoice', 'Purchase Invoice'] else 0,
Rohit Waghchaurec858d522016-12-12 13:01:43 +0530313 "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 +0530314 "is_fixed_asset": item.is_fixed_asset,
Nabin Haite45ec662018-08-01 17:44:34 +0530315 "last_purchase_rate": item.last_purchase_rate if args.get("doctype") in ["Purchase Order"] else 0,
ronelvcabrera370cdc02019-12-04 18:37:11 +0800316 "transaction_date": args.get("transaction_date"),
rohitwaghchaureaa85e512020-05-19 19:51:45 +0530317 "against_blanket_order": args.get("against_blanket_order"),
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530318 "bom_no": item.get("default_bom"),
Ganga Manoj471f48f2021-08-03 14:39:38 +0530319 "weight_per_unit": item.get("weight_per_unit"),
320 "weight_uom": item.get("weight_uom")
Nabin Hait139dc7b2014-02-12 14:53:18 +0530321 })
Anand Doshibd67e872014-04-11 16:51:27 +0530322
Zlash65627be1d2019-01-15 14:16:32 +0530323 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zlash6580f5cb02018-08-29 11:39:08 +0530324 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530325
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530326 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530327 if item.stock_uom == args.uom:
328 out.conversion_factor = 1.0
329 else:
330 out.conversion_factor = args.conversion_factor or \
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530331 get_conversion_factor(item.name, args.uom).get("conversion_factor")
mbauskar287fe812017-04-10 19:15:57 +0530332
333 args.conversion_factor = out.conversion_factor
334 out.stock_qty = out.qty * out.conversion_factor
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530335
Shreya Shah44fa9a62018-01-08 14:58:20 +0530336 # calculate last purchase rate
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530337 if args.get('doctype') in purchase_doctypes:
338 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
339 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 +0530340
Nabin Haitb09ed412015-02-17 10:33:58 +0530341 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530342 for d in [
343 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530344 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530345 ["Cost Center", "cost_center", "cost_center"],
346 ["Warehouse", "warehouse", ""]]:
Nabin Hait33df0b42018-05-26 09:09:02 +0530347 if not out[d[1]]:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530348 out[d[1]] = frappe.get_cached_value('Company', args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530349
Giovanni2144e022017-12-10 17:27:09 +0100350 for fieldname in ("item_name", "item_group", "barcodes", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530351 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530352
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530353 if args.get("manufacturer"):
354 part_no = get_item_manufacturer_part_no(args.get("item_code"), args.get("manufacturer"))
355 if part_no:
356 out["manufacturer_part_no"] = part_no
357 else:
358 out["manufacturer_part_no"] = None
359 out["manufacturer"] = None
marination3e7a8ab2020-04-07 21:00:57 +0530360 else:
rohitwaghchaurebe16e5c2020-05-01 10:50:17 +0530361 data = frappe.get_value("Item", item.name,
362 ["default_item_manufacturer", "default_manufacturer_part_no"] , as_dict=1)
363
364 if data:
365 out.update({
366 "manufacturer": data.default_item_manufacturer,
367 "manufacturer_part_no": data.default_manufacturer_part_no
368 })
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530369
Nabin Hait34c551d2019-07-03 10:34:31 +0530370 child_doctype = args.doctype + ' Item'
371 meta = frappe.get_meta(child_doctype)
372 if meta.get_field("barcode"):
373 update_barcode_value(out)
374
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530375 if out.get("weight_per_unit"):
376 out['total_weight'] = out.weight_per_unit * out.stock_qty
377
Nabin Hait436f5262014-02-10 14:47:54 +0530378 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530379
Saqib438e0432020-04-03 10:02:56 +0530380def get_item_warehouse(item, args, overwrite_warehouse, defaults={}):
381 if not defaults:
382 defaults = frappe._dict({
383 'item_defaults' : get_item_defaults(item.name, args.company),
384 'item_group_defaults' : get_item_group_defaults(item.name, args.company),
385 'brand_defaults' : get_brand_defaults(item.name, args.company)
386 })
387
388 if overwrite_warehouse or not args.warehouse:
389 warehouse = (
390 args.get("set_warehouse") or
391 defaults.item_defaults.get("default_warehouse") or
392 defaults.item_group_defaults.get("default_warehouse") or
393 defaults.brand_defaults.get("default_warehouse") or
394 args.get('warehouse')
395 )
396
397 if not warehouse:
398 defaults = frappe.defaults.get_defaults() or {}
399 warehouse_exists = frappe.db.exists("Warehouse", {
400 'name': defaults.default_warehouse,
401 'company': args.company
402 })
403 if defaults.get("default_warehouse") and warehouse_exists:
404 warehouse = defaults.default_warehouse
405
406 else:
407 warehouse = args.get('warehouse')
marinatione05013e2020-04-06 22:13:13 +0530408
Marica3b1be2b2020-10-22 17:04:31 +0530409 if not warehouse:
410 default_warehouse = frappe.db.get_single_value("Stock Settings", "default_warehouse")
411 if frappe.db.get_value("Warehouse", default_warehouse, "company") == args.company:
412 return default_warehouse
413
Saqib438e0432020-04-03 10:02:56 +0530414 return warehouse
415
Nabin Hait34c551d2019-07-03 10:34:31 +0530416def update_barcode_value(out):
Nabin Hait34c551d2019-07-03 10:34:31 +0530417 barcode_data = get_barcode_data([out])
418
419 # If item has one barcode then update the value of the barcode field
420 if barcode_data and len(barcode_data.get(out.item_code)) == 1:
421 out['barcode'] = barcode_data.get(out.item_code)[0]
422
Saqiba6f98d42020-07-23 18:51:26 +0530423def get_barcode_data(items_list):
424 # get itemwise batch no data
425 # exmaple: {'LED-GRE': [Batch001, Batch002]}
426 # where LED-GRE is item code, SN0001 is serial no and Pune is warehouse
427
428 itemwise_barcode = {}
429 for item in items_list:
430 barcodes = frappe.db.sql("""
431 select barcode from `tabItem Barcode` where parent = %s
432 """, item.item_code, as_dict=1)
433
434 for barcode in barcodes:
435 if item.item_code not in itemwise_barcode:
436 itemwise_barcode.setdefault(item.item_code, [])
437 itemwise_barcode[item.item_code].append(barcode.get("barcode"))
438
439 return itemwise_barcode
440
Zlash6580f5cb02018-08-29 11:39:08 +0530441@frappe.whitelist()
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530442def get_item_tax_info(company, tax_category, item_codes, item_rates=None, item_tax_templates=None):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500443 out = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530444
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530445 if item_tax_templates is None:
Deepesh Gargcae42b482021-06-25 13:34:00 +0530446 item_tax_templates = {}
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +0530447
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530448 if item_rates is None:
449 item_rates = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530450
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530451 if isinstance(item_codes, (str,)):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500452 item_codes = json.loads(item_codes)
453
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530454 if isinstance(item_rates, (str,)):
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530455 item_rates = json.loads(item_rates)
456
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530457 if isinstance(item_tax_templates, (str,)):
Deepesh Garg94d46042021-06-23 20:56:27 +0530458 item_tax_templates = json.loads(item_tax_templates)
459
Saif Ur Rehman67786682018-12-27 02:11:07 +0500460 for item_code in item_codes:
Deepesh Garg94d46042021-06-23 20:56:27 +0530461 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 +0500462 continue
Deepesh Garg94d46042021-06-23 20:56:27 +0530463
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530464 out[item_code[1]] = {}
465 item = frappe.get_cached_doc("Item", item_code[0])
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530466 args = {"company": company, "tax_category": tax_category, "net_rate": item_rates.get(item_code[1])}
Deepesh Garg269962a2021-06-23 22:52:51 +0530467
468 if item_tax_templates:
469 args.update({"item_tax_template": item_tax_templates.get(item_code[1])})
Deepesh Garg94d46042021-06-23 20:56:27 +0530470
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530471 get_item_tax_template(args, item, out[item_code[1]])
472 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 +0500473
474 return out
475
476def get_item_tax_template(args, item, out):
477 """
478 args = {
479 "tax_category": None
480 "item_tax_template": None
481 }
482 """
483 item_tax_template = args.get("item_tax_template")
Deepesh Garg94d46042021-06-23 20:56:27 +0530484 item_tax_template = _get_item_tax_template(args, item.taxes, out)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500485
486 if not item_tax_template:
487 item_group = item.item_group
488 while item_group and not item_tax_template:
489 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
490 item_tax_template = _get_item_tax_template(args, item_group_doc.taxes, out)
491 item_group = item_group_doc.parent_item_group
492
18alantom308905b2021-05-03 23:34:34 +0530493def _get_item_tax_template(args, taxes, out=None, for_validate=False):
494 if out is None:
495 out = {}
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530496 taxes_with_validity = []
497 taxes_with_no_validity = []
498
499 for tax in taxes:
mohammadahmad1990261ecba2020-06-25 01:56:53 +0500500 tax_company = frappe.get_value("Item Tax Template", tax.item_tax_template, 'company')
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530501 if (tax.valid_from or tax.maximum_net_rate) and tax_company == args['company']:
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530502 # In purchase Invoice first preference will be given to supplier invoice date
503 # if supplier date is not present then posting date
504 validation_date = args.get('transaction_date') or args.get('bill_date') or args.get('posting_date')
505
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530506 if getdate(tax.valid_from) <= getdate(validation_date) \
507 and is_within_valid_range(args, tax):
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530508 taxes_with_validity.append(tax)
509 else:
mohammadahmad1990261ecba2020-06-25 01:56:53 +0500510 if tax_company == args['company']:
mohammadahmad1990e39649b2020-06-18 11:42:53 +0500511 taxes_with_no_validity.append(tax)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530512
513 if taxes_with_validity:
514 taxes = sorted(taxes_with_validity, key = lambda i: i.valid_from, reverse=True)
515 else:
516 taxes = taxes_with_no_validity
517
518 if for_validate:
519 return [tax.item_tax_template for tax in taxes if (cstr(tax.tax_category) == cstr(args.get('tax_category')) \
520 and (tax.item_tax_template not in taxes))]
521
522 # all templates have validity and no template is valid
523 if not taxes_with_validity and (not taxes_with_no_validity):
524 return None
525
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530526 # do not change if already a valid template
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530527 if args.get('item_tax_template') in {t.item_tax_template for t in taxes}:
Deepesh Garg94d46042021-06-23 20:56:27 +0530528 out["item_tax_template"] = args.get('item_tax_template')
Deepesh Garg3646c302021-06-05 13:21:03 +0530529 return args.get('item_tax_template')
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530530
Saif Ur Rehman67786682018-12-27 02:11:07 +0500531 for tax in taxes:
532 if cstr(tax.tax_category) == cstr(args.get("tax_category")):
533 out["item_tax_template"] = tax.item_tax_template
534 return tax.item_tax_template
535 return None
536
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530537def is_within_valid_range(args, tax):
538 if not flt(tax.maximum_net_rate):
539 # No range specified, just ignore
540 return True
541 elif flt(tax.minimum_net_rate) <= flt(args.get('net_rate')) <= flt(tax.maximum_net_rate):
542 return True
543
544 return False
545
Saif Ur Rehman67786682018-12-27 02:11:07 +0500546@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500547def get_item_tax_map(company, item_tax_template, as_json=True):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500548 item_tax_map = {}
549 if item_tax_template:
550 template = frappe.get_cached_doc("Item Tax Template", item_tax_template)
551 for d in template.taxes:
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500552 if frappe.get_cached_value("Account", d.tax_type, "company") == company:
553 item_tax_map[d.tax_type] = d.tax_rate
Saif Ur Rehman67786682018-12-27 02:11:07 +0500554
555 return json.dumps(item_tax_map) if as_json else item_tax_map
556
557@frappe.whitelist()
Zlash6580f5cb02018-08-29 11:39:08 +0530558def calculate_service_end_date(args, item=None):
559 args = process_args(args)
560 if not item:
561 item = frappe.get_cached_doc("Item", args.item_code)
562
Zlash65627be1d2019-01-15 14:16:32 +0530563 doctype = args.get("parenttype") or args.get("doctype")
Zlash65a3dd7982019-01-15 14:36:11 +0530564 if doctype == "Sales Invoice":
565 enable_deferred = "enable_deferred_revenue"
566 no_of_months = "no_of_months"
567 account = "deferred_revenue_account"
568 else:
569 enable_deferred = "enable_deferred_expense"
570 no_of_months = "no_of_months_exp"
571 account = "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530572
Zlash6580f5cb02018-08-29 11:39:08 +0530573 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
Zarrare83ff382018-09-21 15:45:40 +0530574 service_end_date = add_months(service_start_date, item.get(no_of_months))
Zlash6580f5cb02018-08-29 11:39:08 +0530575 deferred_detail = {
Zlash6580f5cb02018-08-29 11:39:08 +0530576 "service_start_date": service_start_date,
577 "service_end_date": service_end_date
578 }
Zarrare83ff382018-09-21 15:45:40 +0530579 deferred_detail[enable_deferred] = item.get(enable_deferred)
580 deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)
Zlash6580f5cb02018-08-29 11:39:08 +0530581
582 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100583
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500584def get_default_income_account(args, item, item_group, brand):
Manas Solanki38667ab2018-05-16 16:55:23 +0530585 return (item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530586 or item_group.get("income_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500587 or brand.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530588 or args.income_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530589
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500590def get_default_expense_account(args, item, item_group, brand):
Manas Solanki38667ab2018-05-16 16:55:23 +0530591 return (item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530592 or item_group.get("expense_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500593 or brand.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530594 or args.expense_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530595
GangaManoj0b7d8fb2021-07-13 01:37:30 +0530596def get_default_discount_account(args, item):
597 return (item.get("default_discount_account")
GangaManoj657e9b52021-07-06 16:51:12 +0530598 or args.discount_account)
599
Zarrare83ff382018-09-21 15:45:40 +0530600def get_default_deferred_account(args, item, fieldname=None):
Zlash65627be1d2019-01-15 14:16:32 +0530601 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zarrare83ff382018-09-21 15:45:40 +0530602 return (item.get(fieldname)
603 or args.get(fieldname)
604 or frappe.get_cached_value('Company', args.company, "default_"+fieldname))
Manas Solanki03938482018-05-14 16:16:46 +0530605 else:
606 return None
607
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530608def get_default_cost_center(args, item=None, item_group=None, brand=None, company=None):
Nabin Hait50238c32018-08-08 18:43:04 +0530609 cost_center = None
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530610
611 if not company and args.get("company"):
612 company = args.get("company")
613
Nabin Hait50238c32018-08-08 18:43:04 +0530614 if args.get('project'):
615 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530616
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530617 if not cost_center and (item and item_group and brand):
Nabin Hait50238c32018-08-08 18:43:04 +0530618 if args.get('customer'):
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500619 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 +0530620 else:
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500621 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 +0530622
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530623 elif not cost_center and args.get("item_code") and company:
624 for method in ["get_item_defaults", "get_item_group_defaults", "get_brand_defaults"]:
625 path = "erpnext.stock.get_item_details.{0}".format(method)
626 data = frappe.get_attr(path)(args.get("item_code"), company)
627
628 if data and (data.selling_cost_center or data.buying_cost_center):
629 return data.selling_cost_center or data.buying_cost_center
630
631 if not cost_center and args.get("cost_center"):
632 cost_center = args.get("cost_center")
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530633
634 if (company and cost_center
635 and frappe.get_cached_value("Cost Center", cost_center, "company") != company):
636 return None
637
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530638 if not cost_center and company:
639 cost_center = frappe.get_cached_value("Company",
640 company, "cost_center")
641
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530642 return cost_center
Rushabh Mehta1a763742014-10-03 16:36:43 +0530643
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500644def get_default_supplier(args, item, item_group, brand):
Shreya Shah3c9839f2018-07-17 18:01:44 +0530645 return (item.get("default_supplier")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500646 or item_group.get("default_supplier")
647 or brand.get("default_supplier"))
Shreya Shah3c9839f2018-07-17 18:01:44 +0530648
Ankush16d4de52021-08-09 10:41:24 +0530649def get_price_list_rate(args, item_doc, out=None):
650 if out is None:
651 out = frappe._dict()
652
Anand Doshi39a28912016-02-15 11:42:18 +0530653 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530654
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530655 if meta.get_field("currency") or args.get('currency'):
Maricae8bc9122021-04-19 11:05:21 +0530656 if not args.get("price_list_currency") or not args.get("plc_conversion_rate"):
657 # if currency and plc_conversion_rate exist then
658 # `get_price_list_currency_and_exchange_rate` has already been called
659 pl_details = get_price_list_currency_and_exchange_rate(args)
660 args.update(pl_details)
661
Nabin Hait06c8cf42019-05-16 19:17:02 +0530662 if meta.get_field("currency"):
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530663 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530664
Ankush16d4de52021-08-09 10:41:24 +0530665 price_list_rate = get_price_list_rate_for(args, item_doc.name)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530666
hiousi1516e292019-01-08 18:34:08 +0100667 # variant
Ankush16d4de52021-08-09 10:41:24 +0530668 if price_list_rate is None and item_doc.variant_of:
hiousi1516e292019-01-08 18:34:08 +0100669 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530670
671 # insert in database
Ankush16d4de52021-08-09 10:41:24 +0530672 if price_list_rate is None:
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530673 if args.price_list and args.rate:
674 insert_item_price(args)
Ankush16d4de52021-08-09 10:41:24 +0530675 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530676
Nabin Hait436f5262014-02-10 14:47:54 +0530677 out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) \
678 / flt(args.conversion_rate)
mbauskar287fe812017-04-10 19:15:57 +0530679
Nabin Hait34d28222016-01-19 15:45:49 +0530680 if not out.price_list_rate and args.transaction_type=="buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530681 from erpnext.stock.doctype.item.item import get_last_purchase_details
Anand Doshibd67e872014-04-11 16:51:27 +0530682 out.update(get_last_purchase_details(item_doc.name,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530683 args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530684
Ankush16d4de52021-08-09 10:41:24 +0530685 return out
686
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530687def insert_item_price(args):
688 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530689 if frappe.db.get_value("Price List", args.price_list, "currency", cache=True) == args.currency \
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530690 and cint(frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")):
691 if frappe.has_permission("Item Price", "write"):
Nabin Haite45ec662018-08-01 17:44:34 +0530692 price_list_rate = (args.rate / args.get('conversion_factor')
693 if args.get("conversion_factor") else args.rate)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530694
Nabin Haitb479a872018-09-07 13:17:11 +0530695 item_price = frappe.db.get_value('Item Price',
696 {'item_code': args.item_code, 'price_list': args.price_list, 'currency': args.currency},
697 ['name', 'price_list_rate'], as_dict=1)
698 if item_price and item_price.name:
699 if item_price.price_list_rate != price_list_rate:
700 frappe.db.set_value('Item Price', item_price.name, "price_list_rate", price_list_rate)
701 frappe.msgprint(_("Item Price updated for {0} in Price List {1}").format(args.item_code,
702 args.price_list), alert=True)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530703 else:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530704 item_price = frappe.get_doc({
705 "doctype": "Item Price",
706 "price_list": args.price_list,
707 "item_code": args.item_code,
708 "currency": args.currency,
709 "price_list_rate": price_list_rate
710 })
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530711 item_price.insert()
712 frappe.msgprint(_("Item Price added for {0} in Price List {1}").format(args.item_code,
Rushabh Mehta49f97472018-08-30 18:50:48 +0530713 args.price_list), alert=True)
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530714
Nabin Hait01ca3e52019-01-25 16:25:15 +0530715def get_item_price(args, item_code, ignore_party=False):
Nabin Haite45ec662018-08-01 17:44:34 +0530716 """
717 Get name, price_list_rate from Item Price based on conditions
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530718 Check if the desired qty is within the increment of the packing list.
Nabin Haite45ec662018-08-01 17:44:34 +0530719 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
Nabin Hait03b116d2020-01-20 15:45:04 +0530720 optional fields transaction_date, customer, supplier
Nabin Haite45ec662018-08-01 17:44:34 +0530721 :param item_code: str, Item Doctype field item_code
722 """
723
724 args['item_code'] = item_code
Nabin Haite45ec662018-08-01 17:44:34 +0530725
Nabin Hait01ca3e52019-01-25 16:25:15 +0530726 conditions = """where item_code=%(item_code)s
Nabin Haite45ec662018-08-01 17:44:34 +0530727 and price_list=%(price_list)s
728 and ifnull(uom, '') in ('', %(uom)s)"""
729
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530730 conditions += "and ifnull(batch_no, '') in ('', %(batch_no)s)"
731
Nabin Hait01ca3e52019-01-25 16:25:15 +0530732 if not ignore_party:
Nabin Hait01ca3e52019-01-25 16:25:15 +0530733 if args.get("customer"):
734 conditions += " and customer=%(customer)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530735 elif args.get("supplier"):
Nabin Hait01ca3e52019-01-25 16:25:15 +0530736 conditions += " and supplier=%(supplier)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530737 else:
Saqib41b47a62020-05-15 04:24:36 +0530738 conditions += "and (customer is null or customer = '') and (supplier is null or supplier = '')"
Nabin Hait01ca3e52019-01-25 16:25:15 +0530739
Nabin Haite45ec662018-08-01 17:44:34 +0530740 if args.get('transaction_date'):
741 conditions += """ and %(transaction_date)s between
742 ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
Deepesh Gargf15ff5f2020-07-11 13:58:53 +0530743
Andy Zhub60abb02020-07-03 14:13:15 +1200744 if args.get('posting_date'):
745 conditions += """ and %(posting_date)s between
746 ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
Nabin Haite45ec662018-08-01 17:44:34 +0530747
748 return frappe.db.sql(""" select name, price_list_rate, uom
749 from `tabItem Price` {conditions}
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530750 order by valid_from desc, batch_no desc, uom desc """.format(conditions=conditions), args)
Nabin Haite45ec662018-08-01 17:44:34 +0530751
752def get_price_list_rate_for(args, item_code):
753 """
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530754 :param customer: link to Customer DocType
755 :param supplier: link to Supplier DocType
Nabin Haite45ec662018-08-01 17:44:34 +0530756 :param price_list: str (Standard Buying or Standard Selling)
757 :param item_code: str, Item Doctype field item_code
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530758 :param qty: Desired Qty
Nabin Haite45ec662018-08-01 17:44:34 +0530759 :param transaction_date: Date of the price
760 """
761 item_price_args = {
762 "item_code": item_code,
763 "price_list": args.get('price_list'),
764 "customer": args.get('customer'),
765 "supplier": args.get('supplier'),
766 "uom": args.get('uom'),
Nabin Haite45ec662018-08-01 17:44:34 +0530767 "transaction_date": args.get('transaction_date'),
Andy Zhub60abb02020-07-03 14:13:15 +1200768 "posting_date": args.get('posting_date'),
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530769 "batch_no": args.get('batch_no')
Nabin Haite45ec662018-08-01 17:44:34 +0530770 }
771
772 item_price_data = 0
773 price_list_rate = get_item_price(item_price_args, item_code)
774 if price_list_rate:
775 desired_qty = args.get("qty")
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530776 if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
Nabin Haite45ec662018-08-01 17:44:34 +0530777 item_price_data = price_list_rate
778 else:
Don-Leopardoccdf1932020-01-09 03:54:43 -0300779 for field in ["customer", "supplier"]:
Nabin Haite45ec662018-08-01 17:44:34 +0530780 del item_price_args[field]
781
Nabin Haite321fbb2020-01-16 13:37:25 +0530782 general_price_list_rate = get_item_price(item_price_args, item_code,
783 ignore_party=args.get("ignore_party"))
Don-Leopardoccdf1932020-01-09 03:54:43 -0300784
Nabin Haite45ec662018-08-01 17:44:34 +0530785 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530786 item_price_args["uom"] = args.get("stock_uom")
Nabin Hait01ca3e52019-01-25 16:25:15 +0530787 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 +0530788
789 if general_price_list_rate:
790 item_price_data = general_price_list_rate
791
792 if item_price_data:
793 if item_price_data[0][2] == args.get("uom"):
794 return item_price_data[0][1]
795 elif not args.get('price_list_uom_dependant'):
796 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
797 else:
798 return item_price_data[0][1]
799
800def check_packing_list(price_list_rate_name, desired_qty, item_code):
801 """
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530802 Check if the desired qty is within the increment of the packing list.
Nabin Haite45ec662018-08-01 17:44:34 +0530803 :param price_list_rate_name: Name of Item Price
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530804 :param desired_qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530805 :param item_code: str, Item Doctype field item_code
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530806 :param qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530807 """
808
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530809 flag = True
Nabin Haite45ec662018-08-01 17:44:34 +0530810 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530811 if item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +0530812 packing_increment = desired_qty % item_price.packing_unit
813
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530814 if packing_increment != 0:
815 flag = False
816
817 return flag
Rushabh Mehta1a763742014-10-03 16:36:43 +0530818
Nabin Hait436f5262014-02-10 14:47:54 +0530819def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +0530820 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +0530821
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +0530822 company_currency = frappe.get_cached_value('Company', args.company, "default_currency")
823 if (not args.conversion_rate and args.currency==company_currency):
Anand Doshife13bfe2015-08-25 12:49:40 +0530824 args.conversion_rate = 1.0
825
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +0530826 if (not args.ignore_conversion_rate and args.conversion_rate == 1 and args.currency!=company_currency):
827 args.conversion_rate = get_exchange_rate(args.currency,
828 company_currency, args.transaction_date, "for_buying") or 1.0
829
Nabin Hait436f5262014-02-10 14:47:54 +0530830 # validate currency conversion rate
Anand Doshibd67e872014-04-11 16:51:27 +0530831 validate_conversion_rate(args.currency, args.conversion_rate,
Nabin Hait436f5262014-02-10 14:47:54 +0530832 meta.get_label("conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530833
834 args.conversion_rate = flt(args.conversion_rate,
835 get_field_precision(meta.get_field("conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530836 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530837
Nabin Hait06c8cf42019-05-16 19:17:02 +0530838 if args.price_list:
839 if (not args.plc_conversion_rate
840 and args.price_list_currency==frappe.db.get_value("Price List", args.price_list, "currency", cache=True)):
841 args.plc_conversion_rate = 1.0
Manas Solanki3504a232018-06-06 12:46:06 +0530842
Nabin Hait06c8cf42019-05-16 19:17:02 +0530843 # validate price list currency conversion rate
844 if not args.get("price_list_currency"):
845 throw(_("Price List Currency not selected"))
846 else:
847 validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate,
848 meta.get_label("plc_conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530849
Nabin Hait06c8cf42019-05-16 19:17:02 +0530850 if meta.get_field("plc_conversion_rate"):
851 args.plc_conversion_rate = flt(args.plc_conversion_rate,
852 get_field_precision(meta.get_field("plc_conversion_rate"),
853 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530854
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530855def get_party_item_code(args, item_doc, out):
Nabin Hait34d28222016-01-19 15:45:49 +0530856 if args.transaction_type=="selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +0530857 out.customer_item_code = None
Nabin Hait34c551d2019-07-03 10:34:31 +0530858
859 if args.quotation_to and args.quotation_to != 'Customer':
860 return
861
Nabin Hait79f091e2014-12-26 11:41:15 +0530862 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +0530863
864 if customer_item_code:
865 out.customer_item_code = customer_item_code[0].ref_code
866 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +0530867 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +0530868 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
869 if customer_group_item_code and not customer_group_item_code[0].customer_name:
870 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +0530871
Nabin Hait34d28222016-01-19 15:45:49 +0530872 if args.transaction_type=="buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +0530873 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +0530874 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +0530875
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530876def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530877 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +0530878
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530879 if not frappe.flags.pos_profile and not pos_profile:
880 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get('pos_profile'))
Anand Doshibd67e872014-04-11 16:51:27 +0530881
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530882 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +0530883 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530884 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530885 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530886
Nabin Hait436f5262014-02-10 14:47:54 +0530887 if res.get("warehouse"):
Saurabhd3135532016-02-25 18:59:20 +0530888 res.actual_qty = get_bin_details(args.item_code,
Nabin Hait436f5262014-02-10 14:47:54 +0530889 res.warehouse).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +0530890
Nabin Hait436f5262014-02-10 14:47:54 +0530891 return res
892
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530893@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530894def get_pos_profile(company, pos_profile=None, user=None):
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530895 if pos_profile: return frappe.get_cached_doc('POS Profile', pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530896
897 if not user:
898 user = frappe.session['user']
899
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530900 condition = "pfu.user = %(user)s AND pfu.default=1"
901 if user and company:
902 condition = "pfu.user = %(user)s AND pf.company = %(company)s AND pfu.default=1"
903
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530904 pos_profile = frappe.db.sql("""SELECT pf.*
905 FROM
906 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
907 ON
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530908 pf.name = pfu.parent
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530909 WHERE
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530910 {cond} AND pf.disabled = 0
911 """.format(cond = condition), {
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530912 'user': user,
913 'company': company
914 }, as_dict=1)
Anand Doshibd67e872014-04-11 16:51:27 +0530915
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530916 if not pos_profile and company:
917 pos_profile = frappe.db.sql("""SELECT pf.*
918 FROM
919 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
920 ON
921 pf.name = pfu.parent
922 WHERE
923 pf.company = %(company)s AND pf.disabled = 0
924 """, {
925 'company': company
926 }, as_dict=1)
927
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530928 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +0530929
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530930def get_serial_nos_by_fifo(args, sales_order=None):
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530931 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
932 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530933 where item_code=%(item_code)s and warehouse=%(warehouse)s and
934 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
935 order by timestamp(purchase_date, purchase_time)
936 asc limit %(qty)s""",
937 {
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530938 "item_code": args.item_code,
939 "warehouse": args.warehouse,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530940 "qty": abs(cint(args.stock_qty)),
941 "sales_order": sales_order
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530942 }))
Nabin Hait08222152014-02-28 11:30:47 +0530943
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530944def get_serial_no_batchwise(args, sales_order=None):
Shreyaa20157a2018-04-13 12:03:42 +0530945 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
946 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530947 where item_code=%(item_code)s and warehouse=%(warehouse)s and
948 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
949 and batch_no=IF(%(batch_no)s IS NULL, batch_no, %(batch_no)s) order
950 by timestamp(purchase_date, purchase_time) asc limit %(qty)s""", {
Shreyaa20157a2018-04-13 12:03:42 +0530951 "item_code": args.item_code,
952 "warehouse": args.warehouse,
953 "batch_no": args.batch_no,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530954 "qty": abs(cint(args.stock_qty)),
955 "sales_order": sales_order
Shreyaa20157a2018-04-13 12:03:42 +0530956 }))
957
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530958@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530959def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530960 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530961 filters = {"parent": item_code, "uom": uom}
962 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +0530963 filters["parent"] = ("in", (item_code, variant_of))
Sagar Vora508189e2018-09-11 17:22:25 +0530964 conversion_factor = frappe.db.get_value("UOM Conversion Detail",
965 filters, "conversion_factor")
966 if not conversion_factor:
967 stock_uom = frappe.db.get_value("Item", item_code, "stock_uom")
968 conversion_factor = get_uom_conv_factor(uom, stock_uom)
rohitwaghchaureffdadbf2019-01-08 16:21:25 +0530969 return {"conversion_factor": conversion_factor or 1.0}
Nabin Hait08222152014-02-28 11:30:47 +0530970
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530971@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530972def get_projected_qty(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530973 return {"projected_qty": frappe.db.get_value("Bin",
Nabin Hait436f5262014-02-10 14:47:54 +0530974 {"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
Nabin Hait08222152014-02-28 11:30:47 +0530975
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530976@frappe.whitelist()
Anupam4980dd62021-03-15 11:37:46 +0530977def get_bin_details(item_code, warehouse, company=None):
978 bin_details = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Nabin Haita804d6d2018-08-29 13:34:58 +0530979 ["projected_qty", "actual_qty", "reserved_qty"], as_dict=True, cache=True) \
Shreya Shahbe770332018-08-22 14:45:22 +0530980 or {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
Anupam4980dd62021-03-15 11:37:46 +0530981 if company:
982 bin_details['company_total_stock'] = get_company_total_stock(item_code, company)
983 return bin_details
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530984
Anupam4980dd62021-03-15 11:37:46 +0530985def get_company_total_stock(item_code, company):
Anuja Pawarf132ed42021-05-07 12:11:09 +0530986 return frappe.db.sql("""SELECT sum(actual_qty) from
987 (`tabBin` INNER JOIN `tabWarehouse` ON `tabBin`.warehouse = `tabWarehouse`.name)
18alantome36f3032021-05-03 19:49:22 +0530988 WHERE `tabWarehouse`.company = %s and `tabBin`.item_code = %s""",
989 (company, item_code))[0][0]
Anupam4980dd62021-03-15 11:37:46 +0530990
991@frappe.whitelist()
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530992def get_serial_no_details(item_code, warehouse, stock_qty, serial_no):
993 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "serial_no":serial_no})
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530994 serial_no = get_serial_no(args)
995 return {'serial_no': serial_no}
Rushabh Mehta985cb822016-12-30 15:06:54 +0530996
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530997@frappe.whitelist()
Rohit Waghchaure6daab3c2019-09-19 17:01:26 +0530998def 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 +0530999 bin_details_and_serial_nos = {}
1000 bin_details_and_serial_nos.update(get_bin_details(item_code, warehouse))
Rushabh Mehta49f97472018-08-30 18:50:48 +05301001 if flt(stock_qty) > 0:
Shreyaa20157a2018-04-13 12:03:42 +05301002 if has_batch_no:
1003 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty})
1004 serial_no = get_serial_no(args)
1005 bin_details_and_serial_nos.update({'serial_no': serial_no})
1006 return bin_details_and_serial_nos
1007
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301008 bin_details_and_serial_nos.update(get_serial_no_details(item_code, warehouse, stock_qty, serial_no))
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301009 return bin_details_and_serial_nos
Anand Doshidffec8f2014-07-01 17:45:15 +05301010
1011@frappe.whitelist()
Shreyaa20157a2018-04-13 12:03:42 +05301012def get_batch_qty_and_serial_no(batch_no, stock_qty, warehouse, item_code, has_serial_no):
1013 batch_qty_and_serial_no = {}
1014 batch_qty_and_serial_no.update(get_batch_qty(batch_no, warehouse, item_code))
1015
1016 if (flt(batch_qty_and_serial_no.get('actual_batch_qty')) >= flt(stock_qty)) and has_serial_no:
1017 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "batch_no":batch_no})
1018 serial_no = get_serial_no(args)
1019 batch_qty_and_serial_no.update({'serial_no': serial_no})
1020 return batch_qty_and_serial_no
1021
1022@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +05301023def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +07001024 from erpnext.stock.doctype.batch import batch
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +05301025 if batch_no:
Rushabh Mehtae385b5b2017-04-20 15:21:01 +05301026 return {'actual_batch_qty': batch.get_batch_qty(batch_no, warehouse)}
Rushabh Mehta1e8025b2015-07-24 15:16:25 +05301027
Anand Doshidffec8f2014-07-01 17:45:15 +05301028@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301029def apply_price_list(args, as_doc=False):
1030 """Apply pricelist on a document-like dict object and return as
1031 {'parent': dict, 'children': list}
1032
1033 :param args: See below
1034 :param as_doc: Updates value in the passed dict
1035
Anand Doshidffec8f2014-07-01 17:45:15 +05301036 args = {
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301037 "doctype": "",
1038 "name": "",
1039 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
Anand Doshidffec8f2014-07-01 17:45:15 +05301040 "conversion_rate": 1.0,
1041 "selling_price_list": None,
1042 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +05301043 "price_list_uom_dependant": None,
Anand Doshidffec8f2014-07-01 17:45:15 +05301044 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301045 "doctype": "",
1046 "name": "",
Anand Doshidffec8f2014-07-01 17:45:15 +05301047 "supplier": None,
1048 "transaction_date": None,
1049 "conversion_rate": 1.0,
1050 "buying_price_list": None,
Anand Doshidffec8f2014-07-01 17:45:15 +05301051 "ignore_pricing_rule": 0/1
1052 }
1053 """
1054 args = process_args(args)
1055
1056 parent = get_price_list_currency_and_exchange_rate(args)
Maricae8bc9122021-04-19 11:05:21 +05301057 args.update(parent)
1058
Anand Doshidffec8f2014-07-01 17:45:15 +05301059 children = []
1060
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301061 if "items" in args:
1062 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +05301063 args.update(parent)
1064
1065 for item in item_list:
1066 args_copy = frappe._dict(args.copy())
1067 args_copy.update(item)
1068 item_details = apply_price_list_on_item(args_copy)
1069 children.append(item_details)
1070
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301071 if as_doc:
Shreya Shahb13a54a2017-12-06 19:17:04 +05301072 args.price_list_currency = parent.price_list_currency,
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301073 args.plc_conversion_rate = parent.plc_conversion_rate
1074 if args.get('items'):
1075 for i, item in enumerate(args.get('items')):
1076 for fieldname in children[i]:
1077 # if the field exists in the original doc
1078 # update the value
1079 if fieldname in item and fieldname not in ("name", "doctype"):
1080 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301081 return args
1082 else:
1083 return {
1084 "parent": parent,
1085 "children": children
1086 }
Anand Doshidffec8f2014-07-01 17:45:15 +05301087
1088def apply_price_list_on_item(args):
Anand Doshidffec8f2014-07-01 17:45:15 +05301089 item_doc = frappe.get_doc("Item", args.item_code)
Ankush16d4de52021-08-09 10:41:24 +05301090 item_details = get_price_list_rate(args, item_doc)
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301091
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +05301092 item_details.update(get_pricing_rule_for_item(args, item_details.price_list_rate))
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301093
Anand Doshidffec8f2014-07-01 17:45:15 +05301094 return item_details
1095
Anand Doshidffec8f2014-07-01 17:45:15 +05301096def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +05301097 if not args.price_list:
1098 return {}
1099
Shreya3f778522018-05-15 16:59:20 +05301100 if args.doctype in ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']:
1101 args.update({"exchange_rate": "for_selling"})
1102 elif args.doctype in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']:
1103 args.update({"exchange_rate": "for_buying"})
1104
rohitwaghchaurea85ddf22019-11-19 18:47:48 +05301105 price_list_details = get_price_list_details(args.price_list)
1106
1107 price_list_currency = price_list_details.get("currency")
1108 price_list_uom_dependant = price_list_details.get("price_list_uom_dependant")
1109
Anand Doshidffec8f2014-07-01 17:45:15 +05301110 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +01001111 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +05301112
Nabin Haitdd82bf22015-05-11 16:49:17 +05301113 if (not plc_conversion_rate) or (price_list_currency and args.price_list_currency \
1114 and price_list_currency != args.price_list_currency):
Rushabh Mehta6b537922017-03-14 16:59:11 +05301115 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
tundebabzy6e90f492018-02-12 10:48:57 +01001116 plc_conversion_rate = get_exchange_rate(price_list_currency, company_currency,
Shreya3f778522018-05-15 16:59:20 +05301117 args.transaction_date, args.exchange_rate) or plc_conversion_rate
Anand Doshidffec8f2014-07-01 17:45:15 +05301118
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301119 return frappe._dict({
Anand Doshidffec8f2014-07-01 17:45:15 +05301120 "price_list_currency": price_list_currency,
Shreya Shahb13a54a2017-12-06 19:17:04 +05301121 "price_list_uom_dependant": price_list_uom_dependant,
Maricae8bc9122021-04-19 11:05:21 +05301122 "plc_conversion_rate": plc_conversion_rate or 1
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301123 })
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +05301124
1125@frappe.whitelist()
1126def get_default_bom(item_code=None):
1127 if item_code:
1128 bom = frappe.db.get_value("BOM", {"docstatus": 1, "is_default": 1, "is_active": 1, "item": item_code})
1129 if bom:
1130 return bom
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301131
Deepesh Garg15ff6a52020-02-18 12:28:41 +05301132@frappe.whitelist()
Manas Solanki087a2252018-05-04 16:02:38 +05301133def get_valuation_rate(item_code, company, warehouse=None):
Manas Solankib16a4ec2018-05-04 16:49:33 +05301134 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +05301135 item_group = get_item_group_defaults(item_code, company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001136 brand = get_brand_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +05301137 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +05301138 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +05301139 if not warehouse:
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001140 warehouse = item.get("default_warehouse") or item_group.get("default_warehouse") or brand.get("default_warehouse")
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301141
1142 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Saurabhbd01a812016-03-07 14:32:23 +05301143 ["valuation_rate"], as_dict=True) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301144
Manas Solankie3910fb2018-05-16 15:50:17 +05301145 elif not item.get("is_stock_item"):
Nabin Haitfe876c02017-03-06 16:32:57 +05301146 valuation_rate =frappe.db.sql("""select sum(base_net_amount) / sum(qty*conversion_factor)
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301147 from `tabPurchase Invoice Item`
Saurabhbd01a812016-03-07 14:32:23 +05301148 where item_code = %s and docstatus=1""", item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301149
Saurabhbd01a812016-03-07 14:32:23 +05301150 if valuation_rate:
1151 return {"valuation_rate": valuation_rate[0][0] or 0.0}
1152 else:
1153 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301154
Saurabh2d7af632016-02-26 11:09:20 +05301155def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +05301156 if out.valuation_rate:
1157 out.update({
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301158 "gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)
Saurabh5ada14b2016-02-26 18:02:55 +05301159 })
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301160
Saurabhd3135532016-02-25 18:59:20 +05301161 return out
mbauskar6f603392016-01-21 16:10:22 +05301162
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301163@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301164def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +05301165 serial_no = None
Achilles Rasquinha56b2e122018-02-13 14:42:40 +05301166 if isinstance(args, string_types):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301167 args = json.loads(args)
1168 args = frappe._dict(args)
Rohit Waghchauredc981dc2017-04-03 14:17:08 +05301169 if args.get('doctype') == 'Sales Invoice' and not args.get('update_stock'):
1170 return ""
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301171 if args.get('warehouse') and args.get('stock_qty') and args.get('item_code'):
Shreyaa20157a2018-04-13 12:03:42 +05301172 has_serial_no = frappe.get_value('Item', {'item_code': args.item_code}, "has_serial_no")
Shreyaa20157a2018-04-13 12:03:42 +05301173 if args.get('batch_no') and has_serial_no == 1:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301174 return get_serial_no_batchwise(args, sales_order)
Shreyaa20157a2018-04-13 12:03:42 +05301175 elif has_serial_no == 1:
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301176 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 +05301177 args = process_args(args)
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301178 serial_no = get_serial_nos_by_fifo(args, sales_order)
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +05301179
1180 if not serial_no and serial_nos:
1181 # For POS
1182 serial_no = serial_nos
1183
1184 return serial_no
Manas Solankie5e87f72018-05-28 20:07:08 +05301185
1186
1187def update_party_blanket_order(args, out):
ronelvcabrera370cdc02019-12-04 18:37:11 +08001188 if out["against_blanket_order"]:
1189 blanket_order_details = get_blanket_order_details(args)
1190 if blanket_order_details:
1191 out.update(blanket_order_details)
Manas Solankie5e87f72018-05-28 20:07:08 +05301192
1193@frappe.whitelist()
1194def get_blanket_order_details(args):
1195 if isinstance(args, string_types):
1196 args = frappe._dict(json.loads(args))
1197
1198 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +05301199 condition = ''
Manas Solankie5e87f72018-05-28 20:07:08 +05301200 if args.item_code:
1201 if args.customer and args.doctype == "Sales Order":
Nabin Hait2737b082018-06-14 18:07:22 +05301202 condition = ' and bo.customer=%(customer)s'
Manas Solankie5e87f72018-05-28 20:07:08 +05301203 elif args.supplier and args.doctype == "Purchase Order":
Nabin Hait2737b082018-06-14 18:07:22 +05301204 condition = ' and bo.supplier=%(supplier)s'
Manas Solankie5e87f72018-05-28 20:07:08 +05301205 if args.blanket_order:
Nabin Hait2737b082018-06-14 18:07:22 +05301206 condition += ' and bo.name =%(blanket_order)s'
1207 if args.transaction_date:
1208 condition += ' and bo.to_date>=%(transaction_date)s'
1209
Manas Solankie5e87f72018-05-28 20:07:08 +05301210 blanket_order_details = frappe.db.sql('''
1211 select boi.rate as blanket_order_rate, bo.name as blanket_order
1212 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
Nabin Hait2737b082018-06-14 18:07:22 +05301213 where bo.company=%(company)s and boi.item_code=%(item_code)s
1214 and bo.docstatus=1 and bo.name = boi.parent {0}
1215 '''.format(condition), args, as_dict=True)
1216
Manas Solankie5e87f72018-05-28 20:07:08 +05301217 blanket_order_details = blanket_order_details[0] if blanket_order_details else ''
1218 return blanket_order_details
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301219
1220def get_so_reservation_for_item(args):
1221 reserved_so = None
1222 if args.get('against_sales_order'):
1223 if get_reserved_qty_for_so(args.get('against_sales_order'), args.get('item_code')):
1224 reserved_so = args.get('against_sales_order')
1225 elif args.get('against_sales_invoice'):
1226 sales_order = frappe.db.sql("""select sales_order from `tabSales Invoice Item` where
1227 parent=%s and item_code=%s""", (args.get('against_sales_invoice'), args.get('item_code')))
1228 if sales_order and sales_order[0]:
1229 if get_reserved_qty_for_so(sales_order[0][0], args.get('item_code')):
1230 reserved_so = sales_order[0]
1231 elif args.get("sales_order"):
1232 if get_reserved_qty_for_so(args.get('sales_order'), args.get('item_code')):
1233 reserved_so = args.get('sales_order')
1234 return reserved_so
1235
1236def get_reserved_qty_for_so(sales_order, item_code):
1237 reserved_qty = frappe.db.sql("""select sum(qty) from `tabSales Order Item`
1238 where parent=%s and item_code=%s and ensure_delivery_based_on_produced_serial_no=1
1239 """, (sales_order, item_code))
1240 if reserved_qty and reserved_qty[0][0]:
1241 return reserved_qty[0][0]
1242 else:
1243 return 0