blob: a8eb777342f277fb636fb766f6c808bcc375f40c [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
Chillar Anand915b3432021-09-02 16:44:59 +05304
5import json
6
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05307import frappe
8from frappe import _, throw
Ankush Menat1e976642022-02-15 10:57:06 +05309from frappe.model import child_table_fields, default_fields
Rushabh Mehta66e08e32014-09-29 12:17:03 +053010from frappe.model.meta import get_field_precision
Rohit Waghchaure648efca2023-03-28 12:16:27 +053011from frappe.query_builder.functions import IfNull, Sum
Chillar Anand915b3432021-09-02 16:44:59 +053012from frappe.utils import add_days, add_months, cint, cstr, flt, getdate
Nabin Hait98c2a052014-05-05 18:41:41 +053013
Chillar Anand915b3432021-09-02 16:44:59 +053014from erpnext import get_company_currency
15from erpnext.accounts.doctype.pricing_rule.pricing_rule import (
16 get_pricing_rule_for_item,
17 set_transaction_type,
18)
19from erpnext.setup.doctype.brand.brand import get_brand_defaults
20from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults
21from erpnext.setup.utils import get_exchange_rate
Chillar Anand915b3432021-09-02 16:44:59 +053022from erpnext.stock.doctype.item.item import get_item_defaults, get_uom_conv_factor
23from erpnext.stock.doctype.item_manufacturer.item_manufacturer import get_item_manufacturer_part_no
24from erpnext.stock.doctype.price_list.price_list import get_price_list_details
tundebabzyacccdb32017-11-23 08:35:15 +010025
Ankush Menat494bd9e2022-03-28 18:52:46 +053026sales_doctypes = ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice", "POS Invoice"]
27purchase_doctypes = [
28 "Material Request",
29 "Supplier Quotation",
30 "Purchase Order",
31 "Purchase Receipt",
32 "Purchase Invoice",
33]
34
Nabin Hait0d1ccc32019-02-14 18:30:10 +053035
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053036@frappe.whitelist()
Deepesh Garga7051cb2023-04-14 09:59:42 +053037def get_item_details(args, doc=None, for_validate=False, overwrite_warehouse=True):
Nabin Hait436f5262014-02-10 14:47:54 +053038 """
Ankush Menat494bd9e2022-03-28 18:52:46 +053039 args = {
40 "item_code": "",
41 "warehouse": None,
42 "customer": "",
43 "conversion_rate": 1.0,
44 "selling_price_list": None,
45 "price_list_currency": None,
46 "plc_conversion_rate": 1.0,
47 "doctype": "",
48 "name": "",
49 "supplier": None,
50 "transaction_date": None,
51 "conversion_rate": 1.0,
52 "buying_price_list": None,
Sagar Sharma409df262022-04-19 14:57:31 +053053 "is_subcontracted": 0/1,
Ankush Menat494bd9e2022-03-28 18:52:46 +053054 "ignore_pricing_rule": 0/1
55 "project": ""
56 "set_warehouse": ""
57 }
Nabin Hait436f5262014-02-10 14:47:54 +053058 """
Suraj Shetty182f4de2019-08-16 08:16:22 +053059
Anand Doshidffec8f2014-07-01 17:45:15 +053060 args = process_args(args)
marination392f3232020-07-14 17:03:17 +053061 for_validate = process_string_args(for_validate)
62 overwrite_warehouse = process_string_args(overwrite_warehouse)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053063 item = frappe.get_cached_doc("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053064 validate_item_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053065
Ankush Menat8fe5feb2021-11-04 19:48:32 +053066 if isinstance(doc, str):
Deepesh Gargef0d26c2020-01-06 15:34:15 +053067 doc = json.loads(doc)
68
Deepesh Gargef0d26c2020-01-06 15:34:15 +053069 if doc:
Sagar Vora1a3997a2022-06-16 17:03:47 +000070 args["transaction_date"] = doc.get("transaction_date") or doc.get("posting_date")
Deepesh Gargef0d26c2020-01-06 15:34:15 +053071
Sagar Vora1a3997a2022-06-16 17:03:47 +000072 if doc.get("doctype") == "Purchase Invoice":
73 args["bill_date"] = doc.get("bill_date")
74
Deepesh Garga7051cb2023-04-14 09:59:42 +053075 out = get_basic_details(args, item, overwrite_warehouse)
Deepesh Garg4c61ee32023-04-02 09:35:27 +053076
Saif Ur Rehman67786682018-12-27 02:11:07 +050077 get_item_tax_template(args, item, out)
Ankush Menat494bd9e2022-03-28 18:52:46 +053078 out["item_tax_rate"] = get_item_tax_map(
79 args.company,
80 args.get("item_tax_template")
81 if out.get("item_tax_template") is None
82 else out.get("item_tax_template"),
83 as_json=True,
84 )
Saif Ur Rehman67786682018-12-27 02:11:07 +050085
Rushabh Mehta708e47a2018-08-08 16:37:31 +053086 get_party_item_code(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053087
Rushabh Mehta708e47a2018-08-08 16:37:31 +053088 set_valuation_rate(out, args)
Anand Doshibd67e872014-04-11 16:51:27 +053089
Manas Solankie5e87f72018-05-28 20:07:08 +053090 update_party_blanket_order(args, out)
91
HENRY Florian231fe412023-02-13 16:26:05 +010092 # Never try to find a customer price if customer is set in these Doctype
93 current_customer = args.customer
94 if args.get("doctype") in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]:
95 args.customer = None
96
Ankush16d4de52021-08-09 10:41:24 +053097 out.update(get_price_list_rate(args, item))
Nabin Hait436f5262014-02-10 14:47:54 +053098
HENRY Florian231fe412023-02-13 16:26:05 +010099 args.customer = current_customer
100
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530101 if args.customer and cint(args.is_pos):
Anuja Pawarf132ed42021-05-07 12:11:09 +0530102 out.update(get_pos_profile_item_details(args.company, args, update_data=True))
Rushabh Mehta6b537922017-03-14 16:59:11 +0530103
Ankush Menat494bd9e2022-03-28 18:52:46 +0530104 if (
105 args.get("doctype") == "Material Request"
106 and args.get("material_request_type") == "Material Transfer"
107 ):
Nabin Haitda17f9c2020-05-01 18:16:25 +0530108 out.update(get_bin_details(args.item_code, args.get("from_warehouse")))
109
110 elif out.get("warehouse"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530111 if doc and doc.get("doctype") == "Purchase Order":
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530112 # calculate company_total_stock only for po
s-aga-rc716dcc2022-12-29 12:34:18 +0530113 bin_details = get_bin_details(
114 args.item_code, out.warehouse, args.company, include_child_warehouses=True
115 )
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530116 else:
s-aga-rc716dcc2022-12-29 12:34:18 +0530117 bin_details = get_bin_details(args.item_code, out.warehouse, include_child_warehouses=True)
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530118
119 out.update(bin_details)
Anand Doshibd67e872014-04-11 16:51:27 +0530120
Nabin Haita3dd72a2014-05-28 12:49:20 +0530121 # update args with out, if key or value not exists
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530122 for key, value in out.items():
Nabin Haita3dd72a2014-05-28 12:49:20 +0530123 if args.get(key) is None:
124 args[key] = value
125
Deepesh Garg6192af52022-12-08 18:04:40 +0530126 data = get_pricing_rule_for_item(args, doc=doc, for_validate=for_validate)
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530127
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530128 out.update(data)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530129
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530130 if args.transaction_date and item.lead_time_days:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530131 out.schedule_date = out.lead_time_date = add_days(args.transaction_date, item.lead_time_days)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530132
Sagar Sharma409df262022-04-19 14:57:31 +0530133 if args.get("is_subcontracted"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530134 out.bom = args.get("bom") or get_default_bom(args.item_code)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530135
136 get_gross_profit(out)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530137 if args.doctype == "Material Request":
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530138 out.rate = args.rate or out.price_list_rate
Rohit Waghchaure1bc53a32021-03-31 15:28:26 +0530139 out.amount = flt(args.qty) * flt(out.rate)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530140
Ankush Menat1e976642022-02-15 10:57:06 +0530141 out = remove_standard_fields(out)
Deepesh Garga7051cb2023-04-14 09:59:42 +0530142 return out
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530143
Ankush Menat494bd9e2022-03-28 18:52:46 +0530144
Ankush Menat1e976642022-02-15 10:57:06 +0530145def remove_standard_fields(details):
146 for key in child_table_fields + default_fields:
147 details.pop(key, None)
148 return details
149
150
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530151def set_valuation_rate(out, args):
Nabin Hait50238c32018-08-08 18:43:04 +0530152 if frappe.db.exists("Product Bundle", args.item_code, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530153 valuation_rate = 0.0
154 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530155
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530156 for bundle_item in bundled_items.items:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530157 valuation_rate += flt(
158 get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get(
159 "valuation_rate"
160 )
161 * bundle_item.qty
162 )
Anand Doshi70f57eb2015-11-27 14:37:40 +0530163
Ankush Menat494bd9e2022-03-28 18:52:46 +0530164 out.update({"valuation_rate": valuation_rate})
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530165
166 else:
167 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
168
Nabin Hait436f5262014-02-10 14:47:54 +0530169
Anand Doshidffec8f2014-07-01 17:45:15 +0530170def process_args(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530171 if isinstance(args, str):
Anand Doshidffec8f2014-07-01 17:45:15 +0530172 args = json.loads(args)
173
174 args = frappe._dict(args)
175
Anand Doshidffec8f2014-07-01 17:45:15 +0530176 if not args.get("price_list"):
177 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
178
Devin Slauenwhite55276f12022-05-25 00:05:22 -0400179 if not args.item_code and args.barcode:
Anand Doshidffec8f2014-07-01 17:45:15 +0530180 args.item_code = get_item_code(barcode=args.barcode)
181 elif not args.item_code and args.serial_no:
182 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530183
mbauskar6f603392016-01-21 16:10:22 +0530184 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530185 return args
186
Ankush Menat494bd9e2022-03-28 18:52:46 +0530187
marination392f3232020-07-14 17:03:17 +0530188def process_string_args(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530189 if isinstance(args, str):
marination392f3232020-07-14 17:03:17 +0530190 args = json.loads(args)
191 return args
tundebabzyacccdb32017-11-23 08:35:15 +0100192
Ankush Menat494bd9e2022-03-28 18:52:46 +0530193
Nabin Hait436f5262014-02-10 14:47:54 +0530194def get_item_code(barcode=None, serial_no=None):
195 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100196 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530197 if not item_code:
198 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530199 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530200 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530201 if not item_code:
202 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530203
Nabin Hait436f5262014-02-10 14:47:54 +0530204 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530205
tundebabzyacccdb32017-11-23 08:35:15 +0100206
Nabin Hait436f5262014-02-10 14:47:54 +0530207def validate_item_details(args, item):
208 if not args.company:
209 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530210
Nabin Hait436f5262014-02-10 14:47:54 +0530211 from erpnext.stock.doctype.item.item import validate_end_of_life
Ankush Menat494bd9e2022-03-28 18:52:46 +0530212
Anand Doshi21e09a22015-10-29 12:21:41 +0530213 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530214
Rohit Waghchaure2c83fff2023-01-18 23:21:29 +0530215 if cint(item.has_variants):
216 msg = f"Item {item.name} is a template, please select one of its variants"
217
218 throw(_(msg), title=_("Template Item Selected"))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530219
tundebabzyacccdb32017-11-23 08:35:15 +0100220 elif args.transaction_type == "buying" and args.doctype != "Material Request":
s-aga-r6d89b2f2022-06-18 15:46:59 +0530221 if args.get("is_subcontracted"):
222 if args.get("is_old_subcontracting_flow"):
223 if item.is_sub_contracted_item != 1:
224 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
225 else:
226 if item.is_stock_item:
227 throw(_("Item {0} must be a Non-Stock Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530228
tundebabzyacccdb32017-11-23 08:35:15 +0100229
Suraj Shetty182f4de2019-08-16 08:16:22 +0530230def get_basic_details(args, item, overwrite_warehouse=True):
tundebabzyacccdb32017-11-23 08:35:15 +0100231 """
232 :param args: {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530233 "item_code": "",
234 "warehouse": None,
235 "customer": "",
236 "conversion_rate": 1.0,
237 "selling_price_list": None,
238 "price_list_currency": None,
239 "price_list_uom_dependant": None,
240 "plc_conversion_rate": 1.0,
241 "doctype": "",
242 "name": "",
243 "supplier": None,
244 "transaction_date": None,
245 "conversion_rate": 1.0,
246 "buying_price_list": None,
Sagar Sharma409df262022-04-19 14:57:31 +0530247 "is_subcontracted": 0/1,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530248 "ignore_pricing_rule": 0/1
249 "project": "",
250 barcode: "",
251 serial_no: "",
252 currency: "",
253 update_stock: "",
254 price_list: "",
255 company: "",
256 order_type: "",
257 is_pos: "",
258 project: "",
259 qty: "",
260 stock_qty: "",
261 conversion_factor: "",
262 against_blanket_order: 0/1
263 }
tundebabzyacccdb32017-11-23 08:35:15 +0100264 :param item: `item_code` of Item object
265 :return: frappe._dict
266 """
267
Rushabh Mehta1a763742014-10-03 16:36:43 +0530268 if not item:
269 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530270
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530271 if item.variant_of:
272 item.update_template_tables()
273
Manas Solankib16a4ec2018-05-04 16:49:33 +0530274 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530275 item_group_defaults = get_item_group_defaults(item.name, args.company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500276 brand_defaults = get_brand_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530277
Ankush Menat494bd9e2022-03-28 18:52:46 +0530278 defaults = frappe._dict(
279 {
280 "item_defaults": item_defaults,
281 "item_group_defaults": item_group_defaults,
282 "brand_defaults": brand_defaults,
283 }
284 )
marinatione05013e2020-04-06 22:13:13 +0530285
Saqib438e0432020-04-03 10:02:56 +0530286 warehouse = get_item_warehouse(item, args, overwrite_warehouse, defaults)
Nabin Hait36028bf2014-02-12 19:09:28 +0530287
Ankush Menat494bd9e2022-03-28 18:52:46 +0530288 if args.get("doctype") == "Material Request" and not args.get("material_request_type"):
289 args["material_request_type"] = frappe.db.get_value(
290 "Material Request", args.get("name"), "material_request_type", cache=True
291 )
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530292
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530293 expense_account = None
294
Ankush Menat494bd9e2022-03-28 18:52:46 +0530295 if args.get("doctype") == "Purchase Invoice" and item.is_fixed_asset:
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530296 from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530297
Ankush Menat494bd9e2022-03-28 18:52:46 +0530298 expense_account = get_asset_category_account(
299 fieldname="fixed_asset_account", item=args.item_code, company=args.company
300 )
301
302 # Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
303 if not args.get("uom"):
304 if args.get("doctype") in sales_doctypes:
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530305 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
Ankush Menat494bd9e2022-03-28 18:52:46 +0530306 elif (args.get("doctype") in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]) or (
307 args.get("doctype") == "Material Request" and args.get("material_request_type") == "Purchase"
308 ):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530309 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
310 else:
311 args.uom = item.stock_uom
312
Sagar Vora57038c32022-11-09 18:56:09 +0530313 # Set stock UOM in args, so that it can be used while fetching item price
314 args.stock_uom = item.stock_uom
315
Ankush Menat494bd9e2022-03-28 18:52:46 +0530316 if args.get("batch_no") and item.name != frappe.get_cached_value(
317 "Batch", args.get("batch_no"), "item"
318 ):
319 args["batch_no"] = ""
Rohit Waghchauree1f07042021-08-23 14:27:55 +0530320
Ankush Menat494bd9e2022-03-28 18:52:46 +0530321 out = frappe._dict(
322 {
323 "item_code": item.name,
324 "item_name": item.item_name,
325 "description": cstr(item.description).strip(),
326 "image": cstr(item.image).strip(),
327 "warehouse": warehouse,
328 "income_account": get_default_income_account(
329 args, item_defaults, item_group_defaults, brand_defaults
330 ),
331 "expense_account": expense_account
332 or get_default_expense_account(args, item_defaults, item_group_defaults, brand_defaults),
David Arnold1612d7b2023-10-26 14:03:22 +0200333 "discount_account": get_default_discount_account(
334 args, item_defaults, item_group_defaults, brand_defaults
335 ),
336 "provisional_expense_account": get_provisional_account(
337 args, item_defaults, item_group_defaults, brand_defaults
338 ),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530339 "cost_center": get_default_cost_center(
340 args, item_defaults, item_group_defaults, brand_defaults
341 ),
342 "has_serial_no": item.has_serial_no,
343 "has_batch_no": item.has_batch_no,
344 "batch_no": args.get("batch_no"),
345 "uom": args.uom,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530346 "stock_uom": item.stock_uom,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530347 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
348 "qty": flt(args.qty) or 1.0,
349 "stock_qty": flt(args.qty) or 1.0,
350 "price_list_rate": 0.0,
351 "base_price_list_rate": 0.0,
352 "rate": 0.0,
353 "base_rate": 0.0,
354 "amount": 0.0,
355 "base_amount": 0.0,
356 "net_rate": 0.0,
357 "net_amount": 0.0,
358 "discount_percentage": 0.0,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530359 "discount_amount": flt(args.discount_amount) or 0.0,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530360 "supplier": get_default_supplier(args, item_defaults, item_group_defaults, brand_defaults),
361 "update_stock": args.get("update_stock")
362 if args.get("doctype") in ["Sales Invoice", "Purchase Invoice"]
363 else 0,
364 "delivered_by_supplier": item.delivered_by_supplier
365 if args.get("doctype") in ["Sales Order", "Sales Invoice"]
366 else 0,
367 "is_fixed_asset": item.is_fixed_asset,
368 "last_purchase_rate": item.last_purchase_rate
369 if args.get("doctype") in ["Purchase Order"]
370 else 0,
371 "transaction_date": args.get("transaction_date"),
372 "against_blanket_order": args.get("against_blanket_order"),
373 "bom_no": item.get("default_bom"),
374 "weight_per_unit": args.get("weight_per_unit") or item.get("weight_per_unit"),
375 "weight_uom": args.get("weight_uom") or item.get("weight_uom"),
376 "grant_commission": item.get("grant_commission"),
377 }
378 )
Anand Doshibd67e872014-04-11 16:51:27 +0530379
Zlash65627be1d2019-01-15 14:16:32 +0530380 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zlash6580f5cb02018-08-29 11:39:08 +0530381 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530382
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530383 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530384 if item.stock_uom == args.uom:
385 out.conversion_factor = 1.0
386 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530387 out.conversion_factor = args.conversion_factor or get_conversion_factor(item.name, args.uom).get(
388 "conversion_factor"
389 )
mbauskar287fe812017-04-10 19:15:57 +0530390
391 args.conversion_factor = out.conversion_factor
392 out.stock_qty = out.qty * out.conversion_factor
Saqib Ansari3713ae72022-02-14 11:33:34 +0530393 args.stock_qty = out.stock_qty
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530394
Shreya Shah44fa9a62018-01-08 14:58:20 +0530395 # calculate last purchase rate
Rohit Waghchaureec171fc2023-01-09 18:49:48 +0530396 if args.get("doctype") in purchase_doctypes and not frappe.db.get_single_value(
397 "Buying Settings", "disable_last_purchase_rate"
398 ):
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530399 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +0530400
401 out.last_purchase_rate = item_last_purchase_rate(
402 args.name, args.conversion_rate, item.name, out.conversion_factor
403 )
Shreya Shah44fa9a62018-01-08 14:58:20 +0530404
Nabin Haitb09ed412015-02-17 10:33:58 +0530405 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530406 for d in [
407 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530408 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530409 ["Cost Center", "cost_center", "cost_center"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530410 ["Warehouse", "warehouse", ""],
411 ]:
412 if not out[d[1]]:
413 out[d[1]] = frappe.get_cached_value("Company", args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530414
Ankush Menat64905182022-03-09 15:37:14 +0530415 for fieldname in ("item_name", "item_group", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530416 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530417
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530418 if args.get("manufacturer"):
419 part_no = get_item_manufacturer_part_no(args.get("item_code"), args.get("manufacturer"))
420 if part_no:
421 out["manufacturer_part_no"] = part_no
422 else:
423 out["manufacturer_part_no"] = None
424 out["manufacturer"] = None
marination3e7a8ab2020-04-07 21:00:57 +0530425 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530426 data = frappe.get_value(
427 "Item", item.name, ["default_item_manufacturer", "default_manufacturer_part_no"], as_dict=1
428 )
rohitwaghchaurebe16e5c2020-05-01 10:50:17 +0530429
430 if data:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530431 out.update(
432 {
433 "manufacturer": data.default_item_manufacturer,
434 "manufacturer_part_no": data.default_manufacturer_part_no,
435 }
436 )
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530437
Ankush Menat494bd9e2022-03-28 18:52:46 +0530438 child_doctype = args.doctype + " Item"
Nabin Hait34c551d2019-07-03 10:34:31 +0530439 meta = frappe.get_meta(child_doctype)
440 if meta.get_field("barcode"):
441 update_barcode_value(out)
442
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530443 if out.get("weight_per_unit"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530444 out["total_weight"] = out.weight_per_unit * out.stock_qty
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530445
Nabin Hait436f5262014-02-10 14:47:54 +0530446 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530447
Ankush Menat494bd9e2022-03-28 18:52:46 +0530448
Chillar Anand772d4752021-10-06 22:28:48 +0530449def get_item_warehouse(item, args, overwrite_warehouse, defaults=None):
Saqib438e0432020-04-03 10:02:56 +0530450 if not defaults:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530451 defaults = frappe._dict(
452 {
453 "item_defaults": get_item_defaults(item.name, args.company),
454 "item_group_defaults": get_item_group_defaults(item.name, args.company),
455 "brand_defaults": get_brand_defaults(item.name, args.company),
456 }
457 )
Saqib438e0432020-04-03 10:02:56 +0530458
459 if overwrite_warehouse or not args.warehouse:
460 warehouse = (
Ankush Menat494bd9e2022-03-28 18:52:46 +0530461 args.get("set_warehouse")
462 or defaults.item_defaults.get("default_warehouse")
463 or defaults.item_group_defaults.get("default_warehouse")
464 or defaults.brand_defaults.get("default_warehouse")
465 or args.get("warehouse")
Saqib438e0432020-04-03 10:02:56 +0530466 )
467
468 if not warehouse:
469 defaults = frappe.defaults.get_defaults() or {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530470 warehouse_exists = frappe.db.exists(
471 "Warehouse", {"name": defaults.default_warehouse, "company": args.company}
472 )
Saqib438e0432020-04-03 10:02:56 +0530473 if defaults.get("default_warehouse") and warehouse_exists:
474 warehouse = defaults.default_warehouse
475
476 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530477 warehouse = args.get("warehouse")
marinatione05013e2020-04-06 22:13:13 +0530478
Marica3b1be2b2020-10-22 17:04:31 +0530479 if not warehouse:
480 default_warehouse = frappe.db.get_single_value("Stock Settings", "default_warehouse")
481 if frappe.db.get_value("Warehouse", default_warehouse, "company") == args.company:
482 return default_warehouse
483
Saqib438e0432020-04-03 10:02:56 +0530484 return warehouse
485
Ankush Menat494bd9e2022-03-28 18:52:46 +0530486
Nabin Hait34c551d2019-07-03 10:34:31 +0530487def update_barcode_value(out):
Nabin Hait34c551d2019-07-03 10:34:31 +0530488 barcode_data = get_barcode_data([out])
489
490 # If item has one barcode then update the value of the barcode field
491 if barcode_data and len(barcode_data.get(out.item_code)) == 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530492 out["barcode"] = barcode_data.get(out.item_code)[0]
493
Nabin Hait34c551d2019-07-03 10:34:31 +0530494
Saqiba6f98d42020-07-23 18:51:26 +0530495def get_barcode_data(items_list):
496 # get itemwise batch no data
497 # exmaple: {'LED-GRE': [Batch001, Batch002]}
498 # where LED-GRE is item code, SN0001 is serial no and Pune is warehouse
499
500 itemwise_barcode = {}
501 for item in items_list:
s-aga-r6b144ba2023-02-18 12:18:41 +0530502 barcodes = frappe.db.get_all(
503 "Item Barcode", filters={"parent": item.item_code}, fields="barcode"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530504 )
Saqiba6f98d42020-07-23 18:51:26 +0530505
506 for barcode in barcodes:
507 if item.item_code not in itemwise_barcode:
508 itemwise_barcode.setdefault(item.item_code, [])
509 itemwise_barcode[item.item_code].append(barcode.get("barcode"))
510
511 return itemwise_barcode
512
Ankush Menat494bd9e2022-03-28 18:52:46 +0530513
Zlash6580f5cb02018-08-29 11:39:08 +0530514@frappe.whitelist()
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530515def get_item_tax_info(company, tax_category, item_codes, item_rates=None, item_tax_templates=None):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500516 out = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530517
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530518 if item_tax_templates is None:
Deepesh Gargcae42b482021-06-25 13:34:00 +0530519 item_tax_templates = {}
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +0530520
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530521 if item_rates is None:
522 item_rates = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530523
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530524 if isinstance(item_codes, (str,)):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500525 item_codes = json.loads(item_codes)
526
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530527 if isinstance(item_rates, (str,)):
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530528 item_rates = json.loads(item_rates)
529
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530530 if isinstance(item_tax_templates, (str,)):
Deepesh Garg94d46042021-06-23 20:56:27 +0530531 item_tax_templates = json.loads(item_tax_templates)
532
Saif Ur Rehman67786682018-12-27 02:11:07 +0500533 for item_code in item_codes:
Deepesh Garg94d46042021-06-23 20:56:27 +0530534 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 +0500535 continue
Deepesh Garg94d46042021-06-23 20:56:27 +0530536
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530537 out[item_code[1]] = {}
538 item = frappe.get_cached_doc("Item", item_code[0])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530539 args = {
540 "company": company,
541 "tax_category": tax_category,
542 "net_rate": item_rates.get(item_code[1]),
543 }
Deepesh Garg269962a2021-06-23 22:52:51 +0530544
545 if item_tax_templates:
546 args.update({"item_tax_template": item_tax_templates.get(item_code[1])})
Deepesh Garg94d46042021-06-23 20:56:27 +0530547
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530548 get_item_tax_template(args, item, out[item_code[1]])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530549 out[item_code[1]]["item_tax_rate"] = get_item_tax_map(
550 company, out[item_code[1]].get("item_tax_template"), as_json=True
551 )
Saif Ur Rehman67786682018-12-27 02:11:07 +0500552
553 return out
554
Ankush Menat494bd9e2022-03-28 18:52:46 +0530555
Saif Ur Rehman67786682018-12-27 02:11:07 +0500556def get_item_tax_template(args, item, out):
557 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530558 args = {
559 "tax_category": None
560 "item_tax_template": None
561 }
Saif Ur Rehman67786682018-12-27 02:11:07 +0500562 """
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530563 item_tax_template = None
564 if item.taxes:
565 item_tax_template = _get_item_tax_template(args, item.taxes, out)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500566
567 if not item_tax_template:
568 item_group = item.item_group
569 while item_group and not item_tax_template:
570 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
571 item_tax_template = _get_item_tax_template(args, item_group_doc.taxes, out)
572 item_group = item_group_doc.parent_item_group
573
Ankush Menat494bd9e2022-03-28 18:52:46 +0530574
18alantom308905b2021-05-03 23:34:34 +0530575def _get_item_tax_template(args, taxes, out=None, for_validate=False):
576 if out is None:
577 out = {}
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530578 taxes_with_validity = []
579 taxes_with_no_validity = []
580
581 for tax in taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530582 tax_company = frappe.get_cached_value("Item Tax Template", tax.item_tax_template, "company")
583 if tax_company == args["company"]:
584 if tax.valid_from or tax.maximum_net_rate:
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530585 # In purchase Invoice first preference will be given to supplier invoice date
586 # if supplier date is not present then posting date
Sagar Vora1a3997a2022-06-16 17:03:47 +0000587 validation_date = args.get("bill_date") or args.get("transaction_date")
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530588
Ankush Menat494bd9e2022-03-28 18:52:46 +0530589 if getdate(tax.valid_from) <= getdate(validation_date) and is_within_valid_range(args, tax):
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530590 taxes_with_validity.append(tax)
591 else:
mohammadahmad1990e39649b2020-06-18 11:42:53 +0500592 taxes_with_no_validity.append(tax)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530593
594 if taxes_with_validity:
Deepesh Garg6f6928f2023-04-09 09:38:13 +0530595 taxes = sorted(
596 taxes_with_validity, key=lambda i: i.valid_from or tax.maximum_net_rate, reverse=True
597 )
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530598 else:
599 taxes = taxes_with_no_validity
600
601 if for_validate:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530602 return [
603 tax.item_tax_template
604 for tax in taxes
605 if (
606 cstr(tax.tax_category) == cstr(args.get("tax_category"))
607 and (tax.item_tax_template not in taxes)
608 )
609 ]
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530610
611 # all templates have validity and no template is valid
612 if not taxes_with_validity and (not taxes_with_no_validity):
Gursheen Kaur Anandb0d440c2023-10-21 17:58:43 +0530613 out["item_tax_template"] = ""
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530614 return None
615
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530616 # do not change if already a valid template
Ankush Menat494bd9e2022-03-28 18:52:46 +0530617 if args.get("item_tax_template") in {t.item_tax_template for t in taxes}:
618 out["item_tax_template"] = args.get("item_tax_template")
619 return args.get("item_tax_template")
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530620
Saif Ur Rehman67786682018-12-27 02:11:07 +0500621 for tax in taxes:
622 if cstr(tax.tax_category) == cstr(args.get("tax_category")):
623 out["item_tax_template"] = tax.item_tax_template
624 return tax.item_tax_template
625 return None
626
Ankush Menat494bd9e2022-03-28 18:52:46 +0530627
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530628def is_within_valid_range(args, tax):
629 if not flt(tax.maximum_net_rate):
630 # No range specified, just ignore
631 return True
Ankush Menat494bd9e2022-03-28 18:52:46 +0530632 elif flt(tax.minimum_net_rate) <= flt(args.get("net_rate")) <= flt(tax.maximum_net_rate):
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530633 return True
634
635 return False
636
Ankush Menat494bd9e2022-03-28 18:52:46 +0530637
Saif Ur Rehman67786682018-12-27 02:11:07 +0500638@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500639def get_item_tax_map(company, item_tax_template, as_json=True):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500640 item_tax_map = {}
641 if item_tax_template:
642 template = frappe.get_cached_doc("Item Tax Template", item_tax_template)
643 for d in template.taxes:
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500644 if frappe.get_cached_value("Account", d.tax_type, "company") == company:
645 item_tax_map[d.tax_type] = d.tax_rate
Saif Ur Rehman67786682018-12-27 02:11:07 +0500646
647 return json.dumps(item_tax_map) if as_json else item_tax_map
648
Ankush Menat494bd9e2022-03-28 18:52:46 +0530649
Saif Ur Rehman67786682018-12-27 02:11:07 +0500650@frappe.whitelist()
Zlash6580f5cb02018-08-29 11:39:08 +0530651def calculate_service_end_date(args, item=None):
652 args = process_args(args)
653 if not item:
654 item = frappe.get_cached_doc("Item", args.item_code)
655
Zlash65627be1d2019-01-15 14:16:32 +0530656 doctype = args.get("parenttype") or args.get("doctype")
Zlash65a3dd7982019-01-15 14:36:11 +0530657 if doctype == "Sales Invoice":
658 enable_deferred = "enable_deferred_revenue"
659 no_of_months = "no_of_months"
660 account = "deferred_revenue_account"
661 else:
662 enable_deferred = "enable_deferred_expense"
663 no_of_months = "no_of_months_exp"
664 account = "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530665
Zlash6580f5cb02018-08-29 11:39:08 +0530666 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
Zarrare83ff382018-09-21 15:45:40 +0530667 service_end_date = add_months(service_start_date, item.get(no_of_months))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530668 deferred_detail = {"service_start_date": service_start_date, "service_end_date": service_end_date}
Zarrare83ff382018-09-21 15:45:40 +0530669 deferred_detail[enable_deferred] = item.get(enable_deferred)
670 deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)
Zlash6580f5cb02018-08-29 11:39:08 +0530671
672 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100673
Ankush Menat494bd9e2022-03-28 18:52:46 +0530674
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500675def get_default_income_account(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530676 return (
677 item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530678 or item_group.get("income_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500679 or brand.get("income_account")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530680 or args.income_account
681 )
682
Rushabh Mehta1a763742014-10-03 16:36:43 +0530683
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500684def get_default_expense_account(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530685 return (
686 item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530687 or item_group.get("expense_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500688 or brand.get("expense_account")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530689 or args.expense_account
690 )
691
Rushabh Mehta1a763742014-10-03 16:36:43 +0530692
David Arnold1612d7b2023-10-26 14:03:22 +0200693def get_provisional_account(args, item, item_group, brand):
694 return (
695 item.get("default_provisional_account")
696 or item_group.get("default_provisional_account")
697 or brand.get("default_provisional_account")
698 or args.default_provisional_account
699 )
Deepesh Garg3ce64172022-04-11 14:35:22 +0530700
701
David Arnold1612d7b2023-10-26 14:03:22 +0200702def get_default_discount_account(args, item, item_group, brand):
703 return (
704 item.get("default_discount_account")
705 or item_group.get("default_discount_account")
706 or brand.get("default_discount_account")
707 or args.discount_account
708 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530709
GangaManoj657e9b52021-07-06 16:51:12 +0530710
Zarrare83ff382018-09-21 15:45:40 +0530711def get_default_deferred_account(args, item, fieldname=None):
Zlash65627be1d2019-01-15 14:16:32 +0530712 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530713 return (
Gursheen Kaur Anand099468e2023-09-16 21:25:31 +0530714 frappe.get_cached_value(
715 "Item Default",
716 {"parent": args.item_code, "company": args.get("company")},
717 fieldname,
718 )
Zarrare83ff382018-09-21 15:45:40 +0530719 or args.get(fieldname)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530720 or frappe.get_cached_value("Company", args.company, "default_" + fieldname)
721 )
Manas Solanki03938482018-05-14 16:16:46 +0530722 else:
723 return None
724
Ankush Menat494bd9e2022-03-28 18:52:46 +0530725
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530726def get_default_cost_center(args, item=None, item_group=None, brand=None, company=None):
Nabin Hait50238c32018-08-08 18:43:04 +0530727 cost_center = None
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530728
729 if not company and args.get("company"):
730 company = args.get("company")
731
Ankush Menat494bd9e2022-03-28 18:52:46 +0530732 if args.get("project"):
Nabin Hait50238c32018-08-08 18:43:04 +0530733 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530734
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530735 if not cost_center and (item and item_group and brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530736 if args.get("customer"):
737 cost_center = (
738 item.get("selling_cost_center")
739 or item_group.get("selling_cost_center")
740 or brand.get("selling_cost_center")
741 )
Nabin Hait50238c32018-08-08 18:43:04 +0530742 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530743 cost_center = (
744 item.get("buying_cost_center")
745 or item_group.get("buying_cost_center")
746 or brand.get("buying_cost_center")
747 )
Rushabh Mehta49f97472018-08-30 18:50:48 +0530748
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530749 elif not cost_center and args.get("item_code") and company:
750 for method in ["get_item_defaults", "get_item_group_defaults", "get_brand_defaults"]:
751 path = "erpnext.stock.get_item_details.{0}".format(method)
752 data = frappe.get_attr(path)(args.get("item_code"), company)
753
754 if data and (data.selling_cost_center or data.buying_cost_center):
rohitwaghchaure14b009b2023-10-20 16:22:29 +0530755 if args.get("customer") and data.selling_cost_center:
756 return data.selling_cost_center
757
758 elif args.get("supplier") and data.buying_cost_center:
759 return data.buying_cost_center
760
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530761 return data.selling_cost_center or data.buying_cost_center
762
763 if not cost_center and args.get("cost_center"):
764 cost_center = args.get("cost_center")
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530765
Ankush Menat494bd9e2022-03-28 18:52:46 +0530766 if (
767 company
768 and cost_center
769 and frappe.get_cached_value("Cost Center", cost_center, "company") != company
770 ):
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530771 return None
772
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530773 if not cost_center and company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530774 cost_center = frappe.get_cached_value("Company", company, "cost_center")
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530775
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530776 return cost_center
Rushabh Mehta1a763742014-10-03 16:36:43 +0530777
Ankush Menat494bd9e2022-03-28 18:52:46 +0530778
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500779def get_default_supplier(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530780 return (
781 item.get("default_supplier")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500782 or item_group.get("default_supplier")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530783 or brand.get("default_supplier")
784 )
785
Shreya Shah3c9839f2018-07-17 18:01:44 +0530786
Ankush16d4de52021-08-09 10:41:24 +0530787def get_price_list_rate(args, item_doc, out=None):
788 if out is None:
789 out = frappe._dict()
790
Anand Doshi39a28912016-02-15 11:42:18 +0530791 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530792
Ankush Menat494bd9e2022-03-28 18:52:46 +0530793 if meta.get_field("currency") or args.get("currency"):
Maricae8bc9122021-04-19 11:05:21 +0530794 if not args.get("price_list_currency") or not args.get("plc_conversion_rate"):
795 # if currency and plc_conversion_rate exist then
796 # `get_price_list_currency_and_exchange_rate` has already been called
797 pl_details = get_price_list_currency_and_exchange_rate(args)
798 args.update(pl_details)
799
Nabin Hait06c8cf42019-05-16 19:17:02 +0530800 if meta.get_field("currency"):
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530801 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530802
Ankush16d4de52021-08-09 10:41:24 +0530803 price_list_rate = get_price_list_rate_for(args, item_doc.name)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530804
hiousi1516e292019-01-08 18:34:08 +0100805 # variant
Ankush16d4de52021-08-09 10:41:24 +0530806 if price_list_rate is None and item_doc.variant_of:
hiousi1516e292019-01-08 18:34:08 +0100807 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530808
809 # insert in database
Ankush16d4de52021-08-09 10:41:24 +0530810 if price_list_rate is None:
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530811 if args.price_list and args.rate:
812 insert_item_price(args)
Ankush16d4de52021-08-09 10:41:24 +0530813 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530814
Ankush Menat494bd9e2022-03-28 18:52:46 +0530815 out.price_list_rate = (
816 flt(price_list_rate) * flt(args.plc_conversion_rate) / flt(args.conversion_rate)
817 )
mbauskar287fe812017-04-10 19:15:57 +0530818
Rohit Waghchaured1d46712023-01-09 15:12:46 +0530819 if frappe.db.get_single_value("Buying Settings", "disable_last_purchase_rate"):
820 return out
821
Ankush Menat494bd9e2022-03-28 18:52:46 +0530822 if not out.price_list_rate and args.transaction_type == "buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530823 from erpnext.stock.doctype.item.item import get_last_purchase_details
Ankush Menat494bd9e2022-03-28 18:52:46 +0530824
825 out.update(get_last_purchase_details(item_doc.name, args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530826
Ankush16d4de52021-08-09 10:41:24 +0530827 return out
828
Ankush Menat494bd9e2022-03-28 18:52:46 +0530829
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530830def insert_item_price(args):
831 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530832 if frappe.db.get_value(
833 "Price List", args.price_list, "currency", cache=True
834 ) == args.currency and cint(
835 frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")
836 ):
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530837 if frappe.has_permission("Item Price", "write"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530838 price_list_rate = (
Rohit Waghchaure0f280742022-12-15 16:34:06 +0530839 (flt(args.rate) + flt(args.discount_amount)) / args.get("conversion_factor")
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530840 if args.get("conversion_factor")
Rohit Waghchaure0f280742022-12-15 16:34:06 +0530841 else (flt(args.rate) + flt(args.discount_amount))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530842 )
Rushabh Mehta985cb822016-12-30 15:06:54 +0530843
Ankush Menat494bd9e2022-03-28 18:52:46 +0530844 item_price = frappe.db.get_value(
845 "Item Price",
846 {"item_code": args.item_code, "price_list": args.price_list, "currency": args.currency},
847 ["name", "price_list_rate"],
848 as_dict=1,
849 )
Nabin Haitb479a872018-09-07 13:17:11 +0530850 if item_price and item_price.name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530851 if item_price.price_list_rate != price_list_rate and frappe.db.get_single_value(
852 "Stock Settings", "update_existing_price_list_rate"
853 ):
854 frappe.db.set_value("Item Price", item_price.name, "price_list_rate", price_list_rate)
855 frappe.msgprint(
856 _("Item Price updated for {0} in Price List {1}").format(args.item_code, args.price_list),
857 alert=True,
858 )
Rushabh Mehta985cb822016-12-30 15:06:54 +0530859 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530860 item_price = frappe.get_doc(
861 {
862 "doctype": "Item Price",
863 "price_list": args.price_list,
864 "item_code": args.item_code,
865 "currency": args.currency,
866 "price_list_rate": price_list_rate,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530867 "uom": args.stock_uom,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530868 }
869 )
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530870 item_price.insert()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530871 frappe.msgprint(
872 _("Item Price added for {0} in Price List {1}").format(args.item_code, args.price_list),
873 alert=True,
874 )
875
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530876
Nabin Hait01ca3e52019-01-25 16:25:15 +0530877def get_item_price(args, item_code, ignore_party=False):
Nabin Haite45ec662018-08-01 17:44:34 +0530878 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530879 Get name, price_list_rate from Item Price based on conditions
880 Check if the desired qty is within the increment of the packing list.
881 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
882 optional fields transaction_date, customer, supplier
883 :param item_code: str, Item Doctype field item_code
Nabin Haite45ec662018-08-01 17:44:34 +0530884 """
885
s-aga-r6b144ba2023-02-18 12:18:41 +0530886 ip = frappe.qb.DocType("Item Price")
887 query = (
888 frappe.qb.from_(ip)
889 .select(ip.name, ip.price_list_rate, ip.uom)
890 .where(
891 (ip.item_code == item_code)
892 & (ip.price_list == args.get("price_list"))
893 & (IfNull(ip.uom, "").isin(["", args.get("uom")]))
894 & (IfNull(ip.batch_no, "").isin(["", args.get("batch_no")]))
895 )
896 .orderby(ip.valid_from, order=frappe.qb.desc)
897 .orderby(IfNull(ip.batch_no, ""), order=frappe.qb.desc)
898 .orderby(ip.uom, order=frappe.qb.desc)
899 )
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530900
Nabin Hait01ca3e52019-01-25 16:25:15 +0530901 if not ignore_party:
Nabin Hait01ca3e52019-01-25 16:25:15 +0530902 if args.get("customer"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530903 query = query.where(ip.customer == args.get("customer"))
Nabin Hait4e456632019-01-29 14:02:08 +0530904 elif args.get("supplier"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530905 query = query.where(ip.supplier == args.get("supplier"))
Nabin Hait4e456632019-01-29 14:02:08 +0530906 else:
s-aga-r6b144ba2023-02-18 12:18:41 +0530907 query = query.where((IfNull(ip.customer, "") == "") & (IfNull(ip.supplier, "") == ""))
Nabin Hait01ca3e52019-01-25 16:25:15 +0530908
Ankush Menat494bd9e2022-03-28 18:52:46 +0530909 if args.get("transaction_date"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530910 query = query.where(
911 (IfNull(ip.valid_from, "2000-01-01") <= args["transaction_date"])
912 & (IfNull(ip.valid_upto, "2500-12-31") >= args["transaction_date"])
913 )
Deepesh Gargf15ff5f2020-07-11 13:58:53 +0530914
s-aga-r6b144ba2023-02-18 12:18:41 +0530915 return query.run()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530916
Nabin Haite45ec662018-08-01 17:44:34 +0530917
918def get_price_list_rate_for(args, item_code):
919 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530920 :param customer: link to Customer DocType
921 :param supplier: link to Supplier DocType
922 :param price_list: str (Standard Buying or Standard Selling)
923 :param item_code: str, Item Doctype field item_code
924 :param qty: Desired Qty
925 :param transaction_date: Date of the price
Nabin Haite45ec662018-08-01 17:44:34 +0530926 """
927 item_price_args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530928 "item_code": item_code,
929 "price_list": args.get("price_list"),
930 "customer": args.get("customer"),
931 "supplier": args.get("supplier"),
932 "uom": args.get("uom"),
933 "transaction_date": args.get("transaction_date"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530934 "batch_no": args.get("batch_no"),
Nabin Haite45ec662018-08-01 17:44:34 +0530935 }
936
937 item_price_data = 0
938 price_list_rate = get_item_price(item_price_args, item_code)
939 if price_list_rate:
940 desired_qty = args.get("qty")
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530941 if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
Nabin Haite45ec662018-08-01 17:44:34 +0530942 item_price_data = price_list_rate
943 else:
Don-Leopardoccdf1932020-01-09 03:54:43 -0300944 for field in ["customer", "supplier"]:
Nabin Haite45ec662018-08-01 17:44:34 +0530945 del item_price_args[field]
946
Ankush Menat494bd9e2022-03-28 18:52:46 +0530947 general_price_list_rate = get_item_price(
948 item_price_args, item_code, ignore_party=args.get("ignore_party")
949 )
Don-Leopardoccdf1932020-01-09 03:54:43 -0300950
Nabin Haite45ec662018-08-01 17:44:34 +0530951 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530952 item_price_args["uom"] = args.get("stock_uom")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530953 general_price_list_rate = get_item_price(
954 item_price_args, item_code, ignore_party=args.get("ignore_party")
955 )
Nabin Haite45ec662018-08-01 17:44:34 +0530956
957 if general_price_list_rate:
958 item_price_data = general_price_list_rate
959
960 if item_price_data:
961 if item_price_data[0][2] == args.get("uom"):
962 return item_price_data[0][1]
Ankush Menat494bd9e2022-03-28 18:52:46 +0530963 elif not args.get("price_list_uom_dependant"):
Nabin Haite45ec662018-08-01 17:44:34 +0530964 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
965 else:
966 return item_price_data[0][1]
967
Ankush Menat494bd9e2022-03-28 18:52:46 +0530968
Nabin Haite45ec662018-08-01 17:44:34 +0530969def check_packing_list(price_list_rate_name, desired_qty, item_code):
970 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530971 Check if the desired qty is within the increment of the packing list.
972 :param price_list_rate_name: Name of Item Price
973 :param desired_qty: Desired Qt
974 :param item_code: str, Item Doctype field item_code
975 :param qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530976 """
977
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530978 flag = True
Nabin Haite45ec662018-08-01 17:44:34 +0530979 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530980 if item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +0530981 packing_increment = desired_qty % item_price.packing_unit
982
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530983 if packing_increment != 0:
984 flag = False
985
986 return flag
Rushabh Mehta1a763742014-10-03 16:36:43 +0530987
Ankush Menat494bd9e2022-03-28 18:52:46 +0530988
Nabin Hait436f5262014-02-10 14:47:54 +0530989def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +0530990 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +0530991
Ankush Menat494bd9e2022-03-28 18:52:46 +0530992 company_currency = frappe.get_cached_value("Company", args.company, "default_currency")
993 if not args.conversion_rate and args.currency == company_currency:
Anand Doshife13bfe2015-08-25 12:49:40 +0530994 args.conversion_rate = 1.0
995
Ankush Menat494bd9e2022-03-28 18:52:46 +0530996 if (
997 not args.ignore_conversion_rate
998 and args.conversion_rate == 1
999 and args.currency != company_currency
1000 ):
1001 args.conversion_rate = (
1002 get_exchange_rate(args.currency, company_currency, args.transaction_date, "for_buying") or 1.0
1003 )
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +05301004
Nabin Hait436f5262014-02-10 14:47:54 +05301005 # validate currency conversion rate
Ankush Menat494bd9e2022-03-28 18:52:46 +05301006 validate_conversion_rate(
1007 args.currency, args.conversion_rate, meta.get_label("conversion_rate"), args.company
1008 )
Anand Doshibd67e872014-04-11 16:51:27 +05301009
Ankush Menat494bd9e2022-03-28 18:52:46 +05301010 args.conversion_rate = flt(
1011 args.conversion_rate,
1012 get_field_precision(meta.get_field("conversion_rate"), frappe._dict({"fields": args})),
1013 )
Anand Doshibd67e872014-04-11 16:51:27 +05301014
Nabin Hait06c8cf42019-05-16 19:17:02 +05301015 if args.price_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301016 if not args.plc_conversion_rate and args.price_list_currency == frappe.db.get_value(
1017 "Price List", args.price_list, "currency", cache=True
1018 ):
Nabin Hait06c8cf42019-05-16 19:17:02 +05301019 args.plc_conversion_rate = 1.0
Manas Solanki3504a232018-06-06 12:46:06 +05301020
Nabin Hait06c8cf42019-05-16 19:17:02 +05301021 # validate price list currency conversion rate
1022 if not args.get("price_list_currency"):
1023 throw(_("Price List Currency not selected"))
1024 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301025 validate_conversion_rate(
1026 args.price_list_currency,
1027 args.plc_conversion_rate,
1028 meta.get_label("plc_conversion_rate"),
1029 args.company,
1030 )
Anand Doshibd67e872014-04-11 16:51:27 +05301031
Nabin Hait06c8cf42019-05-16 19:17:02 +05301032 if meta.get_field("plc_conversion_rate"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301033 args.plc_conversion_rate = flt(
1034 args.plc_conversion_rate,
1035 get_field_precision(meta.get_field("plc_conversion_rate"), frappe._dict({"fields": args})),
1036 )
1037
Anand Doshibd67e872014-04-11 16:51:27 +05301038
Rushabh Mehtaf14b8092014-04-03 14:30:42 +05301039def get_party_item_code(args, item_doc, out):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301040 if args.transaction_type == "selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +05301041 out.customer_item_code = None
Nabin Hait34c551d2019-07-03 10:34:31 +05301042
Ankush Menat494bd9e2022-03-28 18:52:46 +05301043 if args.quotation_to and args.quotation_to != "Customer":
Nabin Hait34c551d2019-07-03 10:34:31 +05301044 return
1045
Nabin Hait79f091e2014-12-26 11:41:15 +05301046 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +05301047
1048 if customer_item_code:
1049 out.customer_item_code = customer_item_code[0].ref_code
1050 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +05301051 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +05301052 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
1053 if customer_group_item_code and not customer_group_item_code[0].customer_name:
1054 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +05301055
Ankush Menat494bd9e2022-03-28 18:52:46 +05301056 if args.transaction_type == "buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +05301057 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +05301058 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +05301059
Ankush Menat494bd9e2022-03-28 18:52:46 +05301060
rohitwaghchaure2ea593b2018-04-12 13:37:08 +05301061def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301062 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +05301063
Rushabh Mehta708e47a2018-08-08 16:37:31 +05301064 if not frappe.flags.pos_profile and not pos_profile:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301065 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get("pos_profile"))
Anand Doshibd67e872014-04-11 16:51:27 +05301066
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301067 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +05301068 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +05301069 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301070 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +05301071
Nabin Hait436f5262014-02-10 14:47:54 +05301072 if res.get("warehouse"):
s-aga-rc716dcc2022-12-29 12:34:18 +05301073 res.actual_qty = get_bin_details(
1074 args.item_code, res.warehouse, include_child_warehouses=True
1075 ).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +05301076
Nabin Hait436f5262014-02-10 14:47:54 +05301077 return res
1078
Ankush Menat494bd9e2022-03-28 18:52:46 +05301079
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301080@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301081def get_pos_profile(company, pos_profile=None, user=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301082 if pos_profile:
1083 return frappe.get_cached_doc("POS Profile", pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301084
1085 if not user:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301086 user = frappe.session["user"]
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301087
s-aga-r6b144ba2023-02-18 12:18:41 +05301088 pf = frappe.qb.DocType("POS Profile")
1089 pfu = frappe.qb.DocType("POS Profile User")
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301090
s-aga-r6b144ba2023-02-18 12:18:41 +05301091 query = (
1092 frappe.qb.from_(pf)
1093 .left_join(pfu)
1094 .on(pf.name == pfu.parent)
1095 .select(pf.star)
1096 .where((pfu.user == user) & (pfu.default == 1))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301097 )
Anand Doshibd67e872014-04-11 16:51:27 +05301098
s-aga-r6b144ba2023-02-18 12:18:41 +05301099 if company:
1100 query = query.where(pf.company == company)
1101
1102 pos_profile = query.run(as_dict=True)
1103
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301104 if not pos_profile and company:
s-aga-r6b144ba2023-02-18 12:18:41 +05301105 pos_profile = (
1106 frappe.qb.from_(pf)
1107 .left_join(pfu)
1108 .on(pf.name == pfu.parent)
1109 .select(pf.star)
1110 .where((pf.company == company) & (pf.disabled == 0))
1111 ).run(as_dict=True)
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301112
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301113 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +05301114
Ankush Menat494bd9e2022-03-28 18:52:46 +05301115
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301116@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +05301117def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +05301118 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +05301119 filters = {"parent": item_code, "uom": uom}
s-aga-r58c027d2023-02-28 15:14:34 +05301120
Rushabh Mehta724f9e52014-10-07 15:29:58 +05301121 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +05301122 filters["parent"] = ("in", (item_code, variant_of))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301123 conversion_factor = frappe.db.get_value("UOM Conversion Detail", filters, "conversion_factor")
Sagar Vora508189e2018-09-11 17:22:25 +05301124 if not conversion_factor:
1125 stock_uom = frappe.db.get_value("Item", item_code, "stock_uom")
1126 conversion_factor = get_uom_conv_factor(uom, stock_uom)
s-aga-r6b144ba2023-02-18 12:18:41 +05301127
rohitwaghchaureffdadbf2019-01-08 16:21:25 +05301128 return {"conversion_factor": conversion_factor or 1.0}
Nabin Hait08222152014-02-28 11:30:47 +05301129
Ankush Menat494bd9e2022-03-28 18:52:46 +05301130
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301131@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +05301132def get_projected_qty(item_code, warehouse):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301133 return {
1134 "projected_qty": frappe.db.get_value(
1135 "Bin", {"item_code": item_code, "warehouse": warehouse}, "projected_qty"
1136 )
1137 }
1138
Nabin Hait08222152014-02-28 11:30:47 +05301139
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301140@frappe.whitelist()
s-aga-rc716dcc2022-12-29 12:34:18 +05301141def get_bin_details(item_code, warehouse, company=None, include_child_warehouses=False):
ruthra kumarbe382052023-01-16 08:50:39 +05301142 bin_details = {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
s-aga-rc716dcc2022-12-29 12:34:18 +05301143
1144 if warehouse:
s-aga-rc3911a52022-12-29 16:38:08 +05301145 from frappe.query_builder.functions import Coalesce, Sum
s-aga-r58c027d2023-02-28 15:14:34 +05301146
s-aga-rc716dcc2022-12-29 12:34:18 +05301147 from erpnext.stock.doctype.warehouse.warehouse import get_child_warehouses
1148
1149 warehouses = get_child_warehouses(warehouse) if include_child_warehouses else [warehouse]
s-aga-rc3911a52022-12-29 16:38:08 +05301150
1151 bin = frappe.qb.DocType("Bin")
1152 bin_details = (
1153 frappe.qb.from_(bin)
1154 .select(
1155 Coalesce(Sum(bin.projected_qty), 0).as_("projected_qty"),
1156 Coalesce(Sum(bin.actual_qty), 0).as_("actual_qty"),
1157 Coalesce(Sum(bin.reserved_qty), 0).as_("reserved_qty"),
1158 )
1159 .where((bin.item_code == item_code) & (bin.warehouse.isin(warehouses)))
1160 ).run(as_dict=True)[0]
s-aga-rc716dcc2022-12-29 12:34:18 +05301161
Anupam4980dd62021-03-15 11:37:46 +05301162 if company:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301163 bin_details["company_total_stock"] = get_company_total_stock(item_code, company)
s-aga-rb425c2d2023-01-02 11:25:13 +05301164
Anupam4980dd62021-03-15 11:37:46 +05301165 return bin_details
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301166
Ankush Menat494bd9e2022-03-28 18:52:46 +05301167
Anupam4980dd62021-03-15 11:37:46 +05301168def get_company_total_stock(item_code, company):
s-aga-r6b144ba2023-02-18 12:18:41 +05301169 bin = frappe.qb.DocType("Bin")
1170 wh = frappe.qb.DocType("Warehouse")
1171
1172 return (
1173 frappe.qb.from_(bin)
1174 .inner_join(wh)
1175 .on(bin.warehouse == wh.name)
1176 .select(Sum(bin.actual_qty))
1177 .where((wh.company == company) & (bin.item_code == item_code))
1178 ).run()[0][0]
Ankush Menat494bd9e2022-03-28 18:52:46 +05301179
Anupam4980dd62021-03-15 11:37:46 +05301180
1181@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +05301182def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +07001183 from erpnext.stock.doctype.batch import batch
Ankush Menat494bd9e2022-03-28 18:52:46 +05301184
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +05301185 if batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301186 return {"actual_batch_qty": batch.get_batch_qty(batch_no, warehouse)}
1187
Rushabh Mehta1e8025b2015-07-24 15:16:25 +05301188
Anand Doshidffec8f2014-07-01 17:45:15 +05301189@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301190def apply_price_list(args, as_doc=False):
1191 """Apply pricelist on a document-like dict object and return as
1192 {'parent': dict, 'children': list}
1193
1194 :param args: See below
1195 :param as_doc: Updates value in the passed dict
1196
Ankush Menat494bd9e2022-03-28 18:52:46 +05301197 args = {
1198 "doctype": "",
1199 "name": "",
1200 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
1201 "conversion_rate": 1.0,
1202 "selling_price_list": None,
1203 "price_list_currency": None,
1204 "price_list_uom_dependant": None,
1205 "plc_conversion_rate": 1.0,
1206 "doctype": "",
1207 "name": "",
1208 "supplier": None,
1209 "transaction_date": None,
1210 "conversion_rate": 1.0,
1211 "buying_price_list": None,
1212 "ignore_pricing_rule": 0/1
1213 }
Anand Doshidffec8f2014-07-01 17:45:15 +05301214 """
1215 args = process_args(args)
1216
1217 parent = get_price_list_currency_and_exchange_rate(args)
Maricae8bc9122021-04-19 11:05:21 +05301218 args.update(parent)
1219
Anand Doshidffec8f2014-07-01 17:45:15 +05301220 children = []
1221
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301222 if "items" in args:
1223 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +05301224 args.update(parent)
1225
1226 for item in item_list:
1227 args_copy = frappe._dict(args.copy())
1228 args_copy.update(item)
1229 item_details = apply_price_list_on_item(args_copy)
1230 children.append(item_details)
1231
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301232 if as_doc:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301233 args.price_list_currency = (parent.price_list_currency,)
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301234 args.plc_conversion_rate = parent.plc_conversion_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +05301235 if args.get("items"):
1236 for i, item in enumerate(args.get("items")):
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301237 for fieldname in children[i]:
1238 # if the field exists in the original doc
1239 # update the value
1240 if fieldname in item and fieldname not in ("name", "doctype"):
1241 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301242 return args
1243 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301244 return {"parent": parent, "children": children}
1245
Anand Doshidffec8f2014-07-01 17:45:15 +05301246
1247def apply_price_list_on_item(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301248 item_doc = frappe.db.get_value("Item", args.item_code, ["name", "variant_of"], as_dict=1)
Ankush16d4de52021-08-09 10:41:24 +05301249 item_details = get_price_list_rate(args, item_doc)
Deepesh Gargb741ae12022-12-02 17:14:06 +05301250 item_details.update(get_pricing_rule_for_item(args))
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301251
Anand Doshidffec8f2014-07-01 17:45:15 +05301252 return item_details
1253
Ankush Menat494bd9e2022-03-28 18:52:46 +05301254
Anand Doshidffec8f2014-07-01 17:45:15 +05301255def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +05301256 if not args.price_list:
1257 return {}
1258
Ankush Menat494bd9e2022-03-28 18:52:46 +05301259 if args.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
Shreya3f778522018-05-15 16:59:20 +05301260 args.update({"exchange_rate": "for_selling"})
Ankush Menat494bd9e2022-03-28 18:52:46 +05301261 elif args.doctype in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]:
Shreya3f778522018-05-15 16:59:20 +05301262 args.update({"exchange_rate": "for_buying"})
1263
rohitwaghchaurea85ddf22019-11-19 18:47:48 +05301264 price_list_details = get_price_list_details(args.price_list)
1265
1266 price_list_currency = price_list_details.get("currency")
1267 price_list_uom_dependant = price_list_details.get("price_list_uom_dependant")
1268
Anand Doshidffec8f2014-07-01 17:45:15 +05301269 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +01001270 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +05301271
Ankush Menat494bd9e2022-03-28 18:52:46 +05301272 if (not plc_conversion_rate) or (
1273 price_list_currency
1274 and args.price_list_currency
1275 and price_list_currency != args.price_list_currency
1276 ):
1277 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
1278 plc_conversion_rate = (
1279 get_exchange_rate(
1280 price_list_currency, company_currency, args.transaction_date, args.exchange_rate
1281 )
1282 or plc_conversion_rate
1283 )
Anand Doshidffec8f2014-07-01 17:45:15 +05301284
Ankush Menat494bd9e2022-03-28 18:52:46 +05301285 return frappe._dict(
1286 {
1287 "price_list_currency": price_list_currency,
1288 "price_list_uom_dependant": price_list_uom_dependant,
1289 "plc_conversion_rate": plc_conversion_rate or 1,
1290 }
1291 )
1292
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +05301293
1294@frappe.whitelist()
1295def get_default_bom(item_code=None):
marination9f2d3252022-06-14 17:20:44 +05301296 def _get_bom(item):
1297 bom = frappe.get_all(
1298 "BOM", dict(item=item, is_active=True, is_default=True, docstatus=1), limit=1
Ankush Menat494bd9e2022-03-28 18:52:46 +05301299 )
marination9f2d3252022-06-14 17:20:44 +05301300 return bom[0].name if bom else None
1301
1302 if not item_code:
1303 return
1304
1305 bom_name = _get_bom(item_code)
1306
1307 template_item = frappe.db.get_value("Item", item_code, "variant_of")
1308 if not bom_name and template_item:
1309 bom_name = _get_bom(template_item)
1310
1311 return bom_name
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301312
Ankush Menat494bd9e2022-03-28 18:52:46 +05301313
Deepesh Garg15ff6a52020-02-18 12:28:41 +05301314@frappe.whitelist()
Manas Solanki087a2252018-05-04 16:02:38 +05301315def get_valuation_rate(item_code, company, warehouse=None):
rohitwaghchauree6199dc2023-09-20 17:27:35 +05301316 if frappe.get_cached_value("Warehouse", warehouse, "is_group"):
1317 return {"valuation_rate": 0.0}
1318
Manas Solankib16a4ec2018-05-04 16:49:33 +05301319 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +05301320 item_group = get_item_group_defaults(item_code, company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001321 brand = get_brand_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +05301322 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +05301323 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +05301324 if not warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301325 warehouse = (
1326 item.get("default_warehouse")
1327 or item_group.get("default_warehouse")
1328 or brand.get("default_warehouse")
1329 )
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301330
Ankush Menat494bd9e2022-03-28 18:52:46 +05301331 return frappe.db.get_value(
1332 "Bin", {"item_code": item_code, "warehouse": warehouse}, ["valuation_rate"], as_dict=True
1333 ) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301334
Manas Solankie3910fb2018-05-16 15:50:17 +05301335 elif not item.get("is_stock_item"):
s-aga-r6b144ba2023-02-18 12:18:41 +05301336 pi_item = frappe.qb.DocType("Purchase Invoice Item")
1337 valuation_rate = (
1338 frappe.qb.from_(pi_item)
1339 .select((Sum(pi_item.base_net_amount) / Sum(pi_item.qty * pi_item.conversion_factor)))
s-aga-r58c027d2023-02-28 15:14:34 +05301340 .where((pi_item.docstatus == 1) & (pi_item.item_code == item_code))
s-aga-r6b144ba2023-02-18 12:18:41 +05301341 ).run()
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301342
Saurabhbd01a812016-03-07 14:32:23 +05301343 if valuation_rate:
1344 return {"valuation_rate": valuation_rate[0][0] or 0.0}
1345 else:
1346 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301347
Ankush Menat494bd9e2022-03-28 18:52:46 +05301348
Saurabh2d7af632016-02-26 11:09:20 +05301349def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +05301350 if out.valuation_rate:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301351 out.update({"gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)})
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301352
Saurabhd3135532016-02-25 18:59:20 +05301353 return out
mbauskar6f603392016-01-21 16:10:22 +05301354
Ankush Menat494bd9e2022-03-28 18:52:46 +05301355
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301356@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301357def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaure648efca2023-03-28 12:16:27 +05301358 serial_nos = serial_nos or []
1359 return serial_nos
Manas Solankie5e87f72018-05-28 20:07:08 +05301360
1361
1362def update_party_blanket_order(args, out):
ronelvcabrera370cdc02019-12-04 18:37:11 +08001363 if out["against_blanket_order"]:
1364 blanket_order_details = get_blanket_order_details(args)
1365 if blanket_order_details:
1366 out.update(blanket_order_details)
Manas Solankie5e87f72018-05-28 20:07:08 +05301367
Ankush Menat494bd9e2022-03-28 18:52:46 +05301368
Manas Solankie5e87f72018-05-28 20:07:08 +05301369@frappe.whitelist()
1370def get_blanket_order_details(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301371 if isinstance(args, str):
Manas Solankie5e87f72018-05-28 20:07:08 +05301372 args = frappe._dict(json.loads(args))
1373
1374 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +05301375
s-aga-r6b144ba2023-02-18 12:18:41 +05301376 if args.item_code:
1377 bo = frappe.qb.DocType("Blanket Order")
1378 bo_item = frappe.qb.DocType("Blanket Order Item")
1379
1380 query = (
1381 frappe.qb.from_(bo)
1382 .from_(bo_item)
1383 .select(bo_item.rate.as_("blanket_order_rate"), bo.name.as_("blanket_order"))
1384 .where(
1385 (bo.company == args.company)
1386 & (bo_item.item_code == args.item_code)
1387 & (bo.docstatus == 1)
1388 & (bo.name == bo_item.parent)
1389 )
Ankush Menat494bd9e2022-03-28 18:52:46 +05301390 )
Nabin Hait2737b082018-06-14 18:07:22 +05301391
s-aga-r6b144ba2023-02-18 12:18:41 +05301392 if args.customer and args.doctype == "Sales Order":
1393 query = query.where(bo.customer == args.customer)
1394 elif args.supplier and args.doctype == "Purchase Order":
1395 query = query.where(bo.supplier == args.supplier)
1396 if args.blanket_order:
1397 query = query.where(bo.name == args.blanket_order)
1398 if args.transaction_date:
1399 query = query.where(bo.to_date >= args.transaction_date)
1400
1401 blanket_order_details = query.run(as_dict=True)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301402 blanket_order_details = blanket_order_details[0] if blanket_order_details else ""
s-aga-r6b144ba2023-02-18 12:18:41 +05301403
Manas Solankie5e87f72018-05-28 20:07:08 +05301404 return blanket_order_details