blob: 019be8a25639a6dc7908eecc7a8b5fe7f441f52b [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
Nabin Hait26202d92024-03-13 18:17:41 +0530106 if item.is_stock_item:
107 update_bin_details(args, out, doc)
Anand Doshibd67e872014-04-11 16:51:27 +0530108
Nabin Haita3dd72a2014-05-28 12:49:20 +0530109 # update args with out, if key or value not exists
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530110 for key, value in out.items():
Nabin Haita3dd72a2014-05-28 12:49:20 +0530111 if args.get(key) is None:
112 args[key] = value
113
Deepesh Garg6192af52022-12-08 18:04:40 +0530114 data = get_pricing_rule_for_item(args, doc=doc, for_validate=for_validate)
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530115
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530116 out.update(data)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530117
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530118 if args.transaction_date and item.lead_time_days:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530119 out.schedule_date = out.lead_time_date = add_days(args.transaction_date, item.lead_time_days)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530120
Sagar Sharma409df262022-04-19 14:57:31 +0530121 if args.get("is_subcontracted"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530122 out.bom = args.get("bom") or get_default_bom(args.item_code)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530123
124 get_gross_profit(out)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530125 if args.doctype == "Material Request":
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530126 out.rate = args.rate or out.price_list_rate
Rohit Waghchaure1bc53a32021-03-31 15:28:26 +0530127 out.amount = flt(args.qty) * flt(out.rate)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530128
Ankush Menat1e976642022-02-15 10:57:06 +0530129 out = remove_standard_fields(out)
Deepesh Garga7051cb2023-04-14 09:59:42 +0530130 return out
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530131
Ankush Menat494bd9e2022-03-28 18:52:46 +0530132
Ankush Menat1e976642022-02-15 10:57:06 +0530133def remove_standard_fields(details):
134 for key in child_table_fields + default_fields:
135 details.pop(key, None)
136 return details
137
138
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530139def set_valuation_rate(out, args):
Gursheen Anand8bdb61c2023-11-22 16:17:23 +0530140 if frappe.db.exists("Product Bundle", {"name": args.item_code, "disabled": 0}, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530141 valuation_rate = 0.0
142 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530143
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530144 for bundle_item in bundled_items.items:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530145 valuation_rate += flt(
146 get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get(
147 "valuation_rate"
148 )
149 * bundle_item.qty
150 )
Anand Doshi70f57eb2015-11-27 14:37:40 +0530151
Ankush Menat494bd9e2022-03-28 18:52:46 +0530152 out.update({"valuation_rate": valuation_rate})
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530153
154 else:
155 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
156
Nabin Hait436f5262014-02-10 14:47:54 +0530157
Nabin Hait26202d92024-03-13 18:17:41 +0530158def update_bin_details(args, out, doc):
159 if (
160 args.get("doctype") == "Material Request"
161 and args.get("material_request_type") == "Material Transfer"
162 ):
163 out.update(get_bin_details(args.item_code, args.get("from_warehouse")))
164
165 elif out.get("warehouse"):
166 company = args.company if (doc and doc.get("doctype") == "Purchase Order") else None
167
168 # calculate company_total_stock only for po
169 bin_details = get_bin_details(
170 args.item_code, out.warehouse, company, include_child_warehouses=True
171 )
172
173 out.update(bin_details)
174
175
Anand Doshidffec8f2014-07-01 17:45:15 +0530176def process_args(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530177 if isinstance(args, str):
Anand Doshidffec8f2014-07-01 17:45:15 +0530178 args = json.loads(args)
179
180 args = frappe._dict(args)
181
Anand Doshidffec8f2014-07-01 17:45:15 +0530182 if not args.get("price_list"):
183 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
184
Devin Slauenwhite55276f12022-05-25 00:05:22 -0400185 if not args.item_code and args.barcode:
Anand Doshidffec8f2014-07-01 17:45:15 +0530186 args.item_code = get_item_code(barcode=args.barcode)
187 elif not args.item_code and args.serial_no:
188 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530189
mbauskar6f603392016-01-21 16:10:22 +0530190 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530191 return args
192
Ankush Menat494bd9e2022-03-28 18:52:46 +0530193
marination392f3232020-07-14 17:03:17 +0530194def process_string_args(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530195 if isinstance(args, str):
marination392f3232020-07-14 17:03:17 +0530196 args = json.loads(args)
197 return args
tundebabzyacccdb32017-11-23 08:35:15 +0100198
Ankush Menat494bd9e2022-03-28 18:52:46 +0530199
Nabin Hait436f5262014-02-10 14:47:54 +0530200def get_item_code(barcode=None, serial_no=None):
201 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100202 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530203 if not item_code:
204 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530205 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530206 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530207 if not item_code:
208 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530209
Nabin Hait436f5262014-02-10 14:47:54 +0530210 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530211
tundebabzyacccdb32017-11-23 08:35:15 +0100212
Nabin Hait436f5262014-02-10 14:47:54 +0530213def validate_item_details(args, item):
214 if not args.company:
215 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530216
Nabin Hait436f5262014-02-10 14:47:54 +0530217 from erpnext.stock.doctype.item.item import validate_end_of_life
Ankush Menat494bd9e2022-03-28 18:52:46 +0530218
Anand Doshi21e09a22015-10-29 12:21:41 +0530219 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530220
Rohit Waghchaure2c83fff2023-01-18 23:21:29 +0530221 if cint(item.has_variants):
222 msg = f"Item {item.name} is a template, please select one of its variants"
223
224 throw(_(msg), title=_("Template Item Selected"))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530225
tundebabzyacccdb32017-11-23 08:35:15 +0100226 elif args.transaction_type == "buying" and args.doctype != "Material Request":
s-aga-r6d89b2f2022-06-18 15:46:59 +0530227 if args.get("is_subcontracted"):
228 if args.get("is_old_subcontracting_flow"):
229 if item.is_sub_contracted_item != 1:
230 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
231 else:
232 if item.is_stock_item:
233 throw(_("Item {0} must be a Non-Stock Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530234
tundebabzyacccdb32017-11-23 08:35:15 +0100235
Suraj Shetty182f4de2019-08-16 08:16:22 +0530236def get_basic_details(args, item, overwrite_warehouse=True):
tundebabzyacccdb32017-11-23 08:35:15 +0100237 """
238 :param args: {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530239 "item_code": "",
240 "warehouse": None,
241 "customer": "",
242 "conversion_rate": 1.0,
243 "selling_price_list": None,
244 "price_list_currency": None,
245 "price_list_uom_dependant": None,
246 "plc_conversion_rate": 1.0,
247 "doctype": "",
248 "name": "",
249 "supplier": None,
250 "transaction_date": None,
251 "conversion_rate": 1.0,
252 "buying_price_list": None,
Sagar Sharma409df262022-04-19 14:57:31 +0530253 "is_subcontracted": 0/1,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530254 "ignore_pricing_rule": 0/1
255 "project": "",
256 barcode: "",
257 serial_no: "",
258 currency: "",
259 update_stock: "",
260 price_list: "",
261 company: "",
262 order_type: "",
263 is_pos: "",
264 project: "",
265 qty: "",
266 stock_qty: "",
267 conversion_factor: "",
268 against_blanket_order: 0/1
269 }
tundebabzyacccdb32017-11-23 08:35:15 +0100270 :param item: `item_code` of Item object
271 :return: frappe._dict
272 """
273
Rushabh Mehta1a763742014-10-03 16:36:43 +0530274 if not item:
275 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530276
Rohit Waghchaure951023f2024-01-31 11:32:17 +0530277 if (
278 item.variant_of and not item.taxes and frappe.db.exists("Item Tax", {"parent": item.variant_of})
279 ):
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530280 item.update_template_tables()
281
Manas Solankib16a4ec2018-05-04 16:49:33 +0530282 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530283 item_group_defaults = get_item_group_defaults(item.name, args.company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500284 brand_defaults = get_brand_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530285
Ankush Menat494bd9e2022-03-28 18:52:46 +0530286 defaults = frappe._dict(
287 {
288 "item_defaults": item_defaults,
289 "item_group_defaults": item_group_defaults,
290 "brand_defaults": brand_defaults,
291 }
292 )
marinatione05013e2020-04-06 22:13:13 +0530293
Saqib438e0432020-04-03 10:02:56 +0530294 warehouse = get_item_warehouse(item, args, overwrite_warehouse, defaults)
Nabin Hait36028bf2014-02-12 19:09:28 +0530295
Ankush Menat494bd9e2022-03-28 18:52:46 +0530296 if args.get("doctype") == "Material Request" and not args.get("material_request_type"):
297 args["material_request_type"] = frappe.db.get_value(
298 "Material Request", args.get("name"), "material_request_type", cache=True
299 )
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530300
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530301 expense_account = None
302
Ankush Menat494bd9e2022-03-28 18:52:46 +0530303 if args.get("doctype") == "Purchase Invoice" and item.is_fixed_asset:
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530304 from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530305
Ankush Menat494bd9e2022-03-28 18:52:46 +0530306 expense_account = get_asset_category_account(
307 fieldname="fixed_asset_account", item=args.item_code, company=args.company
308 )
309
310 # Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
311 if not args.get("uom"):
312 if args.get("doctype") in sales_doctypes:
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530313 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
Ankush Menat494bd9e2022-03-28 18:52:46 +0530314 elif (args.get("doctype") in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]) or (
315 args.get("doctype") == "Material Request" and args.get("material_request_type") == "Purchase"
316 ):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530317 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
318 else:
319 args.uom = item.stock_uom
320
Sagar Vora57038c32022-11-09 18:56:09 +0530321 # Set stock UOM in args, so that it can be used while fetching item price
322 args.stock_uom = item.stock_uom
323
Ankush Menat494bd9e2022-03-28 18:52:46 +0530324 if args.get("batch_no") and item.name != frappe.get_cached_value(
325 "Batch", args.get("batch_no"), "item"
326 ):
327 args["batch_no"] = ""
Rohit Waghchauree1f07042021-08-23 14:27:55 +0530328
Ankush Menat494bd9e2022-03-28 18:52:46 +0530329 out = frappe._dict(
330 {
331 "item_code": item.name,
332 "item_name": item.item_name,
333 "description": cstr(item.description).strip(),
334 "image": cstr(item.image).strip(),
335 "warehouse": warehouse,
336 "income_account": get_default_income_account(
337 args, item_defaults, item_group_defaults, brand_defaults
338 ),
339 "expense_account": expense_account
340 or get_default_expense_account(args, item_defaults, item_group_defaults, brand_defaults),
David Arnold1612d7b2023-10-26 14:03:22 +0200341 "discount_account": get_default_discount_account(
342 args, item_defaults, item_group_defaults, brand_defaults
343 ),
344 "provisional_expense_account": get_provisional_account(
345 args, item_defaults, item_group_defaults, brand_defaults
346 ),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530347 "cost_center": get_default_cost_center(
348 args, item_defaults, item_group_defaults, brand_defaults
349 ),
350 "has_serial_no": item.has_serial_no,
351 "has_batch_no": item.has_batch_no,
352 "batch_no": args.get("batch_no"),
353 "uom": args.uom,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530354 "stock_uom": item.stock_uom,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530355 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
356 "qty": flt(args.qty) or 1.0,
357 "stock_qty": flt(args.qty) or 1.0,
358 "price_list_rate": 0.0,
359 "base_price_list_rate": 0.0,
360 "rate": 0.0,
361 "base_rate": 0.0,
362 "amount": 0.0,
363 "base_amount": 0.0,
364 "net_rate": 0.0,
365 "net_amount": 0.0,
366 "discount_percentage": 0.0,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530367 "discount_amount": flt(args.discount_amount) or 0.0,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530368 "update_stock": args.get("update_stock")
369 if args.get("doctype") in ["Sales Invoice", "Purchase Invoice"]
370 else 0,
371 "delivered_by_supplier": item.delivered_by_supplier
372 if args.get("doctype") in ["Sales Order", "Sales Invoice"]
373 else 0,
374 "is_fixed_asset": item.is_fixed_asset,
375 "last_purchase_rate": item.last_purchase_rate
376 if args.get("doctype") in ["Purchase Order"]
377 else 0,
378 "transaction_date": args.get("transaction_date"),
379 "against_blanket_order": args.get("against_blanket_order"),
380 "bom_no": item.get("default_bom"),
381 "weight_per_unit": args.get("weight_per_unit") or item.get("weight_per_unit"),
382 "weight_uom": args.get("weight_uom") or item.get("weight_uom"),
383 "grant_commission": item.get("grant_commission"),
384 }
385 )
Anand Doshibd67e872014-04-11 16:51:27 +0530386
rohitwaghchauredb24e242023-12-13 14:06:45 +0530387 default_supplier = get_default_supplier(args, item_defaults, item_group_defaults, brand_defaults)
388 if default_supplier:
389 out.supplier = default_supplier
390
Zlash65627be1d2019-01-15 14:16:32 +0530391 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zlash6580f5cb02018-08-29 11:39:08 +0530392 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530393
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530394 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530395 if item.stock_uom == args.uom:
396 out.conversion_factor = 1.0
397 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530398 out.conversion_factor = args.conversion_factor or get_conversion_factor(item.name, args.uom).get(
399 "conversion_factor"
400 )
mbauskar287fe812017-04-10 19:15:57 +0530401
402 args.conversion_factor = out.conversion_factor
403 out.stock_qty = out.qty * out.conversion_factor
Saqib Ansari3713ae72022-02-14 11:33:34 +0530404 args.stock_qty = out.stock_qty
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530405
Shreya Shah44fa9a62018-01-08 14:58:20 +0530406 # calculate last purchase rate
Rohit Waghchaureec171fc2023-01-09 18:49:48 +0530407 if args.get("doctype") in purchase_doctypes and not frappe.db.get_single_value(
408 "Buying Settings", "disable_last_purchase_rate"
409 ):
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530410 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +0530411
412 out.last_purchase_rate = item_last_purchase_rate(
413 args.name, args.conversion_rate, item.name, out.conversion_factor
414 )
Shreya Shah44fa9a62018-01-08 14:58:20 +0530415
Nabin Haitb09ed412015-02-17 10:33:58 +0530416 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530417 for d in [
418 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530419 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530420 ["Cost Center", "cost_center", "cost_center"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530421 ["Warehouse", "warehouse", ""],
422 ]:
423 if not out[d[1]]:
424 out[d[1]] = frappe.get_cached_value("Company", args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530425
Ankush Menat64905182022-03-09 15:37:14 +0530426 for fieldname in ("item_name", "item_group", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530427 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530428
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530429 if args.get("manufacturer"):
430 part_no = get_item_manufacturer_part_no(args.get("item_code"), args.get("manufacturer"))
431 if part_no:
432 out["manufacturer_part_no"] = part_no
433 else:
434 out["manufacturer_part_no"] = None
435 out["manufacturer"] = None
marination3e7a8ab2020-04-07 21:00:57 +0530436 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530437 data = frappe.get_value(
438 "Item", item.name, ["default_item_manufacturer", "default_manufacturer_part_no"], as_dict=1
439 )
rohitwaghchaurebe16e5c2020-05-01 10:50:17 +0530440
441 if data:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530442 out.update(
443 {
444 "manufacturer": data.default_item_manufacturer,
445 "manufacturer_part_no": data.default_manufacturer_part_no,
446 }
447 )
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530448
Ankush Menat494bd9e2022-03-28 18:52:46 +0530449 child_doctype = args.doctype + " Item"
Nabin Hait34c551d2019-07-03 10:34:31 +0530450 meta = frappe.get_meta(child_doctype)
451 if meta.get_field("barcode"):
452 update_barcode_value(out)
453
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530454 if out.get("weight_per_unit"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530455 out["total_weight"] = out.weight_per_unit * out.stock_qty
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530456
Nabin Hait436f5262014-02-10 14:47:54 +0530457 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530458
Ankush Menat494bd9e2022-03-28 18:52:46 +0530459
Chillar Anand772d4752021-10-06 22:28:48 +0530460def get_item_warehouse(item, args, overwrite_warehouse, defaults=None):
Saqib438e0432020-04-03 10:02:56 +0530461 if not defaults:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530462 defaults = frappe._dict(
463 {
464 "item_defaults": get_item_defaults(item.name, args.company),
465 "item_group_defaults": get_item_group_defaults(item.name, args.company),
466 "brand_defaults": get_brand_defaults(item.name, args.company),
467 }
468 )
Saqib438e0432020-04-03 10:02:56 +0530469
470 if overwrite_warehouse or not args.warehouse:
471 warehouse = (
Ankush Menat494bd9e2022-03-28 18:52:46 +0530472 args.get("set_warehouse")
473 or defaults.item_defaults.get("default_warehouse")
474 or defaults.item_group_defaults.get("default_warehouse")
475 or defaults.brand_defaults.get("default_warehouse")
476 or args.get("warehouse")
Saqib438e0432020-04-03 10:02:56 +0530477 )
478
479 if not warehouse:
480 defaults = frappe.defaults.get_defaults() or {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530481 warehouse_exists = frappe.db.exists(
482 "Warehouse", {"name": defaults.default_warehouse, "company": args.company}
483 )
Saqib438e0432020-04-03 10:02:56 +0530484 if defaults.get("default_warehouse") and warehouse_exists:
485 warehouse = defaults.default_warehouse
486
487 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530488 warehouse = args.get("warehouse")
marinatione05013e2020-04-06 22:13:13 +0530489
Marica3b1be2b2020-10-22 17:04:31 +0530490 if not warehouse:
491 default_warehouse = frappe.db.get_single_value("Stock Settings", "default_warehouse")
492 if frappe.db.get_value("Warehouse", default_warehouse, "company") == args.company:
493 return default_warehouse
494
Saqib438e0432020-04-03 10:02:56 +0530495 return warehouse
496
Ankush Menat494bd9e2022-03-28 18:52:46 +0530497
Nabin Hait34c551d2019-07-03 10:34:31 +0530498def update_barcode_value(out):
Nabin Hait34c551d2019-07-03 10:34:31 +0530499 barcode_data = get_barcode_data([out])
500
501 # If item has one barcode then update the value of the barcode field
502 if barcode_data and len(barcode_data.get(out.item_code)) == 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530503 out["barcode"] = barcode_data.get(out.item_code)[0]
504
Nabin Hait34c551d2019-07-03 10:34:31 +0530505
Saqiba6f98d42020-07-23 18:51:26 +0530506def get_barcode_data(items_list):
Deepesh Gargf52d7c72024-01-02 13:37:39 +0530507 # get item-wise batch no data
508 # example: {'LED-GRE': [Batch001, Batch002]}
Saqiba6f98d42020-07-23 18:51:26 +0530509 # where LED-GRE is item code, SN0001 is serial no and Pune is warehouse
510
511 itemwise_barcode = {}
512 for item in items_list:
s-aga-r6b144ba2023-02-18 12:18:41 +0530513 barcodes = frappe.db.get_all(
514 "Item Barcode", filters={"parent": item.item_code}, fields="barcode"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530515 )
Saqiba6f98d42020-07-23 18:51:26 +0530516
517 for barcode in barcodes:
518 if item.item_code not in itemwise_barcode:
519 itemwise_barcode.setdefault(item.item_code, [])
520 itemwise_barcode[item.item_code].append(barcode.get("barcode"))
521
522 return itemwise_barcode
523
Ankush Menat494bd9e2022-03-28 18:52:46 +0530524
Zlash6580f5cb02018-08-29 11:39:08 +0530525@frappe.whitelist()
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530526def get_item_tax_info(company, tax_category, item_codes, item_rates=None, item_tax_templates=None):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500527 out = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530528
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530529 if item_tax_templates is None:
Deepesh Gargcae42b482021-06-25 13:34:00 +0530530 item_tax_templates = {}
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +0530531
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530532 if item_rates is None:
533 item_rates = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530534
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530535 if isinstance(item_codes, (str,)):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500536 item_codes = json.loads(item_codes)
537
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530538 if isinstance(item_rates, (str,)):
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530539 item_rates = json.loads(item_rates)
540
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530541 if isinstance(item_tax_templates, (str,)):
Deepesh Garg94d46042021-06-23 20:56:27 +0530542 item_tax_templates = json.loads(item_tax_templates)
543
Saif Ur Rehman67786682018-12-27 02:11:07 +0500544 for item_code in item_codes:
Deepesh Garg94d46042021-06-23 20:56:27 +0530545 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 +0500546 continue
Deepesh Garg94d46042021-06-23 20:56:27 +0530547
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530548 out[item_code[1]] = {}
549 item = frappe.get_cached_doc("Item", item_code[0])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530550 args = {
551 "company": company,
552 "tax_category": tax_category,
Divyam Mistrye9fe10c2024-02-01 16:15:43 +0530553 "base_net_rate": item_rates.get(item_code[1]),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530554 }
Deepesh Garg269962a2021-06-23 22:52:51 +0530555
556 if item_tax_templates:
557 args.update({"item_tax_template": item_tax_templates.get(item_code[1])})
Deepesh Garg94d46042021-06-23 20:56:27 +0530558
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530559 get_item_tax_template(args, item, out[item_code[1]])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530560 out[item_code[1]]["item_tax_rate"] = get_item_tax_map(
561 company, out[item_code[1]].get("item_tax_template"), as_json=True
562 )
Saif Ur Rehman67786682018-12-27 02:11:07 +0500563
564 return out
565
Ankush Menat494bd9e2022-03-28 18:52:46 +0530566
Saif Ur Rehman67786682018-12-27 02:11:07 +0500567def get_item_tax_template(args, item, out):
568 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530569 args = {
570 "tax_category": None
571 "item_tax_template": None
572 }
Saif Ur Rehman67786682018-12-27 02:11:07 +0500573 """
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530574 item_tax_template = None
575 if item.taxes:
576 item_tax_template = _get_item_tax_template(args, item.taxes, out)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500577
578 if not item_tax_template:
579 item_group = item.item_group
580 while item_group and not item_tax_template:
581 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
582 item_tax_template = _get_item_tax_template(args, item_group_doc.taxes, out)
583 item_group = item_group_doc.parent_item_group
584
barredterra0465c9a2023-12-08 14:15:26 +0100585 if args.get("child_doctype") and item_tax_template:
586 out.update(get_fetch_values(args.get("child_doctype"), "item_tax_template", item_tax_template))
Smit Vorab206b052023-11-23 15:10:47 +0530587
Ankush Menat494bd9e2022-03-28 18:52:46 +0530588
18alantom308905b2021-05-03 23:34:34 +0530589def _get_item_tax_template(args, taxes, out=None, for_validate=False):
590 if out is None:
591 out = {}
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530592 taxes_with_validity = []
593 taxes_with_no_validity = []
594
595 for tax in taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530596 tax_company = frappe.get_cached_value("Item Tax Template", tax.item_tax_template, "company")
597 if tax_company == args["company"]:
598 if tax.valid_from or tax.maximum_net_rate:
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530599 # In purchase Invoice first preference will be given to supplier invoice date
600 # if supplier date is not present then posting date
Sagar Vora1a3997a2022-06-16 17:03:47 +0000601 validation_date = args.get("bill_date") or args.get("transaction_date")
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530602
Ankush Menat494bd9e2022-03-28 18:52:46 +0530603 if getdate(tax.valid_from) <= getdate(validation_date) and is_within_valid_range(args, tax):
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530604 taxes_with_validity.append(tax)
605 else:
mohammadahmad1990e39649b2020-06-18 11:42:53 +0500606 taxes_with_no_validity.append(tax)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530607
608 if taxes_with_validity:
Deepesh Garg6f6928f2023-04-09 09:38:13 +0530609 taxes = sorted(
610 taxes_with_validity, key=lambda i: i.valid_from or tax.maximum_net_rate, reverse=True
611 )
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530612 else:
613 taxes = taxes_with_no_validity
614
615 if for_validate:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530616 return [
617 tax.item_tax_template
618 for tax in taxes
619 if (
620 cstr(tax.tax_category) == cstr(args.get("tax_category"))
621 and (tax.item_tax_template not in taxes)
622 )
623 ]
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530624
625 # all templates have validity and no template is valid
626 if not taxes_with_validity and (not taxes_with_no_validity):
627 return None
628
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530629 # do not change if already a valid template
Ankush Menat494bd9e2022-03-28 18:52:46 +0530630 if args.get("item_tax_template") in {t.item_tax_template for t in taxes}:
631 out["item_tax_template"] = args.get("item_tax_template")
632 return args.get("item_tax_template")
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530633
Saif Ur Rehman67786682018-12-27 02:11:07 +0500634 for tax in taxes:
635 if cstr(tax.tax_category) == cstr(args.get("tax_category")):
636 out["item_tax_template"] = tax.item_tax_template
637 return tax.item_tax_template
638 return None
639
Ankush Menat494bd9e2022-03-28 18:52:46 +0530640
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530641def is_within_valid_range(args, tax):
642 if not flt(tax.maximum_net_rate):
643 # No range specified, just ignore
644 return True
Divyam Mistrye9fe10c2024-02-01 16:15:43 +0530645 elif flt(tax.minimum_net_rate) <= flt(args.get("base_net_rate")) <= flt(tax.maximum_net_rate):
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530646 return True
647
648 return False
649
Ankush Menat494bd9e2022-03-28 18:52:46 +0530650
Saif Ur Rehman67786682018-12-27 02:11:07 +0500651@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500652def get_item_tax_map(company, item_tax_template, as_json=True):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500653 item_tax_map = {}
654 if item_tax_template:
655 template = frappe.get_cached_doc("Item Tax Template", item_tax_template)
656 for d in template.taxes:
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500657 if frappe.get_cached_value("Account", d.tax_type, "company") == company:
658 item_tax_map[d.tax_type] = d.tax_rate
Saif Ur Rehman67786682018-12-27 02:11:07 +0500659
660 return json.dumps(item_tax_map) if as_json else item_tax_map
661
Ankush Menat494bd9e2022-03-28 18:52:46 +0530662
Saif Ur Rehman67786682018-12-27 02:11:07 +0500663@frappe.whitelist()
Zlash6580f5cb02018-08-29 11:39:08 +0530664def calculate_service_end_date(args, item=None):
665 args = process_args(args)
666 if not item:
667 item = frappe.get_cached_doc("Item", args.item_code)
668
Zlash65627be1d2019-01-15 14:16:32 +0530669 doctype = args.get("parenttype") or args.get("doctype")
Zlash65a3dd7982019-01-15 14:36:11 +0530670 if doctype == "Sales Invoice":
671 enable_deferred = "enable_deferred_revenue"
672 no_of_months = "no_of_months"
673 account = "deferred_revenue_account"
674 else:
675 enable_deferred = "enable_deferred_expense"
676 no_of_months = "no_of_months_exp"
677 account = "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530678
Zlash6580f5cb02018-08-29 11:39:08 +0530679 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
Zarrare83ff382018-09-21 15:45:40 +0530680 service_end_date = add_months(service_start_date, item.get(no_of_months))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530681 deferred_detail = {"service_start_date": service_start_date, "service_end_date": service_end_date}
Zarrare83ff382018-09-21 15:45:40 +0530682 deferred_detail[enable_deferred] = item.get(enable_deferred)
683 deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)
Zlash6580f5cb02018-08-29 11:39:08 +0530684
685 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100686
Ankush Menat494bd9e2022-03-28 18:52:46 +0530687
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500688def get_default_income_account(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530689 return (
690 item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530691 or item_group.get("income_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500692 or brand.get("income_account")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530693 or args.income_account
694 )
695
Rushabh Mehta1a763742014-10-03 16:36:43 +0530696
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500697def get_default_expense_account(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530698 return (
699 item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530700 or item_group.get("expense_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500701 or brand.get("expense_account")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530702 or args.expense_account
703 )
704
Rushabh Mehta1a763742014-10-03 16:36:43 +0530705
David Arnold1612d7b2023-10-26 14:03:22 +0200706def get_provisional_account(args, item, item_group, brand):
707 return (
708 item.get("default_provisional_account")
709 or item_group.get("default_provisional_account")
710 or brand.get("default_provisional_account")
711 or args.default_provisional_account
712 )
Deepesh Garg3ce64172022-04-11 14:35:22 +0530713
714
David Arnold1612d7b2023-10-26 14:03:22 +0200715def get_default_discount_account(args, item, item_group, brand):
716 return (
717 item.get("default_discount_account")
718 or item_group.get("default_discount_account")
719 or brand.get("default_discount_account")
720 or args.discount_account
721 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530722
GangaManoj657e9b52021-07-06 16:51:12 +0530723
Zarrare83ff382018-09-21 15:45:40 +0530724def get_default_deferred_account(args, item, fieldname=None):
Zlash65627be1d2019-01-15 14:16:32 +0530725 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530726 return (
Gursheen Kaur Anand099468e2023-09-16 21:25:31 +0530727 frappe.get_cached_value(
728 "Item Default",
729 {"parent": args.item_code, "company": args.get("company")},
730 fieldname,
731 )
Zarrare83ff382018-09-21 15:45:40 +0530732 or args.get(fieldname)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530733 or frappe.get_cached_value("Company", args.company, "default_" + fieldname)
734 )
Manas Solanki03938482018-05-14 16:16:46 +0530735 else:
736 return None
737
Ankush Menat494bd9e2022-03-28 18:52:46 +0530738
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530739def get_default_cost_center(args, item=None, item_group=None, brand=None, company=None):
Nabin Hait50238c32018-08-08 18:43:04 +0530740 cost_center = None
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530741
742 if not company and args.get("company"):
743 company = args.get("company")
744
Ankush Menat494bd9e2022-03-28 18:52:46 +0530745 if args.get("project"):
Nabin Hait50238c32018-08-08 18:43:04 +0530746 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530747
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530748 if not cost_center and (item and item_group and brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530749 if args.get("customer"):
750 cost_center = (
751 item.get("selling_cost_center")
752 or item_group.get("selling_cost_center")
753 or brand.get("selling_cost_center")
754 )
Nabin Hait50238c32018-08-08 18:43:04 +0530755 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530756 cost_center = (
757 item.get("buying_cost_center")
758 or item_group.get("buying_cost_center")
759 or brand.get("buying_cost_center")
760 )
Rushabh Mehta49f97472018-08-30 18:50:48 +0530761
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530762 elif not cost_center and args.get("item_code") and company:
763 for method in ["get_item_defaults", "get_item_group_defaults", "get_brand_defaults"]:
764 path = "erpnext.stock.get_item_details.{0}".format(method)
765 data = frappe.get_attr(path)(args.get("item_code"), company)
766
767 if data and (data.selling_cost_center or data.buying_cost_center):
rohitwaghchaure14b009b2023-10-20 16:22:29 +0530768 if args.get("customer") and data.selling_cost_center:
769 return data.selling_cost_center
770
771 elif args.get("supplier") and data.buying_cost_center:
772 return data.buying_cost_center
773
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530774 return data.selling_cost_center or data.buying_cost_center
775
776 if not cost_center and args.get("cost_center"):
777 cost_center = args.get("cost_center")
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530778
Ankush Menat494bd9e2022-03-28 18:52:46 +0530779 if (
780 company
781 and cost_center
782 and frappe.get_cached_value("Cost Center", cost_center, "company") != company
783 ):
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530784 return None
785
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530786 if not cost_center and company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530787 cost_center = frappe.get_cached_value("Company", company, "cost_center")
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530788
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530789 return cost_center
Rushabh Mehta1a763742014-10-03 16:36:43 +0530790
Ankush Menat494bd9e2022-03-28 18:52:46 +0530791
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500792def get_default_supplier(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530793 return (
794 item.get("default_supplier")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500795 or item_group.get("default_supplier")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530796 or brand.get("default_supplier")
797 )
798
Shreya Shah3c9839f2018-07-17 18:01:44 +0530799
Ankush16d4de52021-08-09 10:41:24 +0530800def get_price_list_rate(args, item_doc, out=None):
801 if out is None:
802 out = frappe._dict()
803
Anand Doshi39a28912016-02-15 11:42:18 +0530804 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530805
Ankush Menat494bd9e2022-03-28 18:52:46 +0530806 if meta.get_field("currency") or args.get("currency"):
Maricae8bc9122021-04-19 11:05:21 +0530807 if not args.get("price_list_currency") or not args.get("plc_conversion_rate"):
808 # if currency and plc_conversion_rate exist then
809 # `get_price_list_currency_and_exchange_rate` has already been called
810 pl_details = get_price_list_currency_and_exchange_rate(args)
811 args.update(pl_details)
812
Nabin Hait06c8cf42019-05-16 19:17:02 +0530813 if meta.get_field("currency"):
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530814 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530815
Ankush16d4de52021-08-09 10:41:24 +0530816 price_list_rate = get_price_list_rate_for(args, item_doc.name)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530817
hiousi1516e292019-01-08 18:34:08 +0100818 # variant
Ankush16d4de52021-08-09 10:41:24 +0530819 if price_list_rate is None and item_doc.variant_of:
hiousi1516e292019-01-08 18:34:08 +0100820 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530821
822 # insert in database
rohitwaghchaure09ea7ed2024-03-19 12:10:24 +0530823 if price_list_rate is None or frappe.db.get_single_value(
824 "Stock Settings", "update_existing_price_list_rate"
825 ):
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530826 if args.price_list and args.rate:
827 insert_item_price(args)
Ankush16d4de52021-08-09 10:41:24 +0530828 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530829
Ankush Menat494bd9e2022-03-28 18:52:46 +0530830 out.price_list_rate = (
831 flt(price_list_rate) * flt(args.plc_conversion_rate) / flt(args.conversion_rate)
832 )
mbauskar287fe812017-04-10 19:15:57 +0530833
Rohit Waghchaured1d46712023-01-09 15:12:46 +0530834 if frappe.db.get_single_value("Buying Settings", "disable_last_purchase_rate"):
835 return out
836
Ankush Menat494bd9e2022-03-28 18:52:46 +0530837 if not out.price_list_rate and args.transaction_type == "buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530838 from erpnext.stock.doctype.item.item import get_last_purchase_details
Ankush Menat494bd9e2022-03-28 18:52:46 +0530839
840 out.update(get_last_purchase_details(item_doc.name, args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530841
Ankush16d4de52021-08-09 10:41:24 +0530842 return out
843
Ankush Menat494bd9e2022-03-28 18:52:46 +0530844
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530845def insert_item_price(args):
846 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530847 if frappe.db.get_value(
848 "Price List", args.price_list, "currency", cache=True
849 ) == args.currency and cint(
850 frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")
851 ):
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530852 if frappe.has_permission("Item Price", "write"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530853 price_list_rate = (
Rohit Waghchaure0f280742022-12-15 16:34:06 +0530854 (flt(args.rate) + flt(args.discount_amount)) / args.get("conversion_factor")
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530855 if args.get("conversion_factor")
Rohit Waghchaure0f280742022-12-15 16:34:06 +0530856 else (flt(args.rate) + flt(args.discount_amount))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530857 )
Rushabh Mehta985cb822016-12-30 15:06:54 +0530858
Ankush Menat494bd9e2022-03-28 18:52:46 +0530859 item_price = frappe.db.get_value(
860 "Item Price",
861 {"item_code": args.item_code, "price_list": args.price_list, "currency": args.currency},
862 ["name", "price_list_rate"],
863 as_dict=1,
864 )
Nabin Haitb479a872018-09-07 13:17:11 +0530865 if item_price and item_price.name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530866 if item_price.price_list_rate != price_list_rate and frappe.db.get_single_value(
867 "Stock Settings", "update_existing_price_list_rate"
868 ):
869 frappe.db.set_value("Item Price", item_price.name, "price_list_rate", price_list_rate)
870 frappe.msgprint(
871 _("Item Price updated for {0} in Price List {1}").format(args.item_code, args.price_list),
872 alert=True,
873 )
Rushabh Mehta985cb822016-12-30 15:06:54 +0530874 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530875 item_price = frappe.get_doc(
876 {
877 "doctype": "Item Price",
878 "price_list": args.price_list,
879 "item_code": args.item_code,
880 "currency": args.currency,
881 "price_list_rate": price_list_rate,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530882 "uom": args.stock_uom,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530883 }
884 )
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530885 item_price.insert()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530886 frappe.msgprint(
887 _("Item Price added for {0} in Price List {1}").format(args.item_code, args.price_list),
888 alert=True,
889 )
890
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530891
Nabin Hait01ca3e52019-01-25 16:25:15 +0530892def get_item_price(args, item_code, ignore_party=False):
Nabin Haite45ec662018-08-01 17:44:34 +0530893 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530894 Get name, price_list_rate from Item Price based on conditions
895 Check if the desired qty is within the increment of the packing list.
896 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
897 optional fields transaction_date, customer, supplier
898 :param item_code: str, Item Doctype field item_code
Nabin Haite45ec662018-08-01 17:44:34 +0530899 """
900
s-aga-r6b144ba2023-02-18 12:18:41 +0530901 ip = frappe.qb.DocType("Item Price")
902 query = (
903 frappe.qb.from_(ip)
904 .select(ip.name, ip.price_list_rate, ip.uom)
905 .where(
906 (ip.item_code == item_code)
907 & (ip.price_list == args.get("price_list"))
908 & (IfNull(ip.uom, "").isin(["", args.get("uom")]))
909 & (IfNull(ip.batch_no, "").isin(["", args.get("batch_no")]))
910 )
911 .orderby(ip.valid_from, order=frappe.qb.desc)
912 .orderby(IfNull(ip.batch_no, ""), order=frappe.qb.desc)
913 .orderby(ip.uom, order=frappe.qb.desc)
barredterrabe9fe732024-03-20 19:37:34 +0100914 .limit(1)
s-aga-r6b144ba2023-02-18 12:18:41 +0530915 )
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530916
Nabin Hait01ca3e52019-01-25 16:25:15 +0530917 if not ignore_party:
Nabin Hait01ca3e52019-01-25 16:25:15 +0530918 if args.get("customer"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530919 query = query.where(ip.customer == args.get("customer"))
Nabin Hait4e456632019-01-29 14:02:08 +0530920 elif args.get("supplier"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530921 query = query.where(ip.supplier == args.get("supplier"))
Nabin Hait4e456632019-01-29 14:02:08 +0530922 else:
s-aga-r6b144ba2023-02-18 12:18:41 +0530923 query = query.where((IfNull(ip.customer, "") == "") & (IfNull(ip.supplier, "") == ""))
Nabin Hait01ca3e52019-01-25 16:25:15 +0530924
Ankush Menat494bd9e2022-03-28 18:52:46 +0530925 if args.get("transaction_date"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530926 query = query.where(
927 (IfNull(ip.valid_from, "2000-01-01") <= args["transaction_date"])
928 & (IfNull(ip.valid_upto, "2500-12-31") >= args["transaction_date"])
929 )
Deepesh Gargf15ff5f2020-07-11 13:58:53 +0530930
s-aga-r6b144ba2023-02-18 12:18:41 +0530931 return query.run()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530932
Nabin Haite45ec662018-08-01 17:44:34 +0530933
934def get_price_list_rate_for(args, item_code):
935 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530936 :param customer: link to Customer DocType
937 :param supplier: link to Supplier DocType
938 :param price_list: str (Standard Buying or Standard Selling)
939 :param item_code: str, Item Doctype field item_code
940 :param qty: Desired Qty
941 :param transaction_date: Date of the price
Nabin Haite45ec662018-08-01 17:44:34 +0530942 """
943 item_price_args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530944 "item_code": item_code,
945 "price_list": args.get("price_list"),
946 "customer": args.get("customer"),
947 "supplier": args.get("supplier"),
948 "uom": args.get("uom"),
949 "transaction_date": args.get("transaction_date"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530950 "batch_no": args.get("batch_no"),
Nabin Haite45ec662018-08-01 17:44:34 +0530951 }
952
953 item_price_data = 0
954 price_list_rate = get_item_price(item_price_args, item_code)
955 if price_list_rate:
956 desired_qty = args.get("qty")
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530957 if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
Nabin Haite45ec662018-08-01 17:44:34 +0530958 item_price_data = price_list_rate
959 else:
Don-Leopardoccdf1932020-01-09 03:54:43 -0300960 for field in ["customer", "supplier"]:
Nabin Haite45ec662018-08-01 17:44:34 +0530961 del item_price_args[field]
962
Ankush Menat494bd9e2022-03-28 18:52:46 +0530963 general_price_list_rate = get_item_price(
964 item_price_args, item_code, ignore_party=args.get("ignore_party")
965 )
Don-Leopardoccdf1932020-01-09 03:54:43 -0300966
Nabin Haite45ec662018-08-01 17:44:34 +0530967 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530968 item_price_args["uom"] = args.get("stock_uom")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530969 general_price_list_rate = get_item_price(
970 item_price_args, item_code, ignore_party=args.get("ignore_party")
971 )
Nabin Haite45ec662018-08-01 17:44:34 +0530972
973 if general_price_list_rate:
974 item_price_data = general_price_list_rate
975
976 if item_price_data:
977 if item_price_data[0][2] == args.get("uom"):
978 return item_price_data[0][1]
Ankush Menat494bd9e2022-03-28 18:52:46 +0530979 elif not args.get("price_list_uom_dependant"):
Nabin Haite45ec662018-08-01 17:44:34 +0530980 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
981 else:
982 return item_price_data[0][1]
983
Ankush Menat494bd9e2022-03-28 18:52:46 +0530984
Nabin Haite45ec662018-08-01 17:44:34 +0530985def check_packing_list(price_list_rate_name, desired_qty, item_code):
986 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530987 Check if the desired qty is within the increment of the packing list.
988 :param price_list_rate_name: Name of Item Price
989 :param desired_qty: Desired Qt
990 :param item_code: str, Item Doctype field item_code
991 :param qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530992 """
993
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530994 flag = True
Nabin Haite45ec662018-08-01 17:44:34 +0530995 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530996 if item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +0530997 packing_increment = desired_qty % item_price.packing_unit
998
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530999 if packing_increment != 0:
1000 flag = False
1001
1002 return flag
Rushabh Mehta1a763742014-10-03 16:36:43 +05301003
Ankush Menat494bd9e2022-03-28 18:52:46 +05301004
Nabin Hait436f5262014-02-10 14:47:54 +05301005def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +05301006 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +05301007
Ankush Menat494bd9e2022-03-28 18:52:46 +05301008 company_currency = frappe.get_cached_value("Company", args.company, "default_currency")
1009 if not args.conversion_rate and args.currency == company_currency:
Anand Doshife13bfe2015-08-25 12:49:40 +05301010 args.conversion_rate = 1.0
1011
Ankush Menat494bd9e2022-03-28 18:52:46 +05301012 if (
1013 not args.ignore_conversion_rate
1014 and args.conversion_rate == 1
1015 and args.currency != company_currency
1016 ):
1017 args.conversion_rate = (
1018 get_exchange_rate(args.currency, company_currency, args.transaction_date, "for_buying") or 1.0
1019 )
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +05301020
Nabin Hait436f5262014-02-10 14:47:54 +05301021 # validate currency conversion rate
Ankush Menat494bd9e2022-03-28 18:52:46 +05301022 validate_conversion_rate(
1023 args.currency, args.conversion_rate, meta.get_label("conversion_rate"), args.company
1024 )
Anand Doshibd67e872014-04-11 16:51:27 +05301025
Ankush Menat494bd9e2022-03-28 18:52:46 +05301026 args.conversion_rate = flt(
1027 args.conversion_rate,
1028 get_field_precision(meta.get_field("conversion_rate"), frappe._dict({"fields": args})),
1029 )
Anand Doshibd67e872014-04-11 16:51:27 +05301030
Nabin Hait06c8cf42019-05-16 19:17:02 +05301031 if args.price_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301032 if not args.plc_conversion_rate and args.price_list_currency == frappe.db.get_value(
1033 "Price List", args.price_list, "currency", cache=True
1034 ):
Nabin Hait06c8cf42019-05-16 19:17:02 +05301035 args.plc_conversion_rate = 1.0
Manas Solanki3504a232018-06-06 12:46:06 +05301036
Nabin Hait06c8cf42019-05-16 19:17:02 +05301037 # validate price list currency conversion rate
1038 if not args.get("price_list_currency"):
1039 throw(_("Price List Currency not selected"))
1040 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301041 validate_conversion_rate(
1042 args.price_list_currency,
1043 args.plc_conversion_rate,
1044 meta.get_label("plc_conversion_rate"),
1045 args.company,
1046 )
Anand Doshibd67e872014-04-11 16:51:27 +05301047
Nabin Hait06c8cf42019-05-16 19:17:02 +05301048 if meta.get_field("plc_conversion_rate"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301049 args.plc_conversion_rate = flt(
1050 args.plc_conversion_rate,
1051 get_field_precision(meta.get_field("plc_conversion_rate"), frappe._dict({"fields": args})),
1052 )
1053
Anand Doshibd67e872014-04-11 16:51:27 +05301054
Rushabh Mehtaf14b8092014-04-03 14:30:42 +05301055def get_party_item_code(args, item_doc, out):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301056 if args.transaction_type == "selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +05301057 out.customer_item_code = None
Nabin Hait34c551d2019-07-03 10:34:31 +05301058
Ankush Menat494bd9e2022-03-28 18:52:46 +05301059 if args.quotation_to and args.quotation_to != "Customer":
Nabin Hait34c551d2019-07-03 10:34:31 +05301060 return
1061
Nabin Hait79f091e2014-12-26 11:41:15 +05301062 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +05301063
1064 if customer_item_code:
1065 out.customer_item_code = customer_item_code[0].ref_code
1066 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +05301067 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +05301068 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
1069 if customer_group_item_code and not customer_group_item_code[0].customer_name:
1070 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +05301071
Ankush Menat494bd9e2022-03-28 18:52:46 +05301072 if args.transaction_type == "buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +05301073 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +05301074 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +05301075
Ankush Menat494bd9e2022-03-28 18:52:46 +05301076
rohitwaghchaure2ea593b2018-04-12 13:37:08 +05301077def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301078 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +05301079
Rushabh Mehta708e47a2018-08-08 16:37:31 +05301080 if not frappe.flags.pos_profile and not pos_profile:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301081 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get("pos_profile"))
Anand Doshibd67e872014-04-11 16:51:27 +05301082
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301083 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +05301084 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +05301085 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301086 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +05301087
Nabin Hait436f5262014-02-10 14:47:54 +05301088 if res.get("warehouse"):
s-aga-rc716dcc2022-12-29 12:34:18 +05301089 res.actual_qty = get_bin_details(
1090 args.item_code, res.warehouse, include_child_warehouses=True
1091 ).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +05301092
Nabin Hait436f5262014-02-10 14:47:54 +05301093 return res
1094
Ankush Menat494bd9e2022-03-28 18:52:46 +05301095
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301096@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301097def get_pos_profile(company, pos_profile=None, user=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301098 if pos_profile:
1099 return frappe.get_cached_doc("POS Profile", pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301100
1101 if not user:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301102 user = frappe.session["user"]
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301103
s-aga-r6b144ba2023-02-18 12:18:41 +05301104 pf = frappe.qb.DocType("POS Profile")
1105 pfu = frappe.qb.DocType("POS Profile User")
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301106
s-aga-r6b144ba2023-02-18 12:18:41 +05301107 query = (
1108 frappe.qb.from_(pf)
1109 .left_join(pfu)
1110 .on(pf.name == pfu.parent)
1111 .select(pf.star)
1112 .where((pfu.user == user) & (pfu.default == 1))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301113 )
Anand Doshibd67e872014-04-11 16:51:27 +05301114
s-aga-r6b144ba2023-02-18 12:18:41 +05301115 if company:
1116 query = query.where(pf.company == company)
1117
1118 pos_profile = query.run(as_dict=True)
1119
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301120 if not pos_profile and company:
s-aga-r6b144ba2023-02-18 12:18:41 +05301121 pos_profile = (
1122 frappe.qb.from_(pf)
1123 .left_join(pfu)
1124 .on(pf.name == pfu.parent)
1125 .select(pf.star)
1126 .where((pf.company == company) & (pf.disabled == 0))
1127 ).run(as_dict=True)
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301128
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301129 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +05301130
Ankush Menat494bd9e2022-03-28 18:52:46 +05301131
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301132@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +05301133def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +05301134 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +05301135 filters = {"parent": item_code, "uom": uom}
s-aga-r58c027d2023-02-28 15:14:34 +05301136
Rushabh Mehta724f9e52014-10-07 15:29:58 +05301137 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +05301138 filters["parent"] = ("in", (item_code, variant_of))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301139 conversion_factor = frappe.db.get_value("UOM Conversion Detail", filters, "conversion_factor")
Sagar Vora508189e2018-09-11 17:22:25 +05301140 if not conversion_factor:
1141 stock_uom = frappe.db.get_value("Item", item_code, "stock_uom")
1142 conversion_factor = get_uom_conv_factor(uom, stock_uom)
s-aga-r6b144ba2023-02-18 12:18:41 +05301143
rohitwaghchaureffdadbf2019-01-08 16:21:25 +05301144 return {"conversion_factor": conversion_factor or 1.0}
Nabin Hait08222152014-02-28 11:30:47 +05301145
Ankush Menat494bd9e2022-03-28 18:52:46 +05301146
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301147@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +05301148def get_projected_qty(item_code, warehouse):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301149 return {
1150 "projected_qty": frappe.db.get_value(
1151 "Bin", {"item_code": item_code, "warehouse": warehouse}, "projected_qty"
1152 )
1153 }
1154
Nabin Hait08222152014-02-28 11:30:47 +05301155
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301156@frappe.whitelist()
s-aga-rc716dcc2022-12-29 12:34:18 +05301157def get_bin_details(item_code, warehouse, company=None, include_child_warehouses=False):
ruthra kumarbe382052023-01-16 08:50:39 +05301158 bin_details = {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
s-aga-rc716dcc2022-12-29 12:34:18 +05301159
1160 if warehouse:
s-aga-rc3911a52022-12-29 16:38:08 +05301161 from frappe.query_builder.functions import Coalesce, Sum
s-aga-r58c027d2023-02-28 15:14:34 +05301162
s-aga-rc716dcc2022-12-29 12:34:18 +05301163 from erpnext.stock.doctype.warehouse.warehouse import get_child_warehouses
1164
1165 warehouses = get_child_warehouses(warehouse) if include_child_warehouses else [warehouse]
s-aga-rc3911a52022-12-29 16:38:08 +05301166
1167 bin = frappe.qb.DocType("Bin")
1168 bin_details = (
1169 frappe.qb.from_(bin)
1170 .select(
1171 Coalesce(Sum(bin.projected_qty), 0).as_("projected_qty"),
1172 Coalesce(Sum(bin.actual_qty), 0).as_("actual_qty"),
1173 Coalesce(Sum(bin.reserved_qty), 0).as_("reserved_qty"),
1174 )
1175 .where((bin.item_code == item_code) & (bin.warehouse.isin(warehouses)))
1176 ).run(as_dict=True)[0]
s-aga-rc716dcc2022-12-29 12:34:18 +05301177
Anupam4980dd62021-03-15 11:37:46 +05301178 if company:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301179 bin_details["company_total_stock"] = get_company_total_stock(item_code, company)
s-aga-rb425c2d2023-01-02 11:25:13 +05301180
Anupam4980dd62021-03-15 11:37:46 +05301181 return bin_details
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301182
Ankush Menat494bd9e2022-03-28 18:52:46 +05301183
Anupam4980dd62021-03-15 11:37:46 +05301184def get_company_total_stock(item_code, company):
s-aga-r6b144ba2023-02-18 12:18:41 +05301185 bin = frappe.qb.DocType("Bin")
1186 wh = frappe.qb.DocType("Warehouse")
1187
1188 return (
1189 frappe.qb.from_(bin)
1190 .inner_join(wh)
1191 .on(bin.warehouse == wh.name)
1192 .select(Sum(bin.actual_qty))
1193 .where((wh.company == company) & (bin.item_code == item_code))
1194 ).run()[0][0]
Ankush Menat494bd9e2022-03-28 18:52:46 +05301195
Anupam4980dd62021-03-15 11:37:46 +05301196
1197@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +05301198def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +07001199 from erpnext.stock.doctype.batch import batch
Ankush Menat494bd9e2022-03-28 18:52:46 +05301200
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +05301201 if batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301202 return {"actual_batch_qty": batch.get_batch_qty(batch_no, warehouse)}
1203
Rushabh Mehta1e8025b2015-07-24 15:16:25 +05301204
Anand Doshidffec8f2014-07-01 17:45:15 +05301205@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301206def apply_price_list(args, as_doc=False):
1207 """Apply pricelist on a document-like dict object and return as
1208 {'parent': dict, 'children': list}
1209
1210 :param args: See below
1211 :param as_doc: Updates value in the passed dict
1212
Ankush Menat494bd9e2022-03-28 18:52:46 +05301213 args = {
1214 "doctype": "",
1215 "name": "",
1216 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
1217 "conversion_rate": 1.0,
1218 "selling_price_list": None,
1219 "price_list_currency": None,
1220 "price_list_uom_dependant": None,
1221 "plc_conversion_rate": 1.0,
1222 "doctype": "",
1223 "name": "",
1224 "supplier": None,
1225 "transaction_date": None,
1226 "conversion_rate": 1.0,
1227 "buying_price_list": None,
1228 "ignore_pricing_rule": 0/1
1229 }
Anand Doshidffec8f2014-07-01 17:45:15 +05301230 """
1231 args = process_args(args)
1232
1233 parent = get_price_list_currency_and_exchange_rate(args)
Maricae8bc9122021-04-19 11:05:21 +05301234 args.update(parent)
1235
Anand Doshidffec8f2014-07-01 17:45:15 +05301236 children = []
1237
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301238 if "items" in args:
1239 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +05301240 args.update(parent)
1241
1242 for item in item_list:
1243 args_copy = frappe._dict(args.copy())
1244 args_copy.update(item)
1245 item_details = apply_price_list_on_item(args_copy)
1246 children.append(item_details)
1247
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301248 if as_doc:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301249 args.price_list_currency = (parent.price_list_currency,)
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301250 args.plc_conversion_rate = parent.plc_conversion_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +05301251 if args.get("items"):
1252 for i, item in enumerate(args.get("items")):
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301253 for fieldname in children[i]:
1254 # if the field exists in the original doc
1255 # update the value
1256 if fieldname in item and fieldname not in ("name", "doctype"):
1257 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301258 return args
1259 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301260 return {"parent": parent, "children": children}
1261
Anand Doshidffec8f2014-07-01 17:45:15 +05301262
1263def apply_price_list_on_item(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301264 item_doc = frappe.db.get_value("Item", args.item_code, ["name", "variant_of"], as_dict=1)
Ankush16d4de52021-08-09 10:41:24 +05301265 item_details = get_price_list_rate(args, item_doc)
Deepesh Gargb741ae12022-12-02 17:14:06 +05301266 item_details.update(get_pricing_rule_for_item(args))
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301267
Anand Doshidffec8f2014-07-01 17:45:15 +05301268 return item_details
1269
Ankush Menat494bd9e2022-03-28 18:52:46 +05301270
Anand Doshidffec8f2014-07-01 17:45:15 +05301271def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +05301272 if not args.price_list:
1273 return {}
1274
Ankush Menat494bd9e2022-03-28 18:52:46 +05301275 if args.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
Shreya3f778522018-05-15 16:59:20 +05301276 args.update({"exchange_rate": "for_selling"})
Ankush Menat494bd9e2022-03-28 18:52:46 +05301277 elif args.doctype in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]:
Shreya3f778522018-05-15 16:59:20 +05301278 args.update({"exchange_rate": "for_buying"})
1279
rohitwaghchaurea85ddf22019-11-19 18:47:48 +05301280 price_list_details = get_price_list_details(args.price_list)
1281
1282 price_list_currency = price_list_details.get("currency")
1283 price_list_uom_dependant = price_list_details.get("price_list_uom_dependant")
1284
Anand Doshidffec8f2014-07-01 17:45:15 +05301285 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +01001286 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +05301287
Ankush Menat494bd9e2022-03-28 18:52:46 +05301288 if (not plc_conversion_rate) or (
1289 price_list_currency
1290 and args.price_list_currency
1291 and price_list_currency != args.price_list_currency
1292 ):
1293 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
1294 plc_conversion_rate = (
1295 get_exchange_rate(
1296 price_list_currency, company_currency, args.transaction_date, args.exchange_rate
1297 )
1298 or plc_conversion_rate
1299 )
Anand Doshidffec8f2014-07-01 17:45:15 +05301300
Ankush Menat494bd9e2022-03-28 18:52:46 +05301301 return frappe._dict(
1302 {
1303 "price_list_currency": price_list_currency,
1304 "price_list_uom_dependant": price_list_uom_dependant,
1305 "plc_conversion_rate": plc_conversion_rate or 1,
1306 }
1307 )
1308
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +05301309
1310@frappe.whitelist()
1311def get_default_bom(item_code=None):
marination9f2d3252022-06-14 17:20:44 +05301312 def _get_bom(item):
1313 bom = frappe.get_all(
1314 "BOM", dict(item=item, is_active=True, is_default=True, docstatus=1), limit=1
Ankush Menat494bd9e2022-03-28 18:52:46 +05301315 )
marination9f2d3252022-06-14 17:20:44 +05301316 return bom[0].name if bom else None
1317
1318 if not item_code:
1319 return
1320
1321 bom_name = _get_bom(item_code)
1322
1323 template_item = frappe.db.get_value("Item", item_code, "variant_of")
1324 if not bom_name and template_item:
1325 bom_name = _get_bom(template_item)
1326
1327 return bom_name
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301328
Ankush Menat494bd9e2022-03-28 18:52:46 +05301329
Deepesh Garg15ff6a52020-02-18 12:28:41 +05301330@frappe.whitelist()
Manas Solanki087a2252018-05-04 16:02:38 +05301331def get_valuation_rate(item_code, company, warehouse=None):
rohitwaghchauree6199dc2023-09-20 17:27:35 +05301332 if frappe.get_cached_value("Warehouse", warehouse, "is_group"):
1333 return {"valuation_rate": 0.0}
1334
Manas Solankib16a4ec2018-05-04 16:49:33 +05301335 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +05301336 item_group = get_item_group_defaults(item_code, company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001337 brand = get_brand_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +05301338 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +05301339 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +05301340 if not warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301341 warehouse = (
1342 item.get("default_warehouse")
1343 or item_group.get("default_warehouse")
1344 or brand.get("default_warehouse")
1345 )
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301346
Ankush Menat494bd9e2022-03-28 18:52:46 +05301347 return frappe.db.get_value(
1348 "Bin", {"item_code": item_code, "warehouse": warehouse}, ["valuation_rate"], as_dict=True
1349 ) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301350
Manas Solankie3910fb2018-05-16 15:50:17 +05301351 elif not item.get("is_stock_item"):
s-aga-r6b144ba2023-02-18 12:18:41 +05301352 pi_item = frappe.qb.DocType("Purchase Invoice Item")
1353 valuation_rate = (
1354 frappe.qb.from_(pi_item)
1355 .select((Sum(pi_item.base_net_amount) / Sum(pi_item.qty * pi_item.conversion_factor)))
s-aga-r58c027d2023-02-28 15:14:34 +05301356 .where((pi_item.docstatus == 1) & (pi_item.item_code == item_code))
s-aga-r6b144ba2023-02-18 12:18:41 +05301357 ).run()
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301358
Saurabhbd01a812016-03-07 14:32:23 +05301359 if valuation_rate:
1360 return {"valuation_rate": valuation_rate[0][0] or 0.0}
1361 else:
1362 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301363
Ankush Menat494bd9e2022-03-28 18:52:46 +05301364
Saurabh2d7af632016-02-26 11:09:20 +05301365def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +05301366 if out.valuation_rate:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301367 out.update({"gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)})
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301368
Saurabhd3135532016-02-25 18:59:20 +05301369 return out
mbauskar6f603392016-01-21 16:10:22 +05301370
Ankush Menat494bd9e2022-03-28 18:52:46 +05301371
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301372@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301373def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaure648efca2023-03-28 12:16:27 +05301374 serial_nos = serial_nos or []
1375 return serial_nos
Manas Solankie5e87f72018-05-28 20:07:08 +05301376
1377
1378def update_party_blanket_order(args, out):
ronelvcabrera370cdc02019-12-04 18:37:11 +08001379 if out["against_blanket_order"]:
1380 blanket_order_details = get_blanket_order_details(args)
1381 if blanket_order_details:
1382 out.update(blanket_order_details)
Manas Solankie5e87f72018-05-28 20:07:08 +05301383
Ankush Menat494bd9e2022-03-28 18:52:46 +05301384
Manas Solankie5e87f72018-05-28 20:07:08 +05301385@frappe.whitelist()
1386def get_blanket_order_details(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301387 if isinstance(args, str):
Manas Solankie5e87f72018-05-28 20:07:08 +05301388 args = frappe._dict(json.loads(args))
1389
1390 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +05301391
s-aga-r6b144ba2023-02-18 12:18:41 +05301392 if args.item_code:
1393 bo = frappe.qb.DocType("Blanket Order")
1394 bo_item = frappe.qb.DocType("Blanket Order Item")
1395
1396 query = (
1397 frappe.qb.from_(bo)
1398 .from_(bo_item)
1399 .select(bo_item.rate.as_("blanket_order_rate"), bo.name.as_("blanket_order"))
1400 .where(
1401 (bo.company == args.company)
1402 & (bo_item.item_code == args.item_code)
1403 & (bo.docstatus == 1)
1404 & (bo.name == bo_item.parent)
1405 )
Ankush Menat494bd9e2022-03-28 18:52:46 +05301406 )
Nabin Hait2737b082018-06-14 18:07:22 +05301407
s-aga-r6b144ba2023-02-18 12:18:41 +05301408 if args.customer and args.doctype == "Sales Order":
1409 query = query.where(bo.customer == args.customer)
1410 elif args.supplier and args.doctype == "Purchase Order":
1411 query = query.where(bo.supplier == args.supplier)
1412 if args.blanket_order:
1413 query = query.where(bo.name == args.blanket_order)
1414 if args.transaction_date:
1415 query = query.where(bo.to_date >= args.transaction_date)
1416
1417 blanket_order_details = query.run(as_dict=True)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301418 blanket_order_details = blanket_order_details[0] if blanket_order_details else ""
s-aga-r6b144ba2023-02-18 12:18:41 +05301419
Manas Solankie5e87f72018-05-28 20:07:08 +05301420 return blanket_order_details