blob: 1cb10575cd15bf2d52852a4cf94aceb16c369028 [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
Smit Vorab206b052023-11-23 15:10:47 +053011from frappe.model.utils import get_fetch_values
Rohit Waghchaure648efca2023-03-28 12:16:27 +053012from frappe.query_builder.functions import IfNull, Sum
Chillar Anand915b3432021-09-02 16:44:59 +053013from frappe.utils import add_days, add_months, cint, cstr, flt, getdate
Nabin Hait98c2a052014-05-05 18:41:41 +053014
Chillar Anand915b3432021-09-02 16:44:59 +053015from erpnext import get_company_currency
16from erpnext.accounts.doctype.pricing_rule.pricing_rule import (
17 get_pricing_rule_for_item,
18 set_transaction_type,
19)
20from erpnext.setup.doctype.brand.brand import get_brand_defaults
21from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults
22from erpnext.setup.utils import get_exchange_rate
Chillar Anand915b3432021-09-02 16:44:59 +053023from erpnext.stock.doctype.item.item import get_item_defaults, get_uom_conv_factor
24from erpnext.stock.doctype.item_manufacturer.item_manufacturer import get_item_manufacturer_part_no
25from erpnext.stock.doctype.price_list.price_list import get_price_list_details
tundebabzyacccdb32017-11-23 08:35:15 +010026
Ankush Menat494bd9e2022-03-28 18:52:46 +053027sales_doctypes = ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice", "POS Invoice"]
28purchase_doctypes = [
29 "Material Request",
30 "Supplier Quotation",
31 "Purchase Order",
32 "Purchase Receipt",
33 "Purchase Invoice",
34]
35
Nabin Hait0d1ccc32019-02-14 18:30:10 +053036
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053037@frappe.whitelist()
Deepesh Garga7051cb2023-04-14 09:59:42 +053038def get_item_details(args, doc=None, for_validate=False, overwrite_warehouse=True):
Nabin Hait436f5262014-02-10 14:47:54 +053039 """
Ankush Menat494bd9e2022-03-28 18:52:46 +053040 args = {
41 "item_code": "",
42 "warehouse": None,
43 "customer": "",
44 "conversion_rate": 1.0,
45 "selling_price_list": None,
46 "price_list_currency": None,
47 "plc_conversion_rate": 1.0,
48 "doctype": "",
49 "name": "",
50 "supplier": None,
51 "transaction_date": None,
52 "conversion_rate": 1.0,
53 "buying_price_list": None,
Sagar Sharma409df262022-04-19 14:57:31 +053054 "is_subcontracted": 0/1,
Ankush Menat494bd9e2022-03-28 18:52:46 +053055 "ignore_pricing_rule": 0/1
56 "project": ""
57 "set_warehouse": ""
58 }
Nabin Hait436f5262014-02-10 14:47:54 +053059 """
Suraj Shetty182f4de2019-08-16 08:16:22 +053060
Anand Doshidffec8f2014-07-01 17:45:15 +053061 args = process_args(args)
marination392f3232020-07-14 17:03:17 +053062 for_validate = process_string_args(for_validate)
63 overwrite_warehouse = process_string_args(overwrite_warehouse)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053064 item = frappe.get_cached_doc("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053065 validate_item_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053066
Ankush Menat8fe5feb2021-11-04 19:48:32 +053067 if isinstance(doc, str):
Deepesh Gargef0d26c2020-01-06 15:34:15 +053068 doc = json.loads(doc)
69
Deepesh Gargef0d26c2020-01-06 15:34:15 +053070 if doc:
Sagar Vora1a3997a2022-06-16 17:03:47 +000071 args["transaction_date"] = doc.get("transaction_date") or doc.get("posting_date")
Deepesh Gargef0d26c2020-01-06 15:34:15 +053072
Sagar Vora1a3997a2022-06-16 17:03:47 +000073 if doc.get("doctype") == "Purchase Invoice":
74 args["bill_date"] = doc.get("bill_date")
75
Deepesh Garga7051cb2023-04-14 09:59:42 +053076 out = get_basic_details(args, item, overwrite_warehouse)
Deepesh Garg4c61ee32023-04-02 09:35:27 +053077
Saif Ur Rehman67786682018-12-27 02:11:07 +050078 get_item_tax_template(args, item, out)
Ankush Menat494bd9e2022-03-28 18:52:46 +053079 out["item_tax_rate"] = get_item_tax_map(
80 args.company,
81 args.get("item_tax_template")
82 if out.get("item_tax_template") is None
83 else out.get("item_tax_template"),
84 as_json=True,
85 )
Saif Ur Rehman67786682018-12-27 02:11:07 +050086
Rushabh Mehta708e47a2018-08-08 16:37:31 +053087 get_party_item_code(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053088
Rohit Waghchaure951023f2024-01-31 11:32:17 +053089 if args.get("doctype") in ["Sales Order", "Quotation"]:
90 set_valuation_rate(out, args)
Anand Doshibd67e872014-04-11 16:51:27 +053091
Manas Solankie5e87f72018-05-28 20:07:08 +053092 update_party_blanket_order(args, out)
93
HENRY Florian231fe412023-02-13 16:26:05 +010094 # Never try to find a customer price if customer is set in these Doctype
95 current_customer = args.customer
96 if args.get("doctype") in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]:
97 args.customer = None
98
Ankush16d4de52021-08-09 10:41:24 +053099 out.update(get_price_list_rate(args, item))
Nabin Hait436f5262014-02-10 14:47:54 +0530100
HENRY Florian231fe412023-02-13 16:26:05 +0100101 args.customer = current_customer
102
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530103 if args.customer and cint(args.is_pos):
Anuja Pawarf132ed42021-05-07 12:11:09 +0530104 out.update(get_pos_profile_item_details(args.company, args, update_data=True))
Rushabh Mehta6b537922017-03-14 16:59:11 +0530105
Ankush Menat494bd9e2022-03-28 18:52:46 +0530106 if (
107 args.get("doctype") == "Material Request"
108 and args.get("material_request_type") == "Material Transfer"
109 ):
Nabin Haitda17f9c2020-05-01 18:16:25 +0530110 out.update(get_bin_details(args.item_code, args.get("from_warehouse")))
111
112 elif out.get("warehouse"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530113 if doc and doc.get("doctype") == "Purchase Order":
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530114 # calculate company_total_stock only for po
s-aga-rc716dcc2022-12-29 12:34:18 +0530115 bin_details = get_bin_details(
116 args.item_code, out.warehouse, args.company, include_child_warehouses=True
117 )
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530118 else:
s-aga-rc716dcc2022-12-29 12:34:18 +0530119 bin_details = get_bin_details(args.item_code, out.warehouse, include_child_warehouses=True)
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530120
121 out.update(bin_details)
Anand Doshibd67e872014-04-11 16:51:27 +0530122
Nabin Haita3dd72a2014-05-28 12:49:20 +0530123 # update args with out, if key or value not exists
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530124 for key, value in out.items():
Nabin Haita3dd72a2014-05-28 12:49:20 +0530125 if args.get(key) is None:
126 args[key] = value
127
Deepesh Garg6192af52022-12-08 18:04:40 +0530128 data = get_pricing_rule_for_item(args, doc=doc, for_validate=for_validate)
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530129
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530130 out.update(data)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530131
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530132 if args.transaction_date and item.lead_time_days:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530133 out.schedule_date = out.lead_time_date = add_days(args.transaction_date, item.lead_time_days)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530134
Sagar Sharma409df262022-04-19 14:57:31 +0530135 if args.get("is_subcontracted"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530136 out.bom = args.get("bom") or get_default_bom(args.item_code)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530137
138 get_gross_profit(out)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530139 if args.doctype == "Material Request":
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530140 out.rate = args.rate or out.price_list_rate
Rohit Waghchaure1bc53a32021-03-31 15:28:26 +0530141 out.amount = flt(args.qty) * flt(out.rate)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530142
Ankush Menat1e976642022-02-15 10:57:06 +0530143 out = remove_standard_fields(out)
Deepesh Garga7051cb2023-04-14 09:59:42 +0530144 return out
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530145
Ankush Menat494bd9e2022-03-28 18:52:46 +0530146
Ankush Menat1e976642022-02-15 10:57:06 +0530147def remove_standard_fields(details):
148 for key in child_table_fields + default_fields:
149 details.pop(key, None)
150 return details
151
152
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530153def set_valuation_rate(out, args):
Gursheen Anand8bdb61c2023-11-22 16:17:23 +0530154 if frappe.db.exists("Product Bundle", {"name": args.item_code, "disabled": 0}, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530155 valuation_rate = 0.0
156 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530157
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530158 for bundle_item in bundled_items.items:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530159 valuation_rate += flt(
160 get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get(
161 "valuation_rate"
162 )
163 * bundle_item.qty
164 )
Anand Doshi70f57eb2015-11-27 14:37:40 +0530165
Ankush Menat494bd9e2022-03-28 18:52:46 +0530166 out.update({"valuation_rate": valuation_rate})
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530167
168 else:
169 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
170
Nabin Hait436f5262014-02-10 14:47:54 +0530171
Anand Doshidffec8f2014-07-01 17:45:15 +0530172def process_args(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530173 if isinstance(args, str):
Anand Doshidffec8f2014-07-01 17:45:15 +0530174 args = json.loads(args)
175
176 args = frappe._dict(args)
177
Anand Doshidffec8f2014-07-01 17:45:15 +0530178 if not args.get("price_list"):
179 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
180
Devin Slauenwhite55276f12022-05-25 00:05:22 -0400181 if not args.item_code and args.barcode:
Anand Doshidffec8f2014-07-01 17:45:15 +0530182 args.item_code = get_item_code(barcode=args.barcode)
183 elif not args.item_code and args.serial_no:
184 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530185
mbauskar6f603392016-01-21 16:10:22 +0530186 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530187 return args
188
Ankush Menat494bd9e2022-03-28 18:52:46 +0530189
marination392f3232020-07-14 17:03:17 +0530190def process_string_args(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530191 if isinstance(args, str):
marination392f3232020-07-14 17:03:17 +0530192 args = json.loads(args)
193 return args
tundebabzyacccdb32017-11-23 08:35:15 +0100194
Ankush Menat494bd9e2022-03-28 18:52:46 +0530195
Nabin Hait436f5262014-02-10 14:47:54 +0530196def get_item_code(barcode=None, serial_no=None):
197 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100198 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530199 if not item_code:
200 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530201 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530202 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530203 if not item_code:
204 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530205
Nabin Hait436f5262014-02-10 14:47:54 +0530206 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530207
tundebabzyacccdb32017-11-23 08:35:15 +0100208
Nabin Hait436f5262014-02-10 14:47:54 +0530209def validate_item_details(args, item):
210 if not args.company:
211 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530212
Nabin Hait436f5262014-02-10 14:47:54 +0530213 from erpnext.stock.doctype.item.item import validate_end_of_life
Ankush Menat494bd9e2022-03-28 18:52:46 +0530214
Anand Doshi21e09a22015-10-29 12:21:41 +0530215 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530216
Rohit Waghchaure2c83fff2023-01-18 23:21:29 +0530217 if cint(item.has_variants):
218 msg = f"Item {item.name} is a template, please select one of its variants"
219
220 throw(_(msg), title=_("Template Item Selected"))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530221
tundebabzyacccdb32017-11-23 08:35:15 +0100222 elif args.transaction_type == "buying" and args.doctype != "Material Request":
s-aga-r6d89b2f2022-06-18 15:46:59 +0530223 if args.get("is_subcontracted"):
224 if args.get("is_old_subcontracting_flow"):
225 if item.is_sub_contracted_item != 1:
226 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
227 else:
228 if item.is_stock_item:
229 throw(_("Item {0} must be a Non-Stock Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530230
tundebabzyacccdb32017-11-23 08:35:15 +0100231
Suraj Shetty182f4de2019-08-16 08:16:22 +0530232def get_basic_details(args, item, overwrite_warehouse=True):
tundebabzyacccdb32017-11-23 08:35:15 +0100233 """
234 :param args: {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530235 "item_code": "",
236 "warehouse": None,
237 "customer": "",
238 "conversion_rate": 1.0,
239 "selling_price_list": None,
240 "price_list_currency": None,
241 "price_list_uom_dependant": None,
242 "plc_conversion_rate": 1.0,
243 "doctype": "",
244 "name": "",
245 "supplier": None,
246 "transaction_date": None,
247 "conversion_rate": 1.0,
248 "buying_price_list": None,
Sagar Sharma409df262022-04-19 14:57:31 +0530249 "is_subcontracted": 0/1,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530250 "ignore_pricing_rule": 0/1
251 "project": "",
252 barcode: "",
253 serial_no: "",
254 currency: "",
255 update_stock: "",
256 price_list: "",
257 company: "",
258 order_type: "",
259 is_pos: "",
260 project: "",
261 qty: "",
262 stock_qty: "",
263 conversion_factor: "",
264 against_blanket_order: 0/1
265 }
tundebabzyacccdb32017-11-23 08:35:15 +0100266 :param item: `item_code` of Item object
267 :return: frappe._dict
268 """
269
Rushabh Mehta1a763742014-10-03 16:36:43 +0530270 if not item:
271 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530272
Rohit Waghchaure951023f2024-01-31 11:32:17 +0530273 if (
274 item.variant_of and not item.taxes and frappe.db.exists("Item Tax", {"parent": item.variant_of})
275 ):
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530276 item.update_template_tables()
277
Manas Solankib16a4ec2018-05-04 16:49:33 +0530278 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530279 item_group_defaults = get_item_group_defaults(item.name, args.company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500280 brand_defaults = get_brand_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530281
Ankush Menat494bd9e2022-03-28 18:52:46 +0530282 defaults = frappe._dict(
283 {
284 "item_defaults": item_defaults,
285 "item_group_defaults": item_group_defaults,
286 "brand_defaults": brand_defaults,
287 }
288 )
marinatione05013e2020-04-06 22:13:13 +0530289
Saqib438e0432020-04-03 10:02:56 +0530290 warehouse = get_item_warehouse(item, args, overwrite_warehouse, defaults)
Nabin Hait36028bf2014-02-12 19:09:28 +0530291
Ankush Menat494bd9e2022-03-28 18:52:46 +0530292 if args.get("doctype") == "Material Request" and not args.get("material_request_type"):
293 args["material_request_type"] = frappe.db.get_value(
294 "Material Request", args.get("name"), "material_request_type", cache=True
295 )
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530296
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530297 expense_account = None
298
Ankush Menat494bd9e2022-03-28 18:52:46 +0530299 if args.get("doctype") == "Purchase Invoice" and item.is_fixed_asset:
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530300 from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530301
Ankush Menat494bd9e2022-03-28 18:52:46 +0530302 expense_account = get_asset_category_account(
303 fieldname="fixed_asset_account", item=args.item_code, company=args.company
304 )
305
306 # Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
307 if not args.get("uom"):
308 if args.get("doctype") in sales_doctypes:
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530309 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
Ankush Menat494bd9e2022-03-28 18:52:46 +0530310 elif (args.get("doctype") in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]) or (
311 args.get("doctype") == "Material Request" and args.get("material_request_type") == "Purchase"
312 ):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530313 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
314 else:
315 args.uom = item.stock_uom
316
Sagar Vora57038c32022-11-09 18:56:09 +0530317 # Set stock UOM in args, so that it can be used while fetching item price
318 args.stock_uom = item.stock_uom
319
Ankush Menat494bd9e2022-03-28 18:52:46 +0530320 if args.get("batch_no") and item.name != frappe.get_cached_value(
321 "Batch", args.get("batch_no"), "item"
322 ):
323 args["batch_no"] = ""
Rohit Waghchauree1f07042021-08-23 14:27:55 +0530324
Ankush Menat494bd9e2022-03-28 18:52:46 +0530325 out = frappe._dict(
326 {
327 "item_code": item.name,
328 "item_name": item.item_name,
329 "description": cstr(item.description).strip(),
330 "image": cstr(item.image).strip(),
331 "warehouse": warehouse,
332 "income_account": get_default_income_account(
333 args, item_defaults, item_group_defaults, brand_defaults
334 ),
335 "expense_account": expense_account
336 or get_default_expense_account(args, item_defaults, item_group_defaults, brand_defaults),
David Arnold1612d7b2023-10-26 14:03:22 +0200337 "discount_account": get_default_discount_account(
338 args, item_defaults, item_group_defaults, brand_defaults
339 ),
340 "provisional_expense_account": get_provisional_account(
341 args, item_defaults, item_group_defaults, brand_defaults
342 ),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530343 "cost_center": get_default_cost_center(
344 args, item_defaults, item_group_defaults, brand_defaults
345 ),
346 "has_serial_no": item.has_serial_no,
347 "has_batch_no": item.has_batch_no,
348 "batch_no": args.get("batch_no"),
349 "uom": args.uom,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530350 "stock_uom": item.stock_uom,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530351 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
352 "qty": flt(args.qty) or 1.0,
353 "stock_qty": flt(args.qty) or 1.0,
354 "price_list_rate": 0.0,
355 "base_price_list_rate": 0.0,
356 "rate": 0.0,
357 "base_rate": 0.0,
358 "amount": 0.0,
359 "base_amount": 0.0,
360 "net_rate": 0.0,
361 "net_amount": 0.0,
362 "discount_percentage": 0.0,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530363 "discount_amount": flt(args.discount_amount) or 0.0,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530364 "update_stock": args.get("update_stock")
365 if args.get("doctype") in ["Sales Invoice", "Purchase Invoice"]
366 else 0,
367 "delivered_by_supplier": item.delivered_by_supplier
368 if args.get("doctype") in ["Sales Order", "Sales Invoice"]
369 else 0,
370 "is_fixed_asset": item.is_fixed_asset,
371 "last_purchase_rate": item.last_purchase_rate
372 if args.get("doctype") in ["Purchase Order"]
373 else 0,
374 "transaction_date": args.get("transaction_date"),
375 "against_blanket_order": args.get("against_blanket_order"),
376 "bom_no": item.get("default_bom"),
377 "weight_per_unit": args.get("weight_per_unit") or item.get("weight_per_unit"),
378 "weight_uom": args.get("weight_uom") or item.get("weight_uom"),
379 "grant_commission": item.get("grant_commission"),
380 }
381 )
Anand Doshibd67e872014-04-11 16:51:27 +0530382
rohitwaghchauredb24e242023-12-13 14:06:45 +0530383 default_supplier = get_default_supplier(args, item_defaults, item_group_defaults, brand_defaults)
384 if default_supplier:
385 out.supplier = default_supplier
386
Zlash65627be1d2019-01-15 14:16:32 +0530387 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zlash6580f5cb02018-08-29 11:39:08 +0530388 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530389
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530390 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530391 if item.stock_uom == args.uom:
392 out.conversion_factor = 1.0
393 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530394 out.conversion_factor = args.conversion_factor or get_conversion_factor(item.name, args.uom).get(
395 "conversion_factor"
396 )
mbauskar287fe812017-04-10 19:15:57 +0530397
398 args.conversion_factor = out.conversion_factor
399 out.stock_qty = out.qty * out.conversion_factor
Saqib Ansari3713ae72022-02-14 11:33:34 +0530400 args.stock_qty = out.stock_qty
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530401
Shreya Shah44fa9a62018-01-08 14:58:20 +0530402 # calculate last purchase rate
Rohit Waghchaureec171fc2023-01-09 18:49:48 +0530403 if args.get("doctype") in purchase_doctypes and not frappe.db.get_single_value(
404 "Buying Settings", "disable_last_purchase_rate"
405 ):
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530406 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +0530407
408 out.last_purchase_rate = item_last_purchase_rate(
409 args.name, args.conversion_rate, item.name, out.conversion_factor
410 )
Shreya Shah44fa9a62018-01-08 14:58:20 +0530411
Nabin Haitb09ed412015-02-17 10:33:58 +0530412 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530413 for d in [
414 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530415 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530416 ["Cost Center", "cost_center", "cost_center"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530417 ["Warehouse", "warehouse", ""],
418 ]:
419 if not out[d[1]]:
420 out[d[1]] = frappe.get_cached_value("Company", args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530421
Ankush Menat64905182022-03-09 15:37:14 +0530422 for fieldname in ("item_name", "item_group", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530423 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530424
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530425 if args.get("manufacturer"):
426 part_no = get_item_manufacturer_part_no(args.get("item_code"), args.get("manufacturer"))
427 if part_no:
428 out["manufacturer_part_no"] = part_no
429 else:
430 out["manufacturer_part_no"] = None
431 out["manufacturer"] = None
marination3e7a8ab2020-04-07 21:00:57 +0530432 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530433 data = frappe.get_value(
434 "Item", item.name, ["default_item_manufacturer", "default_manufacturer_part_no"], as_dict=1
435 )
rohitwaghchaurebe16e5c2020-05-01 10:50:17 +0530436
437 if data:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530438 out.update(
439 {
440 "manufacturer": data.default_item_manufacturer,
441 "manufacturer_part_no": data.default_manufacturer_part_no,
442 }
443 )
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530444
Ankush Menat494bd9e2022-03-28 18:52:46 +0530445 child_doctype = args.doctype + " Item"
Nabin Hait34c551d2019-07-03 10:34:31 +0530446 meta = frappe.get_meta(child_doctype)
447 if meta.get_field("barcode"):
448 update_barcode_value(out)
449
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530450 if out.get("weight_per_unit"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530451 out["total_weight"] = out.weight_per_unit * out.stock_qty
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530452
Nabin Hait436f5262014-02-10 14:47:54 +0530453 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530454
Ankush Menat494bd9e2022-03-28 18:52:46 +0530455
Chillar Anand772d4752021-10-06 22:28:48 +0530456def get_item_warehouse(item, args, overwrite_warehouse, defaults=None):
Saqib438e0432020-04-03 10:02:56 +0530457 if not defaults:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530458 defaults = frappe._dict(
459 {
460 "item_defaults": get_item_defaults(item.name, args.company),
461 "item_group_defaults": get_item_group_defaults(item.name, args.company),
462 "brand_defaults": get_brand_defaults(item.name, args.company),
463 }
464 )
Saqib438e0432020-04-03 10:02:56 +0530465
466 if overwrite_warehouse or not args.warehouse:
467 warehouse = (
Ankush Menat494bd9e2022-03-28 18:52:46 +0530468 args.get("set_warehouse")
469 or defaults.item_defaults.get("default_warehouse")
470 or defaults.item_group_defaults.get("default_warehouse")
471 or defaults.brand_defaults.get("default_warehouse")
472 or args.get("warehouse")
Saqib438e0432020-04-03 10:02:56 +0530473 )
474
475 if not warehouse:
476 defaults = frappe.defaults.get_defaults() or {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530477 warehouse_exists = frappe.db.exists(
478 "Warehouse", {"name": defaults.default_warehouse, "company": args.company}
479 )
Saqib438e0432020-04-03 10:02:56 +0530480 if defaults.get("default_warehouse") and warehouse_exists:
481 warehouse = defaults.default_warehouse
482
483 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530484 warehouse = args.get("warehouse")
marinatione05013e2020-04-06 22:13:13 +0530485
Marica3b1be2b2020-10-22 17:04:31 +0530486 if not warehouse:
487 default_warehouse = frappe.db.get_single_value("Stock Settings", "default_warehouse")
488 if frappe.db.get_value("Warehouse", default_warehouse, "company") == args.company:
489 return default_warehouse
490
Saqib438e0432020-04-03 10:02:56 +0530491 return warehouse
492
Ankush Menat494bd9e2022-03-28 18:52:46 +0530493
Nabin Hait34c551d2019-07-03 10:34:31 +0530494def update_barcode_value(out):
Nabin Hait34c551d2019-07-03 10:34:31 +0530495 barcode_data = get_barcode_data([out])
496
497 # If item has one barcode then update the value of the barcode field
498 if barcode_data and len(barcode_data.get(out.item_code)) == 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530499 out["barcode"] = barcode_data.get(out.item_code)[0]
500
Nabin Hait34c551d2019-07-03 10:34:31 +0530501
Saqiba6f98d42020-07-23 18:51:26 +0530502def get_barcode_data(items_list):
Deepesh Gargf52d7c72024-01-02 13:37:39 +0530503 # get item-wise batch no data
504 # example: {'LED-GRE': [Batch001, Batch002]}
Saqiba6f98d42020-07-23 18:51:26 +0530505 # where LED-GRE is item code, SN0001 is serial no and Pune is warehouse
506
507 itemwise_barcode = {}
508 for item in items_list:
s-aga-r6b144ba2023-02-18 12:18:41 +0530509 barcodes = frappe.db.get_all(
510 "Item Barcode", filters={"parent": item.item_code}, fields="barcode"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530511 )
Saqiba6f98d42020-07-23 18:51:26 +0530512
513 for barcode in barcodes:
514 if item.item_code not in itemwise_barcode:
515 itemwise_barcode.setdefault(item.item_code, [])
516 itemwise_barcode[item.item_code].append(barcode.get("barcode"))
517
518 return itemwise_barcode
519
Ankush Menat494bd9e2022-03-28 18:52:46 +0530520
Zlash6580f5cb02018-08-29 11:39:08 +0530521@frappe.whitelist()
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530522def get_item_tax_info(company, tax_category, item_codes, item_rates=None, item_tax_templates=None):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500523 out = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530524
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530525 if item_tax_templates is None:
Deepesh Gargcae42b482021-06-25 13:34:00 +0530526 item_tax_templates = {}
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +0530527
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530528 if item_rates is None:
529 item_rates = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530530
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530531 if isinstance(item_codes, (str,)):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500532 item_codes = json.loads(item_codes)
533
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530534 if isinstance(item_rates, (str,)):
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530535 item_rates = json.loads(item_rates)
536
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530537 if isinstance(item_tax_templates, (str,)):
Deepesh Garg94d46042021-06-23 20:56:27 +0530538 item_tax_templates = json.loads(item_tax_templates)
539
Saif Ur Rehman67786682018-12-27 02:11:07 +0500540 for item_code in item_codes:
Deepesh Garg94d46042021-06-23 20:56:27 +0530541 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 +0500542 continue
Deepesh Garg94d46042021-06-23 20:56:27 +0530543
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530544 out[item_code[1]] = {}
545 item = frappe.get_cached_doc("Item", item_code[0])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530546 args = {
547 "company": company,
548 "tax_category": tax_category,
Divyam Mistrye9fe10c2024-02-01 16:15:43 +0530549 "base_net_rate": item_rates.get(item_code[1]),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530550 }
Deepesh Garg269962a2021-06-23 22:52:51 +0530551
552 if item_tax_templates:
553 args.update({"item_tax_template": item_tax_templates.get(item_code[1])})
Deepesh Garg94d46042021-06-23 20:56:27 +0530554
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530555 get_item_tax_template(args, item, out[item_code[1]])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530556 out[item_code[1]]["item_tax_rate"] = get_item_tax_map(
557 company, out[item_code[1]].get("item_tax_template"), as_json=True
558 )
Saif Ur Rehman67786682018-12-27 02:11:07 +0500559
560 return out
561
Ankush Menat494bd9e2022-03-28 18:52:46 +0530562
Saif Ur Rehman67786682018-12-27 02:11:07 +0500563def get_item_tax_template(args, item, out):
564 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530565 args = {
566 "tax_category": None
567 "item_tax_template": None
568 }
Saif Ur Rehman67786682018-12-27 02:11:07 +0500569 """
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530570 item_tax_template = None
571 if item.taxes:
572 item_tax_template = _get_item_tax_template(args, item.taxes, out)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500573
574 if not item_tax_template:
575 item_group = item.item_group
576 while item_group and not item_tax_template:
577 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
578 item_tax_template = _get_item_tax_template(args, item_group_doc.taxes, out)
579 item_group = item_group_doc.parent_item_group
580
barredterra0465c9a2023-12-08 14:15:26 +0100581 if args.get("child_doctype") and item_tax_template:
582 out.update(get_fetch_values(args.get("child_doctype"), "item_tax_template", item_tax_template))
Smit Vorab206b052023-11-23 15:10:47 +0530583
Ankush Menat494bd9e2022-03-28 18:52:46 +0530584
18alantom308905b2021-05-03 23:34:34 +0530585def _get_item_tax_template(args, taxes, out=None, for_validate=False):
586 if out is None:
587 out = {}
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530588 taxes_with_validity = []
589 taxes_with_no_validity = []
590
591 for tax in taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530592 tax_company = frappe.get_cached_value("Item Tax Template", tax.item_tax_template, "company")
593 if tax_company == args["company"]:
594 if tax.valid_from or tax.maximum_net_rate:
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530595 # In purchase Invoice first preference will be given to supplier invoice date
596 # if supplier date is not present then posting date
Sagar Vora1a3997a2022-06-16 17:03:47 +0000597 validation_date = args.get("bill_date") or args.get("transaction_date")
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530598
Ankush Menat494bd9e2022-03-28 18:52:46 +0530599 if getdate(tax.valid_from) <= getdate(validation_date) and is_within_valid_range(args, tax):
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530600 taxes_with_validity.append(tax)
601 else:
mohammadahmad1990e39649b2020-06-18 11:42:53 +0500602 taxes_with_no_validity.append(tax)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530603
604 if taxes_with_validity:
Deepesh Garg6f6928f2023-04-09 09:38:13 +0530605 taxes = sorted(
606 taxes_with_validity, key=lambda i: i.valid_from or tax.maximum_net_rate, reverse=True
607 )
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530608 else:
609 taxes = taxes_with_no_validity
610
611 if for_validate:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530612 return [
613 tax.item_tax_template
614 for tax in taxes
615 if (
616 cstr(tax.tax_category) == cstr(args.get("tax_category"))
617 and (tax.item_tax_template not in taxes)
618 )
619 ]
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530620
621 # all templates have validity and no template is valid
622 if not taxes_with_validity and (not taxes_with_no_validity):
623 return None
624
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530625 # do not change if already a valid template
Ankush Menat494bd9e2022-03-28 18:52:46 +0530626 if args.get("item_tax_template") in {t.item_tax_template for t in taxes}:
627 out["item_tax_template"] = args.get("item_tax_template")
628 return args.get("item_tax_template")
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530629
Saif Ur Rehman67786682018-12-27 02:11:07 +0500630 for tax in taxes:
631 if cstr(tax.tax_category) == cstr(args.get("tax_category")):
632 out["item_tax_template"] = tax.item_tax_template
633 return tax.item_tax_template
634 return None
635
Ankush Menat494bd9e2022-03-28 18:52:46 +0530636
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530637def is_within_valid_range(args, tax):
638 if not flt(tax.maximum_net_rate):
639 # No range specified, just ignore
640 return True
Divyam Mistrye9fe10c2024-02-01 16:15:43 +0530641 elif flt(tax.minimum_net_rate) <= flt(args.get("base_net_rate")) <= flt(tax.maximum_net_rate):
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530642 return True
643
644 return False
645
Ankush Menat494bd9e2022-03-28 18:52:46 +0530646
Saif Ur Rehman67786682018-12-27 02:11:07 +0500647@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500648def get_item_tax_map(company, item_tax_template, as_json=True):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500649 item_tax_map = {}
650 if item_tax_template:
651 template = frappe.get_cached_doc("Item Tax Template", item_tax_template)
652 for d in template.taxes:
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500653 if frappe.get_cached_value("Account", d.tax_type, "company") == company:
654 item_tax_map[d.tax_type] = d.tax_rate
Saif Ur Rehman67786682018-12-27 02:11:07 +0500655
656 return json.dumps(item_tax_map) if as_json else item_tax_map
657
Ankush Menat494bd9e2022-03-28 18:52:46 +0530658
Saif Ur Rehman67786682018-12-27 02:11:07 +0500659@frappe.whitelist()
Zlash6580f5cb02018-08-29 11:39:08 +0530660def calculate_service_end_date(args, item=None):
661 args = process_args(args)
662 if not item:
663 item = frappe.get_cached_doc("Item", args.item_code)
664
Zlash65627be1d2019-01-15 14:16:32 +0530665 doctype = args.get("parenttype") or args.get("doctype")
Zlash65a3dd7982019-01-15 14:36:11 +0530666 if doctype == "Sales Invoice":
667 enable_deferred = "enable_deferred_revenue"
668 no_of_months = "no_of_months"
669 account = "deferred_revenue_account"
670 else:
671 enable_deferred = "enable_deferred_expense"
672 no_of_months = "no_of_months_exp"
673 account = "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530674
Zlash6580f5cb02018-08-29 11:39:08 +0530675 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
Zarrare83ff382018-09-21 15:45:40 +0530676 service_end_date = add_months(service_start_date, item.get(no_of_months))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530677 deferred_detail = {"service_start_date": service_start_date, "service_end_date": service_end_date}
Zarrare83ff382018-09-21 15:45:40 +0530678 deferred_detail[enable_deferred] = item.get(enable_deferred)
679 deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)
Zlash6580f5cb02018-08-29 11:39:08 +0530680
681 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100682
Ankush Menat494bd9e2022-03-28 18:52:46 +0530683
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500684def get_default_income_account(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530685 return (
686 item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530687 or item_group.get("income_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500688 or brand.get("income_account")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530689 or args.income_account
690 )
691
Rushabh Mehta1a763742014-10-03 16:36:43 +0530692
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500693def get_default_expense_account(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530694 return (
695 item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530696 or item_group.get("expense_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500697 or brand.get("expense_account")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530698 or args.expense_account
699 )
700
Rushabh Mehta1a763742014-10-03 16:36:43 +0530701
David Arnold1612d7b2023-10-26 14:03:22 +0200702def get_provisional_account(args, item, item_group, brand):
703 return (
704 item.get("default_provisional_account")
705 or item_group.get("default_provisional_account")
706 or brand.get("default_provisional_account")
707 or args.default_provisional_account
708 )
Deepesh Garg3ce64172022-04-11 14:35:22 +0530709
710
David Arnold1612d7b2023-10-26 14:03:22 +0200711def get_default_discount_account(args, item, item_group, brand):
712 return (
713 item.get("default_discount_account")
714 or item_group.get("default_discount_account")
715 or brand.get("default_discount_account")
716 or args.discount_account
717 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530718
GangaManoj657e9b52021-07-06 16:51:12 +0530719
Zarrare83ff382018-09-21 15:45:40 +0530720def get_default_deferred_account(args, item, fieldname=None):
Zlash65627be1d2019-01-15 14:16:32 +0530721 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530722 return (
Gursheen Kaur Anand099468e2023-09-16 21:25:31 +0530723 frappe.get_cached_value(
724 "Item Default",
725 {"parent": args.item_code, "company": args.get("company")},
726 fieldname,
727 )
Zarrare83ff382018-09-21 15:45:40 +0530728 or args.get(fieldname)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530729 or frappe.get_cached_value("Company", args.company, "default_" + fieldname)
730 )
Manas Solanki03938482018-05-14 16:16:46 +0530731 else:
732 return None
733
Ankush Menat494bd9e2022-03-28 18:52:46 +0530734
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530735def get_default_cost_center(args, item=None, item_group=None, brand=None, company=None):
Nabin Hait50238c32018-08-08 18:43:04 +0530736 cost_center = None
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530737
738 if not company and args.get("company"):
739 company = args.get("company")
740
Ankush Menat494bd9e2022-03-28 18:52:46 +0530741 if args.get("project"):
Nabin Hait50238c32018-08-08 18:43:04 +0530742 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530743
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530744 if not cost_center and (item and item_group and brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530745 if args.get("customer"):
746 cost_center = (
747 item.get("selling_cost_center")
748 or item_group.get("selling_cost_center")
749 or brand.get("selling_cost_center")
750 )
Nabin Hait50238c32018-08-08 18:43:04 +0530751 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530752 cost_center = (
753 item.get("buying_cost_center")
754 or item_group.get("buying_cost_center")
755 or brand.get("buying_cost_center")
756 )
Rushabh Mehta49f97472018-08-30 18:50:48 +0530757
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530758 elif not cost_center and args.get("item_code") and company:
759 for method in ["get_item_defaults", "get_item_group_defaults", "get_brand_defaults"]:
760 path = "erpnext.stock.get_item_details.{0}".format(method)
761 data = frappe.get_attr(path)(args.get("item_code"), company)
762
763 if data and (data.selling_cost_center or data.buying_cost_center):
rohitwaghchaure14b009b2023-10-20 16:22:29 +0530764 if args.get("customer") and data.selling_cost_center:
765 return data.selling_cost_center
766
767 elif args.get("supplier") and data.buying_cost_center:
768 return data.buying_cost_center
769
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530770 return data.selling_cost_center or data.buying_cost_center
771
772 if not cost_center and args.get("cost_center"):
773 cost_center = args.get("cost_center")
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530774
Ankush Menat494bd9e2022-03-28 18:52:46 +0530775 if (
776 company
777 and cost_center
778 and frappe.get_cached_value("Cost Center", cost_center, "company") != company
779 ):
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530780 return None
781
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530782 if not cost_center and company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530783 cost_center = frappe.get_cached_value("Company", company, "cost_center")
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530784
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530785 return cost_center
Rushabh Mehta1a763742014-10-03 16:36:43 +0530786
Ankush Menat494bd9e2022-03-28 18:52:46 +0530787
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500788def get_default_supplier(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530789 return (
790 item.get("default_supplier")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500791 or item_group.get("default_supplier")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530792 or brand.get("default_supplier")
793 )
794
Shreya Shah3c9839f2018-07-17 18:01:44 +0530795
Ankush16d4de52021-08-09 10:41:24 +0530796def get_price_list_rate(args, item_doc, out=None):
797 if out is None:
798 out = frappe._dict()
799
Anand Doshi39a28912016-02-15 11:42:18 +0530800 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530801
Ankush Menat494bd9e2022-03-28 18:52:46 +0530802 if meta.get_field("currency") or args.get("currency"):
Maricae8bc9122021-04-19 11:05:21 +0530803 if not args.get("price_list_currency") or not args.get("plc_conversion_rate"):
804 # if currency and plc_conversion_rate exist then
805 # `get_price_list_currency_and_exchange_rate` has already been called
806 pl_details = get_price_list_currency_and_exchange_rate(args)
807 args.update(pl_details)
808
Nabin Hait06c8cf42019-05-16 19:17:02 +0530809 if meta.get_field("currency"):
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530810 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530811
Ankush16d4de52021-08-09 10:41:24 +0530812 price_list_rate = get_price_list_rate_for(args, item_doc.name)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530813
hiousi1516e292019-01-08 18:34:08 +0100814 # variant
Ankush16d4de52021-08-09 10:41:24 +0530815 if price_list_rate is None and item_doc.variant_of:
hiousi1516e292019-01-08 18:34:08 +0100816 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530817
818 # insert in database
Ankush16d4de52021-08-09 10:41:24 +0530819 if price_list_rate is None:
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530820 if args.price_list and args.rate:
821 insert_item_price(args)
Ankush16d4de52021-08-09 10:41:24 +0530822 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530823
Ankush Menat494bd9e2022-03-28 18:52:46 +0530824 out.price_list_rate = (
825 flt(price_list_rate) * flt(args.plc_conversion_rate) / flt(args.conversion_rate)
826 )
mbauskar287fe812017-04-10 19:15:57 +0530827
Rohit Waghchaured1d46712023-01-09 15:12:46 +0530828 if frappe.db.get_single_value("Buying Settings", "disable_last_purchase_rate"):
829 return out
830
Ankush Menat494bd9e2022-03-28 18:52:46 +0530831 if not out.price_list_rate and args.transaction_type == "buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530832 from erpnext.stock.doctype.item.item import get_last_purchase_details
Ankush Menat494bd9e2022-03-28 18:52:46 +0530833
834 out.update(get_last_purchase_details(item_doc.name, args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530835
Ankush16d4de52021-08-09 10:41:24 +0530836 return out
837
Ankush Menat494bd9e2022-03-28 18:52:46 +0530838
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530839def insert_item_price(args):
840 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530841 if frappe.db.get_value(
842 "Price List", args.price_list, "currency", cache=True
843 ) == args.currency and cint(
844 frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")
845 ):
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530846 if frappe.has_permission("Item Price", "write"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530847 price_list_rate = (
Rohit Waghchaure0f280742022-12-15 16:34:06 +0530848 (flt(args.rate) + flt(args.discount_amount)) / args.get("conversion_factor")
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530849 if args.get("conversion_factor")
Rohit Waghchaure0f280742022-12-15 16:34:06 +0530850 else (flt(args.rate) + flt(args.discount_amount))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530851 )
Rushabh Mehta985cb822016-12-30 15:06:54 +0530852
Ankush Menat494bd9e2022-03-28 18:52:46 +0530853 item_price = frappe.db.get_value(
854 "Item Price",
855 {"item_code": args.item_code, "price_list": args.price_list, "currency": args.currency},
856 ["name", "price_list_rate"],
857 as_dict=1,
858 )
Nabin Haitb479a872018-09-07 13:17:11 +0530859 if item_price and item_price.name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530860 if item_price.price_list_rate != price_list_rate and frappe.db.get_single_value(
861 "Stock Settings", "update_existing_price_list_rate"
862 ):
863 frappe.db.set_value("Item Price", item_price.name, "price_list_rate", price_list_rate)
864 frappe.msgprint(
865 _("Item Price updated for {0} in Price List {1}").format(args.item_code, args.price_list),
866 alert=True,
867 )
Rushabh Mehta985cb822016-12-30 15:06:54 +0530868 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530869 item_price = frappe.get_doc(
870 {
871 "doctype": "Item Price",
872 "price_list": args.price_list,
873 "item_code": args.item_code,
874 "currency": args.currency,
875 "price_list_rate": price_list_rate,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530876 "uom": args.stock_uom,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530877 }
878 )
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530879 item_price.insert()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530880 frappe.msgprint(
881 _("Item Price added for {0} in Price List {1}").format(args.item_code, args.price_list),
882 alert=True,
883 )
884
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530885
Nabin Hait01ca3e52019-01-25 16:25:15 +0530886def get_item_price(args, item_code, ignore_party=False):
Nabin Haite45ec662018-08-01 17:44:34 +0530887 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530888 Get name, price_list_rate from Item Price based on conditions
889 Check if the desired qty is within the increment of the packing list.
890 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
891 optional fields transaction_date, customer, supplier
892 :param item_code: str, Item Doctype field item_code
Nabin Haite45ec662018-08-01 17:44:34 +0530893 """
894
s-aga-r6b144ba2023-02-18 12:18:41 +0530895 ip = frappe.qb.DocType("Item Price")
896 query = (
897 frappe.qb.from_(ip)
898 .select(ip.name, ip.price_list_rate, ip.uom)
899 .where(
900 (ip.item_code == item_code)
901 & (ip.price_list == args.get("price_list"))
902 & (IfNull(ip.uom, "").isin(["", args.get("uom")]))
903 & (IfNull(ip.batch_no, "").isin(["", args.get("batch_no")]))
904 )
905 .orderby(ip.valid_from, order=frappe.qb.desc)
906 .orderby(IfNull(ip.batch_no, ""), order=frappe.qb.desc)
907 .orderby(ip.uom, order=frappe.qb.desc)
908 )
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530909
Nabin Hait01ca3e52019-01-25 16:25:15 +0530910 if not ignore_party:
Nabin Hait01ca3e52019-01-25 16:25:15 +0530911 if args.get("customer"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530912 query = query.where(ip.customer == args.get("customer"))
Nabin Hait4e456632019-01-29 14:02:08 +0530913 elif args.get("supplier"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530914 query = query.where(ip.supplier == args.get("supplier"))
Nabin Hait4e456632019-01-29 14:02:08 +0530915 else:
s-aga-r6b144ba2023-02-18 12:18:41 +0530916 query = query.where((IfNull(ip.customer, "") == "") & (IfNull(ip.supplier, "") == ""))
Nabin Hait01ca3e52019-01-25 16:25:15 +0530917
Ankush Menat494bd9e2022-03-28 18:52:46 +0530918 if args.get("transaction_date"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530919 query = query.where(
920 (IfNull(ip.valid_from, "2000-01-01") <= args["transaction_date"])
921 & (IfNull(ip.valid_upto, "2500-12-31") >= args["transaction_date"])
922 )
Deepesh Gargf15ff5f2020-07-11 13:58:53 +0530923
s-aga-r6b144ba2023-02-18 12:18:41 +0530924 return query.run()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530925
Nabin Haite45ec662018-08-01 17:44:34 +0530926
927def get_price_list_rate_for(args, item_code):
928 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530929 :param customer: link to Customer DocType
930 :param supplier: link to Supplier DocType
931 :param price_list: str (Standard Buying or Standard Selling)
932 :param item_code: str, Item Doctype field item_code
933 :param qty: Desired Qty
934 :param transaction_date: Date of the price
Nabin Haite45ec662018-08-01 17:44:34 +0530935 """
936 item_price_args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530937 "item_code": item_code,
938 "price_list": args.get("price_list"),
939 "customer": args.get("customer"),
940 "supplier": args.get("supplier"),
941 "uom": args.get("uom"),
942 "transaction_date": args.get("transaction_date"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530943 "batch_no": args.get("batch_no"),
Nabin Haite45ec662018-08-01 17:44:34 +0530944 }
945
946 item_price_data = 0
947 price_list_rate = get_item_price(item_price_args, item_code)
948 if price_list_rate:
949 desired_qty = args.get("qty")
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530950 if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
Nabin Haite45ec662018-08-01 17:44:34 +0530951 item_price_data = price_list_rate
952 else:
Don-Leopardoccdf1932020-01-09 03:54:43 -0300953 for field in ["customer", "supplier"]:
Nabin Haite45ec662018-08-01 17:44:34 +0530954 del item_price_args[field]
955
Ankush Menat494bd9e2022-03-28 18:52:46 +0530956 general_price_list_rate = get_item_price(
957 item_price_args, item_code, ignore_party=args.get("ignore_party")
958 )
Don-Leopardoccdf1932020-01-09 03:54:43 -0300959
Nabin Haite45ec662018-08-01 17:44:34 +0530960 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530961 item_price_args["uom"] = args.get("stock_uom")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530962 general_price_list_rate = get_item_price(
963 item_price_args, item_code, ignore_party=args.get("ignore_party")
964 )
Nabin Haite45ec662018-08-01 17:44:34 +0530965
966 if general_price_list_rate:
967 item_price_data = general_price_list_rate
968
969 if item_price_data:
970 if item_price_data[0][2] == args.get("uom"):
971 return item_price_data[0][1]
Ankush Menat494bd9e2022-03-28 18:52:46 +0530972 elif not args.get("price_list_uom_dependant"):
Nabin Haite45ec662018-08-01 17:44:34 +0530973 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
974 else:
975 return item_price_data[0][1]
976
Ankush Menat494bd9e2022-03-28 18:52:46 +0530977
Nabin Haite45ec662018-08-01 17:44:34 +0530978def check_packing_list(price_list_rate_name, desired_qty, item_code):
979 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530980 Check if the desired qty is within the increment of the packing list.
981 :param price_list_rate_name: Name of Item Price
982 :param desired_qty: Desired Qt
983 :param item_code: str, Item Doctype field item_code
984 :param qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530985 """
986
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530987 flag = True
Nabin Haite45ec662018-08-01 17:44:34 +0530988 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530989 if item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +0530990 packing_increment = desired_qty % item_price.packing_unit
991
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530992 if packing_increment != 0:
993 flag = False
994
995 return flag
Rushabh Mehta1a763742014-10-03 16:36:43 +0530996
Ankush Menat494bd9e2022-03-28 18:52:46 +0530997
Nabin Hait436f5262014-02-10 14:47:54 +0530998def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +0530999 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +05301000
Ankush Menat494bd9e2022-03-28 18:52:46 +05301001 company_currency = frappe.get_cached_value("Company", args.company, "default_currency")
1002 if not args.conversion_rate and args.currency == company_currency:
Anand Doshife13bfe2015-08-25 12:49:40 +05301003 args.conversion_rate = 1.0
1004
Ankush Menat494bd9e2022-03-28 18:52:46 +05301005 if (
1006 not args.ignore_conversion_rate
1007 and args.conversion_rate == 1
1008 and args.currency != company_currency
1009 ):
1010 args.conversion_rate = (
1011 get_exchange_rate(args.currency, company_currency, args.transaction_date, "for_buying") or 1.0
1012 )
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +05301013
Nabin Hait436f5262014-02-10 14:47:54 +05301014 # validate currency conversion rate
Ankush Menat494bd9e2022-03-28 18:52:46 +05301015 validate_conversion_rate(
1016 args.currency, args.conversion_rate, meta.get_label("conversion_rate"), args.company
1017 )
Anand Doshibd67e872014-04-11 16:51:27 +05301018
Ankush Menat494bd9e2022-03-28 18:52:46 +05301019 args.conversion_rate = flt(
1020 args.conversion_rate,
1021 get_field_precision(meta.get_field("conversion_rate"), frappe._dict({"fields": args})),
1022 )
Anand Doshibd67e872014-04-11 16:51:27 +05301023
Nabin Hait06c8cf42019-05-16 19:17:02 +05301024 if args.price_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301025 if not args.plc_conversion_rate and args.price_list_currency == frappe.db.get_value(
1026 "Price List", args.price_list, "currency", cache=True
1027 ):
Nabin Hait06c8cf42019-05-16 19:17:02 +05301028 args.plc_conversion_rate = 1.0
Manas Solanki3504a232018-06-06 12:46:06 +05301029
Nabin Hait06c8cf42019-05-16 19:17:02 +05301030 # validate price list currency conversion rate
1031 if not args.get("price_list_currency"):
1032 throw(_("Price List Currency not selected"))
1033 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301034 validate_conversion_rate(
1035 args.price_list_currency,
1036 args.plc_conversion_rate,
1037 meta.get_label("plc_conversion_rate"),
1038 args.company,
1039 )
Anand Doshibd67e872014-04-11 16:51:27 +05301040
Nabin Hait06c8cf42019-05-16 19:17:02 +05301041 if meta.get_field("plc_conversion_rate"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301042 args.plc_conversion_rate = flt(
1043 args.plc_conversion_rate,
1044 get_field_precision(meta.get_field("plc_conversion_rate"), frappe._dict({"fields": args})),
1045 )
1046
Anand Doshibd67e872014-04-11 16:51:27 +05301047
Rushabh Mehtaf14b8092014-04-03 14:30:42 +05301048def get_party_item_code(args, item_doc, out):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301049 if args.transaction_type == "selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +05301050 out.customer_item_code = None
Nabin Hait34c551d2019-07-03 10:34:31 +05301051
Ankush Menat494bd9e2022-03-28 18:52:46 +05301052 if args.quotation_to and args.quotation_to != "Customer":
Nabin Hait34c551d2019-07-03 10:34:31 +05301053 return
1054
Nabin Hait79f091e2014-12-26 11:41:15 +05301055 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +05301056
1057 if customer_item_code:
1058 out.customer_item_code = customer_item_code[0].ref_code
1059 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +05301060 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +05301061 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
1062 if customer_group_item_code and not customer_group_item_code[0].customer_name:
1063 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +05301064
Ankush Menat494bd9e2022-03-28 18:52:46 +05301065 if args.transaction_type == "buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +05301066 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +05301067 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +05301068
Ankush Menat494bd9e2022-03-28 18:52:46 +05301069
rohitwaghchaure2ea593b2018-04-12 13:37:08 +05301070def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301071 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +05301072
Rushabh Mehta708e47a2018-08-08 16:37:31 +05301073 if not frappe.flags.pos_profile and not pos_profile:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301074 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get("pos_profile"))
Anand Doshibd67e872014-04-11 16:51:27 +05301075
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301076 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +05301077 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +05301078 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301079 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +05301080
Nabin Hait436f5262014-02-10 14:47:54 +05301081 if res.get("warehouse"):
s-aga-rc716dcc2022-12-29 12:34:18 +05301082 res.actual_qty = get_bin_details(
1083 args.item_code, res.warehouse, include_child_warehouses=True
1084 ).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +05301085
Nabin Hait436f5262014-02-10 14:47:54 +05301086 return res
1087
Ankush Menat494bd9e2022-03-28 18:52:46 +05301088
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301089@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301090def get_pos_profile(company, pos_profile=None, user=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301091 if pos_profile:
1092 return frappe.get_cached_doc("POS Profile", pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301093
1094 if not user:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301095 user = frappe.session["user"]
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301096
s-aga-r6b144ba2023-02-18 12:18:41 +05301097 pf = frappe.qb.DocType("POS Profile")
1098 pfu = frappe.qb.DocType("POS Profile User")
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301099
s-aga-r6b144ba2023-02-18 12:18:41 +05301100 query = (
1101 frappe.qb.from_(pf)
1102 .left_join(pfu)
1103 .on(pf.name == pfu.parent)
1104 .select(pf.star)
1105 .where((pfu.user == user) & (pfu.default == 1))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301106 )
Anand Doshibd67e872014-04-11 16:51:27 +05301107
s-aga-r6b144ba2023-02-18 12:18:41 +05301108 if company:
1109 query = query.where(pf.company == company)
1110
1111 pos_profile = query.run(as_dict=True)
1112
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301113 if not pos_profile and company:
s-aga-r6b144ba2023-02-18 12:18:41 +05301114 pos_profile = (
1115 frappe.qb.from_(pf)
1116 .left_join(pfu)
1117 .on(pf.name == pfu.parent)
1118 .select(pf.star)
1119 .where((pf.company == company) & (pf.disabled == 0))
1120 ).run(as_dict=True)
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301121
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301122 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +05301123
Ankush Menat494bd9e2022-03-28 18:52:46 +05301124
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301125@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +05301126def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +05301127 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +05301128 filters = {"parent": item_code, "uom": uom}
s-aga-r58c027d2023-02-28 15:14:34 +05301129
Rushabh Mehta724f9e52014-10-07 15:29:58 +05301130 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +05301131 filters["parent"] = ("in", (item_code, variant_of))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301132 conversion_factor = frappe.db.get_value("UOM Conversion Detail", filters, "conversion_factor")
Sagar Vora508189e2018-09-11 17:22:25 +05301133 if not conversion_factor:
1134 stock_uom = frappe.db.get_value("Item", item_code, "stock_uom")
1135 conversion_factor = get_uom_conv_factor(uom, stock_uom)
s-aga-r6b144ba2023-02-18 12:18:41 +05301136
rohitwaghchaureffdadbf2019-01-08 16:21:25 +05301137 return {"conversion_factor": conversion_factor or 1.0}
Nabin Hait08222152014-02-28 11:30:47 +05301138
Ankush Menat494bd9e2022-03-28 18:52:46 +05301139
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301140@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +05301141def get_projected_qty(item_code, warehouse):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301142 return {
1143 "projected_qty": frappe.db.get_value(
1144 "Bin", {"item_code": item_code, "warehouse": warehouse}, "projected_qty"
1145 )
1146 }
1147
Nabin Hait08222152014-02-28 11:30:47 +05301148
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301149@frappe.whitelist()
s-aga-rc716dcc2022-12-29 12:34:18 +05301150def get_bin_details(item_code, warehouse, company=None, include_child_warehouses=False):
ruthra kumarbe382052023-01-16 08:50:39 +05301151 bin_details = {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
s-aga-rc716dcc2022-12-29 12:34:18 +05301152
1153 if warehouse:
s-aga-rc3911a52022-12-29 16:38:08 +05301154 from frappe.query_builder.functions import Coalesce, Sum
s-aga-r58c027d2023-02-28 15:14:34 +05301155
s-aga-rc716dcc2022-12-29 12:34:18 +05301156 from erpnext.stock.doctype.warehouse.warehouse import get_child_warehouses
1157
1158 warehouses = get_child_warehouses(warehouse) if include_child_warehouses else [warehouse]
s-aga-rc3911a52022-12-29 16:38:08 +05301159
1160 bin = frappe.qb.DocType("Bin")
1161 bin_details = (
1162 frappe.qb.from_(bin)
1163 .select(
1164 Coalesce(Sum(bin.projected_qty), 0).as_("projected_qty"),
1165 Coalesce(Sum(bin.actual_qty), 0).as_("actual_qty"),
1166 Coalesce(Sum(bin.reserved_qty), 0).as_("reserved_qty"),
1167 )
1168 .where((bin.item_code == item_code) & (bin.warehouse.isin(warehouses)))
1169 ).run(as_dict=True)[0]
s-aga-rc716dcc2022-12-29 12:34:18 +05301170
Anupam4980dd62021-03-15 11:37:46 +05301171 if company:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301172 bin_details["company_total_stock"] = get_company_total_stock(item_code, company)
s-aga-rb425c2d2023-01-02 11:25:13 +05301173
Anupam4980dd62021-03-15 11:37:46 +05301174 return bin_details
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301175
Ankush Menat494bd9e2022-03-28 18:52:46 +05301176
Anupam4980dd62021-03-15 11:37:46 +05301177def get_company_total_stock(item_code, company):
s-aga-r6b144ba2023-02-18 12:18:41 +05301178 bin = frappe.qb.DocType("Bin")
1179 wh = frappe.qb.DocType("Warehouse")
1180
1181 return (
1182 frappe.qb.from_(bin)
1183 .inner_join(wh)
1184 .on(bin.warehouse == wh.name)
1185 .select(Sum(bin.actual_qty))
1186 .where((wh.company == company) & (bin.item_code == item_code))
1187 ).run()[0][0]
Ankush Menat494bd9e2022-03-28 18:52:46 +05301188
Anupam4980dd62021-03-15 11:37:46 +05301189
1190@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +05301191def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +07001192 from erpnext.stock.doctype.batch import batch
Ankush Menat494bd9e2022-03-28 18:52:46 +05301193
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +05301194 if batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301195 return {"actual_batch_qty": batch.get_batch_qty(batch_no, warehouse)}
1196
Rushabh Mehta1e8025b2015-07-24 15:16:25 +05301197
Anand Doshidffec8f2014-07-01 17:45:15 +05301198@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301199def apply_price_list(args, as_doc=False):
1200 """Apply pricelist on a document-like dict object and return as
1201 {'parent': dict, 'children': list}
1202
1203 :param args: See below
1204 :param as_doc: Updates value in the passed dict
1205
Ankush Menat494bd9e2022-03-28 18:52:46 +05301206 args = {
1207 "doctype": "",
1208 "name": "",
1209 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
1210 "conversion_rate": 1.0,
1211 "selling_price_list": None,
1212 "price_list_currency": None,
1213 "price_list_uom_dependant": None,
1214 "plc_conversion_rate": 1.0,
1215 "doctype": "",
1216 "name": "",
1217 "supplier": None,
1218 "transaction_date": None,
1219 "conversion_rate": 1.0,
1220 "buying_price_list": None,
1221 "ignore_pricing_rule": 0/1
1222 }
Anand Doshidffec8f2014-07-01 17:45:15 +05301223 """
1224 args = process_args(args)
1225
1226 parent = get_price_list_currency_and_exchange_rate(args)
Maricae8bc9122021-04-19 11:05:21 +05301227 args.update(parent)
1228
Anand Doshidffec8f2014-07-01 17:45:15 +05301229 children = []
1230
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301231 if "items" in args:
1232 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +05301233 args.update(parent)
1234
1235 for item in item_list:
1236 args_copy = frappe._dict(args.copy())
1237 args_copy.update(item)
1238 item_details = apply_price_list_on_item(args_copy)
1239 children.append(item_details)
1240
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301241 if as_doc:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301242 args.price_list_currency = (parent.price_list_currency,)
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301243 args.plc_conversion_rate = parent.plc_conversion_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +05301244 if args.get("items"):
1245 for i, item in enumerate(args.get("items")):
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301246 for fieldname in children[i]:
1247 # if the field exists in the original doc
1248 # update the value
1249 if fieldname in item and fieldname not in ("name", "doctype"):
1250 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301251 return args
1252 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301253 return {"parent": parent, "children": children}
1254
Anand Doshidffec8f2014-07-01 17:45:15 +05301255
1256def apply_price_list_on_item(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301257 item_doc = frappe.db.get_value("Item", args.item_code, ["name", "variant_of"], as_dict=1)
Ankush16d4de52021-08-09 10:41:24 +05301258 item_details = get_price_list_rate(args, item_doc)
Deepesh Gargb741ae12022-12-02 17:14:06 +05301259 item_details.update(get_pricing_rule_for_item(args))
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301260
Anand Doshidffec8f2014-07-01 17:45:15 +05301261 return item_details
1262
Ankush Menat494bd9e2022-03-28 18:52:46 +05301263
Anand Doshidffec8f2014-07-01 17:45:15 +05301264def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +05301265 if not args.price_list:
1266 return {}
1267
Ankush Menat494bd9e2022-03-28 18:52:46 +05301268 if args.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
Shreya3f778522018-05-15 16:59:20 +05301269 args.update({"exchange_rate": "for_selling"})
Ankush Menat494bd9e2022-03-28 18:52:46 +05301270 elif args.doctype in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]:
Shreya3f778522018-05-15 16:59:20 +05301271 args.update({"exchange_rate": "for_buying"})
1272
rohitwaghchaurea85ddf22019-11-19 18:47:48 +05301273 price_list_details = get_price_list_details(args.price_list)
1274
1275 price_list_currency = price_list_details.get("currency")
1276 price_list_uom_dependant = price_list_details.get("price_list_uom_dependant")
1277
Anand Doshidffec8f2014-07-01 17:45:15 +05301278 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +01001279 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +05301280
Ankush Menat494bd9e2022-03-28 18:52:46 +05301281 if (not plc_conversion_rate) or (
1282 price_list_currency
1283 and args.price_list_currency
1284 and price_list_currency != args.price_list_currency
1285 ):
1286 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
1287 plc_conversion_rate = (
1288 get_exchange_rate(
1289 price_list_currency, company_currency, args.transaction_date, args.exchange_rate
1290 )
1291 or plc_conversion_rate
1292 )
Anand Doshidffec8f2014-07-01 17:45:15 +05301293
Ankush Menat494bd9e2022-03-28 18:52:46 +05301294 return frappe._dict(
1295 {
1296 "price_list_currency": price_list_currency,
1297 "price_list_uom_dependant": price_list_uom_dependant,
1298 "plc_conversion_rate": plc_conversion_rate or 1,
1299 }
1300 )
1301
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +05301302
1303@frappe.whitelist()
1304def get_default_bom(item_code=None):
marination9f2d3252022-06-14 17:20:44 +05301305 def _get_bom(item):
1306 bom = frappe.get_all(
1307 "BOM", dict(item=item, is_active=True, is_default=True, docstatus=1), limit=1
Ankush Menat494bd9e2022-03-28 18:52:46 +05301308 )
marination9f2d3252022-06-14 17:20:44 +05301309 return bom[0].name if bom else None
1310
1311 if not item_code:
1312 return
1313
1314 bom_name = _get_bom(item_code)
1315
1316 template_item = frappe.db.get_value("Item", item_code, "variant_of")
1317 if not bom_name and template_item:
1318 bom_name = _get_bom(template_item)
1319
1320 return bom_name
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301321
Ankush Menat494bd9e2022-03-28 18:52:46 +05301322
Deepesh Garg15ff6a52020-02-18 12:28:41 +05301323@frappe.whitelist()
Manas Solanki087a2252018-05-04 16:02:38 +05301324def get_valuation_rate(item_code, company, warehouse=None):
rohitwaghchauree6199dc2023-09-20 17:27:35 +05301325 if frappe.get_cached_value("Warehouse", warehouse, "is_group"):
1326 return {"valuation_rate": 0.0}
1327
Manas Solankib16a4ec2018-05-04 16:49:33 +05301328 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +05301329 item_group = get_item_group_defaults(item_code, company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001330 brand = get_brand_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +05301331 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +05301332 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +05301333 if not warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301334 warehouse = (
1335 item.get("default_warehouse")
1336 or item_group.get("default_warehouse")
1337 or brand.get("default_warehouse")
1338 )
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301339
Ankush Menat494bd9e2022-03-28 18:52:46 +05301340 return frappe.db.get_value(
1341 "Bin", {"item_code": item_code, "warehouse": warehouse}, ["valuation_rate"], as_dict=True
1342 ) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301343
Manas Solankie3910fb2018-05-16 15:50:17 +05301344 elif not item.get("is_stock_item"):
s-aga-r6b144ba2023-02-18 12:18:41 +05301345 pi_item = frappe.qb.DocType("Purchase Invoice Item")
1346 valuation_rate = (
1347 frappe.qb.from_(pi_item)
1348 .select((Sum(pi_item.base_net_amount) / Sum(pi_item.qty * pi_item.conversion_factor)))
s-aga-r58c027d2023-02-28 15:14:34 +05301349 .where((pi_item.docstatus == 1) & (pi_item.item_code == item_code))
s-aga-r6b144ba2023-02-18 12:18:41 +05301350 ).run()
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301351
Saurabhbd01a812016-03-07 14:32:23 +05301352 if valuation_rate:
1353 return {"valuation_rate": valuation_rate[0][0] or 0.0}
1354 else:
1355 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301356
Ankush Menat494bd9e2022-03-28 18:52:46 +05301357
Saurabh2d7af632016-02-26 11:09:20 +05301358def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +05301359 if out.valuation_rate:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301360 out.update({"gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)})
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301361
Saurabhd3135532016-02-25 18:59:20 +05301362 return out
mbauskar6f603392016-01-21 16:10:22 +05301363
Ankush Menat494bd9e2022-03-28 18:52:46 +05301364
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301365@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301366def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaure648efca2023-03-28 12:16:27 +05301367 serial_nos = serial_nos or []
1368 return serial_nos
Manas Solankie5e87f72018-05-28 20:07:08 +05301369
1370
1371def update_party_blanket_order(args, out):
ronelvcabrera370cdc02019-12-04 18:37:11 +08001372 if out["against_blanket_order"]:
1373 blanket_order_details = get_blanket_order_details(args)
1374 if blanket_order_details:
1375 out.update(blanket_order_details)
Manas Solankie5e87f72018-05-28 20:07:08 +05301376
Ankush Menat494bd9e2022-03-28 18:52:46 +05301377
Manas Solankie5e87f72018-05-28 20:07:08 +05301378@frappe.whitelist()
1379def get_blanket_order_details(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301380 if isinstance(args, str):
Manas Solankie5e87f72018-05-28 20:07:08 +05301381 args = frappe._dict(json.loads(args))
1382
1383 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +05301384
s-aga-r6b144ba2023-02-18 12:18:41 +05301385 if args.item_code:
1386 bo = frappe.qb.DocType("Blanket Order")
1387 bo_item = frappe.qb.DocType("Blanket Order Item")
1388
1389 query = (
1390 frappe.qb.from_(bo)
1391 .from_(bo_item)
1392 .select(bo_item.rate.as_("blanket_order_rate"), bo.name.as_("blanket_order"))
1393 .where(
1394 (bo.company == args.company)
1395 & (bo_item.item_code == args.item_code)
1396 & (bo.docstatus == 1)
1397 & (bo.name == bo_item.parent)
1398 )
Ankush Menat494bd9e2022-03-28 18:52:46 +05301399 )
Nabin Hait2737b082018-06-14 18:07:22 +05301400
s-aga-r6b144ba2023-02-18 12:18:41 +05301401 if args.customer and args.doctype == "Sales Order":
1402 query = query.where(bo.customer == args.customer)
1403 elif args.supplier and args.doctype == "Purchase Order":
1404 query = query.where(bo.supplier == args.supplier)
1405 if args.blanket_order:
1406 query = query.where(bo.name == args.blanket_order)
1407 if args.transaction_date:
1408 query = query.where(bo.to_date >= args.transaction_date)
1409
1410 blanket_order_details = query.run(as_dict=True)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301411 blanket_order_details = blanket_order_details[0] if blanket_order_details else ""
s-aga-r6b144ba2023-02-18 12:18:41 +05301412
Manas Solankie5e87f72018-05-28 20:07:08 +05301413 return blanket_order_details