blob: 64650bc2018546340d2dc0f0cb2666001de874ff [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Nabin Hait436f5262014-02-10 14:47:54 +05302# License: GNU General Public License v3. See license.txt
3
Chillar Anand915b3432021-09-02 16:44:59 +05304
5import json
6
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05307import frappe
8from frappe import _, throw
Ankush Menat1e976642022-02-15 10:57:06 +05309from frappe.model import child_table_fields, default_fields
Rushabh Mehta66e08e32014-09-29 12:17:03 +053010from frappe.model.meta import get_field_precision
Rohit Waghchaure648efca2023-03-28 12:16:27 +053011from frappe.query_builder.functions import IfNull, Sum
Chillar Anand915b3432021-09-02 16:44:59 +053012from frappe.utils import add_days, add_months, cint, cstr, flt, getdate
Nabin Hait98c2a052014-05-05 18:41:41 +053013
Chillar Anand915b3432021-09-02 16:44:59 +053014from erpnext import get_company_currency
15from erpnext.accounts.doctype.pricing_rule.pricing_rule import (
16 get_pricing_rule_for_item,
17 set_transaction_type,
18)
19from erpnext.setup.doctype.brand.brand import get_brand_defaults
20from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults
21from erpnext.setup.utils import get_exchange_rate
Chillar Anand915b3432021-09-02 16:44:59 +053022from erpnext.stock.doctype.item.item import get_item_defaults, get_uom_conv_factor
23from erpnext.stock.doctype.item_manufacturer.item_manufacturer import get_item_manufacturer_part_no
24from erpnext.stock.doctype.price_list.price_list import get_price_list_details
tundebabzyacccdb32017-11-23 08:35:15 +010025
Ankush Menat494bd9e2022-03-28 18:52:46 +053026sales_doctypes = ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice", "POS Invoice"]
27purchase_doctypes = [
28 "Material Request",
29 "Supplier Quotation",
30 "Purchase Order",
31 "Purchase Receipt",
32 "Purchase Invoice",
33]
34
Nabin Hait0d1ccc32019-02-14 18:30:10 +053035
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053036@frappe.whitelist()
Deepesh Garga7051cb2023-04-14 09:59:42 +053037def get_item_details(args, doc=None, for_validate=False, overwrite_warehouse=True):
Nabin Hait436f5262014-02-10 14:47:54 +053038 """
Ankush Menat494bd9e2022-03-28 18:52:46 +053039 args = {
40 "item_code": "",
41 "warehouse": None,
42 "customer": "",
43 "conversion_rate": 1.0,
44 "selling_price_list": None,
45 "price_list_currency": None,
46 "plc_conversion_rate": 1.0,
47 "doctype": "",
48 "name": "",
49 "supplier": None,
50 "transaction_date": None,
51 "conversion_rate": 1.0,
52 "buying_price_list": None,
Sagar Sharma409df262022-04-19 14:57:31 +053053 "is_subcontracted": 0/1,
Ankush Menat494bd9e2022-03-28 18:52:46 +053054 "ignore_pricing_rule": 0/1
55 "project": ""
56 "set_warehouse": ""
57 }
Nabin Hait436f5262014-02-10 14:47:54 +053058 """
Suraj Shetty182f4de2019-08-16 08:16:22 +053059
Anand Doshidffec8f2014-07-01 17:45:15 +053060 args = process_args(args)
marination392f3232020-07-14 17:03:17 +053061 for_validate = process_string_args(for_validate)
62 overwrite_warehouse = process_string_args(overwrite_warehouse)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053063 item = frappe.get_cached_doc("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053064 validate_item_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053065
Ankush Menat8fe5feb2021-11-04 19:48:32 +053066 if isinstance(doc, str):
Deepesh Gargef0d26c2020-01-06 15:34:15 +053067 doc = json.loads(doc)
68
Deepesh Gargef0d26c2020-01-06 15:34:15 +053069 if doc:
Sagar Vora1a3997a2022-06-16 17:03:47 +000070 args["transaction_date"] = doc.get("transaction_date") or doc.get("posting_date")
Deepesh Gargef0d26c2020-01-06 15:34:15 +053071
Sagar Vora1a3997a2022-06-16 17:03:47 +000072 if doc.get("doctype") == "Purchase Invoice":
73 args["bill_date"] = doc.get("bill_date")
74
Deepesh Garga7051cb2023-04-14 09:59:42 +053075 out = get_basic_details(args, item, overwrite_warehouse)
Deepesh Garg4c61ee32023-04-02 09:35:27 +053076
Saif Ur Rehman67786682018-12-27 02:11:07 +050077 get_item_tax_template(args, item, out)
Ankush Menat494bd9e2022-03-28 18:52:46 +053078 out["item_tax_rate"] = get_item_tax_map(
79 args.company,
80 args.get("item_tax_template")
81 if out.get("item_tax_template") is None
82 else out.get("item_tax_template"),
83 as_json=True,
84 )
Saif Ur Rehman67786682018-12-27 02:11:07 +050085
Rushabh Mehta708e47a2018-08-08 16:37:31 +053086 get_party_item_code(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053087
Rushabh Mehta708e47a2018-08-08 16:37:31 +053088 set_valuation_rate(out, args)
Anand Doshibd67e872014-04-11 16:51:27 +053089
Manas Solankie5e87f72018-05-28 20:07:08 +053090 update_party_blanket_order(args, out)
91
HENRY Florian231fe412023-02-13 16:26:05 +010092 # Never try to find a customer price if customer is set in these Doctype
93 current_customer = args.customer
94 if args.get("doctype") in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]:
95 args.customer = None
96
Ankush16d4de52021-08-09 10:41:24 +053097 out.update(get_price_list_rate(args, item))
Nabin Hait436f5262014-02-10 14:47:54 +053098
HENRY Florian231fe412023-02-13 16:26:05 +010099 args.customer = current_customer
100
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530101 if args.customer and cint(args.is_pos):
Anuja Pawarf132ed42021-05-07 12:11:09 +0530102 out.update(get_pos_profile_item_details(args.company, args, update_data=True))
Rushabh Mehta6b537922017-03-14 16:59:11 +0530103
Ankush Menat494bd9e2022-03-28 18:52:46 +0530104 if (
105 args.get("doctype") == "Material Request"
106 and args.get("material_request_type") == "Material Transfer"
107 ):
Nabin Haitda17f9c2020-05-01 18:16:25 +0530108 out.update(get_bin_details(args.item_code, args.get("from_warehouse")))
109
110 elif out.get("warehouse"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530111 if doc and doc.get("doctype") == "Purchase Order":
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530112 # calculate company_total_stock only for po
s-aga-rc716dcc2022-12-29 12:34:18 +0530113 bin_details = get_bin_details(
114 args.item_code, out.warehouse, args.company, include_child_warehouses=True
115 )
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530116 else:
s-aga-rc716dcc2022-12-29 12:34:18 +0530117 bin_details = get_bin_details(args.item_code, out.warehouse, include_child_warehouses=True)
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530118
119 out.update(bin_details)
Anand Doshibd67e872014-04-11 16:51:27 +0530120
Nabin Haita3dd72a2014-05-28 12:49:20 +0530121 # update args with out, if key or value not exists
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530122 for key, value in out.items():
Nabin Haita3dd72a2014-05-28 12:49:20 +0530123 if args.get(key) is None:
124 args[key] = value
125
Deepesh Garg6192af52022-12-08 18:04:40 +0530126 data = get_pricing_rule_for_item(args, doc=doc, for_validate=for_validate)
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530127
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530128 out.update(data)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530129
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530130 if args.transaction_date and item.lead_time_days:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530131 out.schedule_date = out.lead_time_date = add_days(args.transaction_date, item.lead_time_days)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530132
Sagar Sharma409df262022-04-19 14:57:31 +0530133 if args.get("is_subcontracted"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530134 out.bom = args.get("bom") or get_default_bom(args.item_code)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530135
136 get_gross_profit(out)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530137 if args.doctype == "Material Request":
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530138 out.rate = args.rate or out.price_list_rate
Rohit Waghchaure1bc53a32021-03-31 15:28:26 +0530139 out.amount = flt(args.qty) * flt(out.rate)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530140
Ankush Menat1e976642022-02-15 10:57:06 +0530141 out = remove_standard_fields(out)
Deepesh Garga7051cb2023-04-14 09:59:42 +0530142 return out
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530143
Ankush Menat494bd9e2022-03-28 18:52:46 +0530144
Ankush Menat1e976642022-02-15 10:57:06 +0530145def remove_standard_fields(details):
146 for key in child_table_fields + default_fields:
147 details.pop(key, None)
148 return details
149
150
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530151def set_valuation_rate(out, args):
Nabin Hait50238c32018-08-08 18:43:04 +0530152 if frappe.db.exists("Product Bundle", args.item_code, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530153 valuation_rate = 0.0
154 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530155
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530156 for bundle_item in bundled_items.items:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530157 valuation_rate += flt(
158 get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get(
159 "valuation_rate"
160 )
161 * bundle_item.qty
162 )
Anand Doshi70f57eb2015-11-27 14:37:40 +0530163
Ankush Menat494bd9e2022-03-28 18:52:46 +0530164 out.update({"valuation_rate": valuation_rate})
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530165
166 else:
167 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
168
Nabin Hait436f5262014-02-10 14:47:54 +0530169
Anand Doshidffec8f2014-07-01 17:45:15 +0530170def process_args(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530171 if isinstance(args, str):
Anand Doshidffec8f2014-07-01 17:45:15 +0530172 args = json.loads(args)
173
174 args = frappe._dict(args)
175
Anand Doshidffec8f2014-07-01 17:45:15 +0530176 if not args.get("price_list"):
177 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
178
Devin Slauenwhite55276f12022-05-25 00:05:22 -0400179 if not args.item_code and args.barcode:
Anand Doshidffec8f2014-07-01 17:45:15 +0530180 args.item_code = get_item_code(barcode=args.barcode)
181 elif not args.item_code and args.serial_no:
182 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530183
mbauskar6f603392016-01-21 16:10:22 +0530184 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530185 return args
186
Ankush Menat494bd9e2022-03-28 18:52:46 +0530187
marination392f3232020-07-14 17:03:17 +0530188def process_string_args(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530189 if isinstance(args, str):
marination392f3232020-07-14 17:03:17 +0530190 args = json.loads(args)
191 return args
tundebabzyacccdb32017-11-23 08:35:15 +0100192
Ankush Menat494bd9e2022-03-28 18:52:46 +0530193
Neil Trini Lasrado4abda672015-02-25 17:34:27 +0530194@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530195def get_item_code(barcode=None, serial_no=None):
196 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100197 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530198 if not item_code:
199 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530200 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530201 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530202 if not item_code:
203 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530204
Nabin Hait436f5262014-02-10 14:47:54 +0530205 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530206
tundebabzyacccdb32017-11-23 08:35:15 +0100207
Nabin Hait436f5262014-02-10 14:47:54 +0530208def validate_item_details(args, item):
209 if not args.company:
210 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530211
Nabin Hait436f5262014-02-10 14:47:54 +0530212 from erpnext.stock.doctype.item.item import validate_end_of_life
Ankush Menat494bd9e2022-03-28 18:52:46 +0530213
Anand Doshi21e09a22015-10-29 12:21:41 +0530214 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530215
Rohit Waghchaure2c83fff2023-01-18 23:21:29 +0530216 if cint(item.has_variants):
217 msg = f"Item {item.name} is a template, please select one of its variants"
218
219 throw(_(msg), title=_("Template Item Selected"))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530220
tundebabzyacccdb32017-11-23 08:35:15 +0100221 elif args.transaction_type == "buying" and args.doctype != "Material Request":
s-aga-r6d89b2f2022-06-18 15:46:59 +0530222 if args.get("is_subcontracted"):
223 if args.get("is_old_subcontracting_flow"):
224 if item.is_sub_contracted_item != 1:
225 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
226 else:
227 if item.is_stock_item:
228 throw(_("Item {0} must be a Non-Stock Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530229
tundebabzyacccdb32017-11-23 08:35:15 +0100230
Suraj Shetty182f4de2019-08-16 08:16:22 +0530231def get_basic_details(args, item, overwrite_warehouse=True):
tundebabzyacccdb32017-11-23 08:35:15 +0100232 """
233 :param args: {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530234 "item_code": "",
235 "warehouse": None,
236 "customer": "",
237 "conversion_rate": 1.0,
238 "selling_price_list": None,
239 "price_list_currency": None,
240 "price_list_uom_dependant": None,
241 "plc_conversion_rate": 1.0,
242 "doctype": "",
243 "name": "",
244 "supplier": None,
245 "transaction_date": None,
246 "conversion_rate": 1.0,
247 "buying_price_list": None,
Sagar Sharma409df262022-04-19 14:57:31 +0530248 "is_subcontracted": 0/1,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530249 "ignore_pricing_rule": 0/1
250 "project": "",
251 barcode: "",
252 serial_no: "",
253 currency: "",
254 update_stock: "",
255 price_list: "",
256 company: "",
257 order_type: "",
258 is_pos: "",
259 project: "",
260 qty: "",
261 stock_qty: "",
262 conversion_factor: "",
263 against_blanket_order: 0/1
264 }
tundebabzyacccdb32017-11-23 08:35:15 +0100265 :param item: `item_code` of Item object
266 :return: frappe._dict
267 """
268
Rushabh Mehta1a763742014-10-03 16:36:43 +0530269 if not item:
270 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530271
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530272 if item.variant_of:
273 item.update_template_tables()
274
Manas Solankib16a4ec2018-05-04 16:49:33 +0530275 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530276 item_group_defaults = get_item_group_defaults(item.name, args.company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500277 brand_defaults = get_brand_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530278
Ankush Menat494bd9e2022-03-28 18:52:46 +0530279 defaults = frappe._dict(
280 {
281 "item_defaults": item_defaults,
282 "item_group_defaults": item_group_defaults,
283 "brand_defaults": brand_defaults,
284 }
285 )
marinatione05013e2020-04-06 22:13:13 +0530286
Saqib438e0432020-04-03 10:02:56 +0530287 warehouse = get_item_warehouse(item, args, overwrite_warehouse, defaults)
Nabin Hait36028bf2014-02-12 19:09:28 +0530288
Ankush Menat494bd9e2022-03-28 18:52:46 +0530289 if args.get("doctype") == "Material Request" and not args.get("material_request_type"):
290 args["material_request_type"] = frappe.db.get_value(
291 "Material Request", args.get("name"), "material_request_type", cache=True
292 )
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530293
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530294 expense_account = None
295
Ankush Menat494bd9e2022-03-28 18:52:46 +0530296 if args.get("doctype") == "Purchase Invoice" and item.is_fixed_asset:
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530297 from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530298
Ankush Menat494bd9e2022-03-28 18:52:46 +0530299 expense_account = get_asset_category_account(
300 fieldname="fixed_asset_account", item=args.item_code, company=args.company
301 )
302
303 # Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
304 if not args.get("uom"):
305 if args.get("doctype") in sales_doctypes:
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530306 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
Ankush Menat494bd9e2022-03-28 18:52:46 +0530307 elif (args.get("doctype") in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]) or (
308 args.get("doctype") == "Material Request" and args.get("material_request_type") == "Purchase"
309 ):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530310 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
311 else:
312 args.uom = item.stock_uom
313
Sagar Vora57038c32022-11-09 18:56:09 +0530314 # Set stock UOM in args, so that it can be used while fetching item price
315 args.stock_uom = item.stock_uom
316
Ankush Menat494bd9e2022-03-28 18:52:46 +0530317 if args.get("batch_no") and item.name != frappe.get_cached_value(
318 "Batch", args.get("batch_no"), "item"
319 ):
320 args["batch_no"] = ""
Rohit Waghchauree1f07042021-08-23 14:27:55 +0530321
Ankush Menat494bd9e2022-03-28 18:52:46 +0530322 out = frappe._dict(
323 {
324 "item_code": item.name,
325 "item_name": item.item_name,
326 "description": cstr(item.description).strip(),
327 "image": cstr(item.image).strip(),
328 "warehouse": warehouse,
329 "income_account": get_default_income_account(
330 args, item_defaults, item_group_defaults, brand_defaults
331 ),
332 "expense_account": expense_account
333 or get_default_expense_account(args, item_defaults, item_group_defaults, brand_defaults),
334 "discount_account": get_default_discount_account(args, item_defaults),
Deepesh Garg3ce64172022-04-11 14:35:22 +0530335 "provisional_expense_account": get_provisional_account(args, item_defaults),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530336 "cost_center": get_default_cost_center(
337 args, item_defaults, item_group_defaults, brand_defaults
338 ),
339 "has_serial_no": item.has_serial_no,
340 "has_batch_no": item.has_batch_no,
341 "batch_no": args.get("batch_no"),
342 "uom": args.uom,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530343 "stock_uom": item.stock_uom,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530344 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
345 "qty": flt(args.qty) or 1.0,
346 "stock_qty": flt(args.qty) or 1.0,
347 "price_list_rate": 0.0,
348 "base_price_list_rate": 0.0,
349 "rate": 0.0,
350 "base_rate": 0.0,
351 "amount": 0.0,
352 "base_amount": 0.0,
353 "net_rate": 0.0,
354 "net_amount": 0.0,
355 "discount_percentage": 0.0,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530356 "discount_amount": flt(args.discount_amount) or 0.0,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530357 "supplier": get_default_supplier(args, item_defaults, item_group_defaults, brand_defaults),
358 "update_stock": args.get("update_stock")
359 if args.get("doctype") in ["Sales Invoice", "Purchase Invoice"]
360 else 0,
361 "delivered_by_supplier": item.delivered_by_supplier
362 if args.get("doctype") in ["Sales Order", "Sales Invoice"]
363 else 0,
364 "is_fixed_asset": item.is_fixed_asset,
365 "last_purchase_rate": item.last_purchase_rate
366 if args.get("doctype") in ["Purchase Order"]
367 else 0,
368 "transaction_date": args.get("transaction_date"),
369 "against_blanket_order": args.get("against_blanket_order"),
370 "bom_no": item.get("default_bom"),
371 "weight_per_unit": args.get("weight_per_unit") or item.get("weight_per_unit"),
372 "weight_uom": args.get("weight_uom") or item.get("weight_uom"),
373 "grant_commission": item.get("grant_commission"),
374 }
375 )
Anand Doshibd67e872014-04-11 16:51:27 +0530376
Zlash65627be1d2019-01-15 14:16:32 +0530377 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zlash6580f5cb02018-08-29 11:39:08 +0530378 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530379
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530380 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530381 if item.stock_uom == args.uom:
382 out.conversion_factor = 1.0
383 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530384 out.conversion_factor = args.conversion_factor or get_conversion_factor(item.name, args.uom).get(
385 "conversion_factor"
386 )
mbauskar287fe812017-04-10 19:15:57 +0530387
388 args.conversion_factor = out.conversion_factor
389 out.stock_qty = out.qty * out.conversion_factor
Saqib Ansari3713ae72022-02-14 11:33:34 +0530390 args.stock_qty = out.stock_qty
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530391
Shreya Shah44fa9a62018-01-08 14:58:20 +0530392 # calculate last purchase rate
Rohit Waghchaureec171fc2023-01-09 18:49:48 +0530393 if args.get("doctype") in purchase_doctypes and not frappe.db.get_single_value(
394 "Buying Settings", "disable_last_purchase_rate"
395 ):
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530396 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +0530397
398 out.last_purchase_rate = item_last_purchase_rate(
399 args.name, args.conversion_rate, item.name, out.conversion_factor
400 )
Shreya Shah44fa9a62018-01-08 14:58:20 +0530401
Nabin Haitb09ed412015-02-17 10:33:58 +0530402 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530403 for d in [
404 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530405 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530406 ["Cost Center", "cost_center", "cost_center"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530407 ["Warehouse", "warehouse", ""],
408 ]:
409 if not out[d[1]]:
410 out[d[1]] = frappe.get_cached_value("Company", args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530411
Ankush Menat64905182022-03-09 15:37:14 +0530412 for fieldname in ("item_name", "item_group", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530413 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530414
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530415 if args.get("manufacturer"):
416 part_no = get_item_manufacturer_part_no(args.get("item_code"), args.get("manufacturer"))
417 if part_no:
418 out["manufacturer_part_no"] = part_no
419 else:
420 out["manufacturer_part_no"] = None
421 out["manufacturer"] = None
marination3e7a8ab2020-04-07 21:00:57 +0530422 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530423 data = frappe.get_value(
424 "Item", item.name, ["default_item_manufacturer", "default_manufacturer_part_no"], as_dict=1
425 )
rohitwaghchaurebe16e5c2020-05-01 10:50:17 +0530426
427 if data:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530428 out.update(
429 {
430 "manufacturer": data.default_item_manufacturer,
431 "manufacturer_part_no": data.default_manufacturer_part_no,
432 }
433 )
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530434
Ankush Menat494bd9e2022-03-28 18:52:46 +0530435 child_doctype = args.doctype + " Item"
Nabin Hait34c551d2019-07-03 10:34:31 +0530436 meta = frappe.get_meta(child_doctype)
437 if meta.get_field("barcode"):
438 update_barcode_value(out)
439
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530440 if out.get("weight_per_unit"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530441 out["total_weight"] = out.weight_per_unit * out.stock_qty
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530442
Nabin Hait436f5262014-02-10 14:47:54 +0530443 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530444
Ankush Menat494bd9e2022-03-28 18:52:46 +0530445
Chillar Anand772d4752021-10-06 22:28:48 +0530446def get_item_warehouse(item, args, overwrite_warehouse, defaults=None):
Saqib438e0432020-04-03 10:02:56 +0530447 if not defaults:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530448 defaults = frappe._dict(
449 {
450 "item_defaults": get_item_defaults(item.name, args.company),
451 "item_group_defaults": get_item_group_defaults(item.name, args.company),
452 "brand_defaults": get_brand_defaults(item.name, args.company),
453 }
454 )
Saqib438e0432020-04-03 10:02:56 +0530455
456 if overwrite_warehouse or not args.warehouse:
457 warehouse = (
Ankush Menat494bd9e2022-03-28 18:52:46 +0530458 args.get("set_warehouse")
459 or defaults.item_defaults.get("default_warehouse")
460 or defaults.item_group_defaults.get("default_warehouse")
461 or defaults.brand_defaults.get("default_warehouse")
462 or args.get("warehouse")
Saqib438e0432020-04-03 10:02:56 +0530463 )
464
465 if not warehouse:
466 defaults = frappe.defaults.get_defaults() or {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530467 warehouse_exists = frappe.db.exists(
468 "Warehouse", {"name": defaults.default_warehouse, "company": args.company}
469 )
Saqib438e0432020-04-03 10:02:56 +0530470 if defaults.get("default_warehouse") and warehouse_exists:
471 warehouse = defaults.default_warehouse
472
473 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530474 warehouse = args.get("warehouse")
marinatione05013e2020-04-06 22:13:13 +0530475
Marica3b1be2b2020-10-22 17:04:31 +0530476 if not warehouse:
477 default_warehouse = frappe.db.get_single_value("Stock Settings", "default_warehouse")
478 if frappe.db.get_value("Warehouse", default_warehouse, "company") == args.company:
479 return default_warehouse
480
Saqib438e0432020-04-03 10:02:56 +0530481 return warehouse
482
Ankush Menat494bd9e2022-03-28 18:52:46 +0530483
Nabin Hait34c551d2019-07-03 10:34:31 +0530484def update_barcode_value(out):
Nabin Hait34c551d2019-07-03 10:34:31 +0530485 barcode_data = get_barcode_data([out])
486
487 # If item has one barcode then update the value of the barcode field
488 if barcode_data and len(barcode_data.get(out.item_code)) == 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530489 out["barcode"] = barcode_data.get(out.item_code)[0]
490
Nabin Hait34c551d2019-07-03 10:34:31 +0530491
Saqiba6f98d42020-07-23 18:51:26 +0530492def get_barcode_data(items_list):
493 # get itemwise batch no data
494 # exmaple: {'LED-GRE': [Batch001, Batch002]}
495 # where LED-GRE is item code, SN0001 is serial no and Pune is warehouse
496
497 itemwise_barcode = {}
498 for item in items_list:
s-aga-r6b144ba2023-02-18 12:18:41 +0530499 barcodes = frappe.db.get_all(
500 "Item Barcode", filters={"parent": item.item_code}, fields="barcode"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530501 )
Saqiba6f98d42020-07-23 18:51:26 +0530502
503 for barcode in barcodes:
504 if item.item_code not in itemwise_barcode:
505 itemwise_barcode.setdefault(item.item_code, [])
506 itemwise_barcode[item.item_code].append(barcode.get("barcode"))
507
508 return itemwise_barcode
509
Ankush Menat494bd9e2022-03-28 18:52:46 +0530510
Zlash6580f5cb02018-08-29 11:39:08 +0530511@frappe.whitelist()
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530512def get_item_tax_info(company, tax_category, item_codes, item_rates=None, item_tax_templates=None):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500513 out = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530514
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530515 if item_tax_templates is None:
Deepesh Gargcae42b482021-06-25 13:34:00 +0530516 item_tax_templates = {}
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +0530517
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530518 if item_rates is None:
519 item_rates = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530520
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530521 if isinstance(item_codes, (str,)):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500522 item_codes = json.loads(item_codes)
523
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530524 if isinstance(item_rates, (str,)):
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530525 item_rates = json.loads(item_rates)
526
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530527 if isinstance(item_tax_templates, (str,)):
Deepesh Garg94d46042021-06-23 20:56:27 +0530528 item_tax_templates = json.loads(item_tax_templates)
529
Saif Ur Rehman67786682018-12-27 02:11:07 +0500530 for item_code in item_codes:
Deepesh Garg94d46042021-06-23 20:56:27 +0530531 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 +0500532 continue
Deepesh Garg94d46042021-06-23 20:56:27 +0530533
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530534 out[item_code[1]] = {}
535 item = frappe.get_cached_doc("Item", item_code[0])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530536 args = {
537 "company": company,
538 "tax_category": tax_category,
539 "net_rate": item_rates.get(item_code[1]),
540 }
Deepesh Garg269962a2021-06-23 22:52:51 +0530541
542 if item_tax_templates:
543 args.update({"item_tax_template": item_tax_templates.get(item_code[1])})
Deepesh Garg94d46042021-06-23 20:56:27 +0530544
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530545 get_item_tax_template(args, item, out[item_code[1]])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530546 out[item_code[1]]["item_tax_rate"] = get_item_tax_map(
547 company, out[item_code[1]].get("item_tax_template"), as_json=True
548 )
Saif Ur Rehman67786682018-12-27 02:11:07 +0500549
550 return out
551
Ankush Menat494bd9e2022-03-28 18:52:46 +0530552
Saif Ur Rehman67786682018-12-27 02:11:07 +0500553def get_item_tax_template(args, item, out):
554 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530555 args = {
556 "tax_category": None
557 "item_tax_template": None
558 }
Saif Ur Rehman67786682018-12-27 02:11:07 +0500559 """
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530560 item_tax_template = None
561 if item.taxes:
562 item_tax_template = _get_item_tax_template(args, item.taxes, out)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500563
564 if not item_tax_template:
565 item_group = item.item_group
566 while item_group and not item_tax_template:
567 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
568 item_tax_template = _get_item_tax_template(args, item_group_doc.taxes, out)
569 item_group = item_group_doc.parent_item_group
570
Ankush Menat494bd9e2022-03-28 18:52:46 +0530571
18alantom308905b2021-05-03 23:34:34 +0530572def _get_item_tax_template(args, taxes, out=None, for_validate=False):
573 if out is None:
574 out = {}
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530575 taxes_with_validity = []
576 taxes_with_no_validity = []
577
578 for tax in taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530579 tax_company = frappe.get_cached_value("Item Tax Template", tax.item_tax_template, "company")
580 if tax_company == args["company"]:
581 if tax.valid_from or tax.maximum_net_rate:
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530582 # In purchase Invoice first preference will be given to supplier invoice date
583 # if supplier date is not present then posting date
Sagar Vora1a3997a2022-06-16 17:03:47 +0000584 validation_date = args.get("bill_date") or args.get("transaction_date")
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530585
Ankush Menat494bd9e2022-03-28 18:52:46 +0530586 if getdate(tax.valid_from) <= getdate(validation_date) and is_within_valid_range(args, tax):
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530587 taxes_with_validity.append(tax)
588 else:
mohammadahmad1990e39649b2020-06-18 11:42:53 +0500589 taxes_with_no_validity.append(tax)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530590
591 if taxes_with_validity:
Deepesh Garg6f6928f2023-04-09 09:38:13 +0530592 taxes = sorted(
593 taxes_with_validity, key=lambda i: i.valid_from or tax.maximum_net_rate, reverse=True
594 )
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530595 else:
596 taxes = taxes_with_no_validity
597
598 if for_validate:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530599 return [
600 tax.item_tax_template
601 for tax in taxes
602 if (
603 cstr(tax.tax_category) == cstr(args.get("tax_category"))
604 and (tax.item_tax_template not in taxes)
605 )
606 ]
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530607
608 # all templates have validity and no template is valid
609 if not taxes_with_validity and (not taxes_with_no_validity):
610 return None
611
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530612 # do not change if already a valid template
Ankush Menat494bd9e2022-03-28 18:52:46 +0530613 if args.get("item_tax_template") in {t.item_tax_template for t in taxes}:
614 out["item_tax_template"] = args.get("item_tax_template")
615 return args.get("item_tax_template")
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530616
Saif Ur Rehman67786682018-12-27 02:11:07 +0500617 for tax in taxes:
618 if cstr(tax.tax_category) == cstr(args.get("tax_category")):
619 out["item_tax_template"] = tax.item_tax_template
620 return tax.item_tax_template
621 return None
622
Ankush Menat494bd9e2022-03-28 18:52:46 +0530623
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530624def is_within_valid_range(args, tax):
625 if not flt(tax.maximum_net_rate):
626 # No range specified, just ignore
627 return True
Ankush Menat494bd9e2022-03-28 18:52:46 +0530628 elif flt(tax.minimum_net_rate) <= flt(args.get("net_rate")) <= flt(tax.maximum_net_rate):
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530629 return True
630
631 return False
632
Ankush Menat494bd9e2022-03-28 18:52:46 +0530633
Saif Ur Rehman67786682018-12-27 02:11:07 +0500634@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500635def get_item_tax_map(company, item_tax_template, as_json=True):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500636 item_tax_map = {}
637 if item_tax_template:
638 template = frappe.get_cached_doc("Item Tax Template", item_tax_template)
639 for d in template.taxes:
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500640 if frappe.get_cached_value("Account", d.tax_type, "company") == company:
641 item_tax_map[d.tax_type] = d.tax_rate
Saif Ur Rehman67786682018-12-27 02:11:07 +0500642
643 return json.dumps(item_tax_map) if as_json else item_tax_map
644
Ankush Menat494bd9e2022-03-28 18:52:46 +0530645
Saif Ur Rehman67786682018-12-27 02:11:07 +0500646@frappe.whitelist()
Zlash6580f5cb02018-08-29 11:39:08 +0530647def calculate_service_end_date(args, item=None):
648 args = process_args(args)
649 if not item:
650 item = frappe.get_cached_doc("Item", args.item_code)
651
Zlash65627be1d2019-01-15 14:16:32 +0530652 doctype = args.get("parenttype") or args.get("doctype")
Zlash65a3dd7982019-01-15 14:36:11 +0530653 if doctype == "Sales Invoice":
654 enable_deferred = "enable_deferred_revenue"
655 no_of_months = "no_of_months"
656 account = "deferred_revenue_account"
657 else:
658 enable_deferred = "enable_deferred_expense"
659 no_of_months = "no_of_months_exp"
660 account = "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530661
Zlash6580f5cb02018-08-29 11:39:08 +0530662 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
Zarrare83ff382018-09-21 15:45:40 +0530663 service_end_date = add_months(service_start_date, item.get(no_of_months))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530664 deferred_detail = {"service_start_date": service_start_date, "service_end_date": service_end_date}
Zarrare83ff382018-09-21 15:45:40 +0530665 deferred_detail[enable_deferred] = item.get(enable_deferred)
666 deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)
Zlash6580f5cb02018-08-29 11:39:08 +0530667
668 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100669
Ankush Menat494bd9e2022-03-28 18:52:46 +0530670
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500671def get_default_income_account(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530672 return (
673 item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530674 or item_group.get("income_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500675 or brand.get("income_account")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530676 or args.income_account
677 )
678
Rushabh Mehta1a763742014-10-03 16:36:43 +0530679
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500680def get_default_expense_account(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530681 return (
682 item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530683 or item_group.get("expense_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500684 or brand.get("expense_account")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530685 or args.expense_account
686 )
687
Rushabh Mehta1a763742014-10-03 16:36:43 +0530688
Deepesh Garg3ce64172022-04-11 14:35:22 +0530689def get_provisional_account(args, item):
690 return item.get("default_provisional_account") or args.default_provisional_account
691
692
GangaManoj0b7d8fb2021-07-13 01:37:30 +0530693def get_default_discount_account(args, item):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530694 return item.get("default_discount_account") or args.discount_account
695
GangaManoj657e9b52021-07-06 16:51:12 +0530696
Zarrare83ff382018-09-21 15:45:40 +0530697def get_default_deferred_account(args, item, fieldname=None):
Zlash65627be1d2019-01-15 14:16:32 +0530698 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530699 return (
700 item.get(fieldname)
Zarrare83ff382018-09-21 15:45:40 +0530701 or args.get(fieldname)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530702 or frappe.get_cached_value("Company", args.company, "default_" + fieldname)
703 )
Manas Solanki03938482018-05-14 16:16:46 +0530704 else:
705 return None
706
Ankush Menat494bd9e2022-03-28 18:52:46 +0530707
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530708def get_default_cost_center(args, item=None, item_group=None, brand=None, company=None):
Nabin Hait50238c32018-08-08 18:43:04 +0530709 cost_center = None
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530710
711 if not company and args.get("company"):
712 company = args.get("company")
713
Ankush Menat494bd9e2022-03-28 18:52:46 +0530714 if args.get("project"):
Nabin Hait50238c32018-08-08 18:43:04 +0530715 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530716
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530717 if not cost_center and (item and item_group and brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530718 if args.get("customer"):
719 cost_center = (
720 item.get("selling_cost_center")
721 or item_group.get("selling_cost_center")
722 or brand.get("selling_cost_center")
723 )
Nabin Hait50238c32018-08-08 18:43:04 +0530724 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530725 cost_center = (
726 item.get("buying_cost_center")
727 or item_group.get("buying_cost_center")
728 or brand.get("buying_cost_center")
729 )
Rushabh Mehta49f97472018-08-30 18:50:48 +0530730
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530731 elif not cost_center and args.get("item_code") and company:
732 for method in ["get_item_defaults", "get_item_group_defaults", "get_brand_defaults"]:
733 path = "erpnext.stock.get_item_details.{0}".format(method)
734 data = frappe.get_attr(path)(args.get("item_code"), company)
735
736 if data and (data.selling_cost_center or data.buying_cost_center):
737 return data.selling_cost_center or data.buying_cost_center
738
739 if not cost_center and args.get("cost_center"):
740 cost_center = args.get("cost_center")
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530741
Ankush Menat494bd9e2022-03-28 18:52:46 +0530742 if (
743 company
744 and cost_center
745 and frappe.get_cached_value("Cost Center", cost_center, "company") != company
746 ):
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530747 return None
748
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530749 if not cost_center and company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530750 cost_center = frappe.get_cached_value("Company", company, "cost_center")
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530751
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530752 return cost_center
Rushabh Mehta1a763742014-10-03 16:36:43 +0530753
Ankush Menat494bd9e2022-03-28 18:52:46 +0530754
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500755def get_default_supplier(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530756 return (
757 item.get("default_supplier")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500758 or item_group.get("default_supplier")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530759 or brand.get("default_supplier")
760 )
761
Shreya Shah3c9839f2018-07-17 18:01:44 +0530762
Ankush16d4de52021-08-09 10:41:24 +0530763def get_price_list_rate(args, item_doc, out=None):
764 if out is None:
765 out = frappe._dict()
766
Anand Doshi39a28912016-02-15 11:42:18 +0530767 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530768
Ankush Menat494bd9e2022-03-28 18:52:46 +0530769 if meta.get_field("currency") or args.get("currency"):
Maricae8bc9122021-04-19 11:05:21 +0530770 if not args.get("price_list_currency") or not args.get("plc_conversion_rate"):
771 # if currency and plc_conversion_rate exist then
772 # `get_price_list_currency_and_exchange_rate` has already been called
773 pl_details = get_price_list_currency_and_exchange_rate(args)
774 args.update(pl_details)
775
Nabin Hait06c8cf42019-05-16 19:17:02 +0530776 if meta.get_field("currency"):
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530777 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530778
Ankush16d4de52021-08-09 10:41:24 +0530779 price_list_rate = get_price_list_rate_for(args, item_doc.name)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530780
hiousi1516e292019-01-08 18:34:08 +0100781 # variant
Ankush16d4de52021-08-09 10:41:24 +0530782 if price_list_rate is None and item_doc.variant_of:
hiousi1516e292019-01-08 18:34:08 +0100783 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530784
785 # insert in database
Ankush16d4de52021-08-09 10:41:24 +0530786 if price_list_rate is None:
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530787 if args.price_list and args.rate:
788 insert_item_price(args)
Ankush16d4de52021-08-09 10:41:24 +0530789 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530790
Ankush Menat494bd9e2022-03-28 18:52:46 +0530791 out.price_list_rate = (
792 flt(price_list_rate) * flt(args.plc_conversion_rate) / flt(args.conversion_rate)
793 )
mbauskar287fe812017-04-10 19:15:57 +0530794
Rohit Waghchaured1d46712023-01-09 15:12:46 +0530795 if frappe.db.get_single_value("Buying Settings", "disable_last_purchase_rate"):
796 return out
797
Ankush Menat494bd9e2022-03-28 18:52:46 +0530798 if not out.price_list_rate and args.transaction_type == "buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530799 from erpnext.stock.doctype.item.item import get_last_purchase_details
Ankush Menat494bd9e2022-03-28 18:52:46 +0530800
801 out.update(get_last_purchase_details(item_doc.name, args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530802
Ankush16d4de52021-08-09 10:41:24 +0530803 return out
804
Ankush Menat494bd9e2022-03-28 18:52:46 +0530805
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530806def insert_item_price(args):
807 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530808 if frappe.db.get_value(
809 "Price List", args.price_list, "currency", cache=True
810 ) == args.currency and cint(
811 frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")
812 ):
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530813 if frappe.has_permission("Item Price", "write"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530814 price_list_rate = (
Rohit Waghchaure0f280742022-12-15 16:34:06 +0530815 (flt(args.rate) + flt(args.discount_amount)) / args.get("conversion_factor")
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530816 if args.get("conversion_factor")
Rohit Waghchaure0f280742022-12-15 16:34:06 +0530817 else (flt(args.rate) + flt(args.discount_amount))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530818 )
Rushabh Mehta985cb822016-12-30 15:06:54 +0530819
Ankush Menat494bd9e2022-03-28 18:52:46 +0530820 item_price = frappe.db.get_value(
821 "Item Price",
822 {"item_code": args.item_code, "price_list": args.price_list, "currency": args.currency},
823 ["name", "price_list_rate"],
824 as_dict=1,
825 )
Nabin Haitb479a872018-09-07 13:17:11 +0530826 if item_price and item_price.name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530827 if item_price.price_list_rate != price_list_rate and frappe.db.get_single_value(
828 "Stock Settings", "update_existing_price_list_rate"
829 ):
830 frappe.db.set_value("Item Price", item_price.name, "price_list_rate", price_list_rate)
831 frappe.msgprint(
832 _("Item Price updated for {0} in Price List {1}").format(args.item_code, args.price_list),
833 alert=True,
834 )
Rushabh Mehta985cb822016-12-30 15:06:54 +0530835 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530836 item_price = frappe.get_doc(
837 {
838 "doctype": "Item Price",
839 "price_list": args.price_list,
840 "item_code": args.item_code,
841 "currency": args.currency,
842 "price_list_rate": price_list_rate,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530843 "uom": args.stock_uom,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530844 }
845 )
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530846 item_price.insert()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530847 frappe.msgprint(
848 _("Item Price added for {0} in Price List {1}").format(args.item_code, args.price_list),
849 alert=True,
850 )
851
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530852
Nabin Hait01ca3e52019-01-25 16:25:15 +0530853def get_item_price(args, item_code, ignore_party=False):
Nabin Haite45ec662018-08-01 17:44:34 +0530854 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530855 Get name, price_list_rate from Item Price based on conditions
856 Check if the desired qty is within the increment of the packing list.
857 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
858 optional fields transaction_date, customer, supplier
859 :param item_code: str, Item Doctype field item_code
Nabin Haite45ec662018-08-01 17:44:34 +0530860 """
861
s-aga-r6b144ba2023-02-18 12:18:41 +0530862 ip = frappe.qb.DocType("Item Price")
863 query = (
864 frappe.qb.from_(ip)
865 .select(ip.name, ip.price_list_rate, ip.uom)
866 .where(
867 (ip.item_code == item_code)
868 & (ip.price_list == args.get("price_list"))
869 & (IfNull(ip.uom, "").isin(["", args.get("uom")]))
870 & (IfNull(ip.batch_no, "").isin(["", args.get("batch_no")]))
871 )
872 .orderby(ip.valid_from, order=frappe.qb.desc)
873 .orderby(IfNull(ip.batch_no, ""), order=frappe.qb.desc)
874 .orderby(ip.uom, order=frappe.qb.desc)
875 )
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530876
Nabin Hait01ca3e52019-01-25 16:25:15 +0530877 if not ignore_party:
Nabin Hait01ca3e52019-01-25 16:25:15 +0530878 if args.get("customer"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530879 query = query.where(ip.customer == args.get("customer"))
Nabin Hait4e456632019-01-29 14:02:08 +0530880 elif args.get("supplier"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530881 query = query.where(ip.supplier == args.get("supplier"))
Nabin Hait4e456632019-01-29 14:02:08 +0530882 else:
s-aga-r6b144ba2023-02-18 12:18:41 +0530883 query = query.where((IfNull(ip.customer, "") == "") & (IfNull(ip.supplier, "") == ""))
Nabin Hait01ca3e52019-01-25 16:25:15 +0530884
Ankush Menat494bd9e2022-03-28 18:52:46 +0530885 if args.get("transaction_date"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530886 query = query.where(
887 (IfNull(ip.valid_from, "2000-01-01") <= args["transaction_date"])
888 & (IfNull(ip.valid_upto, "2500-12-31") >= args["transaction_date"])
889 )
Deepesh Gargf15ff5f2020-07-11 13:58:53 +0530890
s-aga-r6b144ba2023-02-18 12:18:41 +0530891 return query.run()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530892
Nabin Haite45ec662018-08-01 17:44:34 +0530893
894def get_price_list_rate_for(args, item_code):
895 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530896 :param customer: link to Customer DocType
897 :param supplier: link to Supplier DocType
898 :param price_list: str (Standard Buying or Standard Selling)
899 :param item_code: str, Item Doctype field item_code
900 :param qty: Desired Qty
901 :param transaction_date: Date of the price
Nabin Haite45ec662018-08-01 17:44:34 +0530902 """
903 item_price_args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530904 "item_code": item_code,
905 "price_list": args.get("price_list"),
906 "customer": args.get("customer"),
907 "supplier": args.get("supplier"),
908 "uom": args.get("uom"),
909 "transaction_date": args.get("transaction_date"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530910 "batch_no": args.get("batch_no"),
Nabin Haite45ec662018-08-01 17:44:34 +0530911 }
912
913 item_price_data = 0
914 price_list_rate = get_item_price(item_price_args, item_code)
915 if price_list_rate:
916 desired_qty = args.get("qty")
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530917 if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
Nabin Haite45ec662018-08-01 17:44:34 +0530918 item_price_data = price_list_rate
919 else:
Don-Leopardoccdf1932020-01-09 03:54:43 -0300920 for field in ["customer", "supplier"]:
Nabin Haite45ec662018-08-01 17:44:34 +0530921 del item_price_args[field]
922
Ankush Menat494bd9e2022-03-28 18:52:46 +0530923 general_price_list_rate = get_item_price(
924 item_price_args, item_code, ignore_party=args.get("ignore_party")
925 )
Don-Leopardoccdf1932020-01-09 03:54:43 -0300926
Nabin Haite45ec662018-08-01 17:44:34 +0530927 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530928 item_price_args["uom"] = args.get("stock_uom")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530929 general_price_list_rate = get_item_price(
930 item_price_args, item_code, ignore_party=args.get("ignore_party")
931 )
Nabin Haite45ec662018-08-01 17:44:34 +0530932
933 if general_price_list_rate:
934 item_price_data = general_price_list_rate
935
936 if item_price_data:
937 if item_price_data[0][2] == args.get("uom"):
938 return item_price_data[0][1]
Ankush Menat494bd9e2022-03-28 18:52:46 +0530939 elif not args.get("price_list_uom_dependant"):
Nabin Haite45ec662018-08-01 17:44:34 +0530940 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
941 else:
942 return item_price_data[0][1]
943
Ankush Menat494bd9e2022-03-28 18:52:46 +0530944
Nabin Haite45ec662018-08-01 17:44:34 +0530945def check_packing_list(price_list_rate_name, desired_qty, item_code):
946 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530947 Check if the desired qty is within the increment of the packing list.
948 :param price_list_rate_name: Name of Item Price
949 :param desired_qty: Desired Qt
950 :param item_code: str, Item Doctype field item_code
951 :param qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530952 """
953
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530954 flag = True
Nabin Haite45ec662018-08-01 17:44:34 +0530955 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530956 if item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +0530957 packing_increment = desired_qty % item_price.packing_unit
958
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530959 if packing_increment != 0:
960 flag = False
961
962 return flag
Rushabh Mehta1a763742014-10-03 16:36:43 +0530963
Ankush Menat494bd9e2022-03-28 18:52:46 +0530964
Nabin Hait436f5262014-02-10 14:47:54 +0530965def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +0530966 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +0530967
Ankush Menat494bd9e2022-03-28 18:52:46 +0530968 company_currency = frappe.get_cached_value("Company", args.company, "default_currency")
969 if not args.conversion_rate and args.currency == company_currency:
Anand Doshife13bfe2015-08-25 12:49:40 +0530970 args.conversion_rate = 1.0
971
Ankush Menat494bd9e2022-03-28 18:52:46 +0530972 if (
973 not args.ignore_conversion_rate
974 and args.conversion_rate == 1
975 and args.currency != company_currency
976 ):
977 args.conversion_rate = (
978 get_exchange_rate(args.currency, company_currency, args.transaction_date, "for_buying") or 1.0
979 )
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +0530980
Nabin Hait436f5262014-02-10 14:47:54 +0530981 # validate currency conversion rate
Ankush Menat494bd9e2022-03-28 18:52:46 +0530982 validate_conversion_rate(
983 args.currency, args.conversion_rate, meta.get_label("conversion_rate"), args.company
984 )
Anand Doshibd67e872014-04-11 16:51:27 +0530985
Ankush Menat494bd9e2022-03-28 18:52:46 +0530986 args.conversion_rate = flt(
987 args.conversion_rate,
988 get_field_precision(meta.get_field("conversion_rate"), frappe._dict({"fields": args})),
989 )
Anand Doshibd67e872014-04-11 16:51:27 +0530990
Nabin Hait06c8cf42019-05-16 19:17:02 +0530991 if args.price_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530992 if not args.plc_conversion_rate and args.price_list_currency == frappe.db.get_value(
993 "Price List", args.price_list, "currency", cache=True
994 ):
Nabin Hait06c8cf42019-05-16 19:17:02 +0530995 args.plc_conversion_rate = 1.0
Manas Solanki3504a232018-06-06 12:46:06 +0530996
Nabin Hait06c8cf42019-05-16 19:17:02 +0530997 # validate price list currency conversion rate
998 if not args.get("price_list_currency"):
999 throw(_("Price List Currency not selected"))
1000 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301001 validate_conversion_rate(
1002 args.price_list_currency,
1003 args.plc_conversion_rate,
1004 meta.get_label("plc_conversion_rate"),
1005 args.company,
1006 )
Anand Doshibd67e872014-04-11 16:51:27 +05301007
Nabin Hait06c8cf42019-05-16 19:17:02 +05301008 if meta.get_field("plc_conversion_rate"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301009 args.plc_conversion_rate = flt(
1010 args.plc_conversion_rate,
1011 get_field_precision(meta.get_field("plc_conversion_rate"), frappe._dict({"fields": args})),
1012 )
1013
Anand Doshibd67e872014-04-11 16:51:27 +05301014
Rushabh Mehtaf14b8092014-04-03 14:30:42 +05301015def get_party_item_code(args, item_doc, out):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301016 if args.transaction_type == "selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +05301017 out.customer_item_code = None
Nabin Hait34c551d2019-07-03 10:34:31 +05301018
Ankush Menat494bd9e2022-03-28 18:52:46 +05301019 if args.quotation_to and args.quotation_to != "Customer":
Nabin Hait34c551d2019-07-03 10:34:31 +05301020 return
1021
Nabin Hait79f091e2014-12-26 11:41:15 +05301022 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +05301023
1024 if customer_item_code:
1025 out.customer_item_code = customer_item_code[0].ref_code
1026 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +05301027 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +05301028 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
1029 if customer_group_item_code and not customer_group_item_code[0].customer_name:
1030 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +05301031
Ankush Menat494bd9e2022-03-28 18:52:46 +05301032 if args.transaction_type == "buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +05301033 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +05301034 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +05301035
Ankush Menat494bd9e2022-03-28 18:52:46 +05301036
rohitwaghchaure2ea593b2018-04-12 13:37:08 +05301037def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301038 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +05301039
Rushabh Mehta708e47a2018-08-08 16:37:31 +05301040 if not frappe.flags.pos_profile and not pos_profile:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301041 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get("pos_profile"))
Anand Doshibd67e872014-04-11 16:51:27 +05301042
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301043 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +05301044 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +05301045 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301046 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +05301047
Nabin Hait436f5262014-02-10 14:47:54 +05301048 if res.get("warehouse"):
s-aga-rc716dcc2022-12-29 12:34:18 +05301049 res.actual_qty = get_bin_details(
1050 args.item_code, res.warehouse, include_child_warehouses=True
1051 ).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +05301052
Nabin Hait436f5262014-02-10 14:47:54 +05301053 return res
1054
Ankush Menat494bd9e2022-03-28 18:52:46 +05301055
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301056@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301057def get_pos_profile(company, pos_profile=None, user=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301058 if pos_profile:
1059 return frappe.get_cached_doc("POS Profile", pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301060
1061 if not user:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301062 user = frappe.session["user"]
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301063
s-aga-r6b144ba2023-02-18 12:18:41 +05301064 pf = frappe.qb.DocType("POS Profile")
1065 pfu = frappe.qb.DocType("POS Profile User")
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301066
s-aga-r6b144ba2023-02-18 12:18:41 +05301067 query = (
1068 frappe.qb.from_(pf)
1069 .left_join(pfu)
1070 .on(pf.name == pfu.parent)
1071 .select(pf.star)
1072 .where((pfu.user == user) & (pfu.default == 1))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301073 )
Anand Doshibd67e872014-04-11 16:51:27 +05301074
s-aga-r6b144ba2023-02-18 12:18:41 +05301075 if company:
1076 query = query.where(pf.company == company)
1077
1078 pos_profile = query.run(as_dict=True)
1079
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301080 if not pos_profile and company:
s-aga-r6b144ba2023-02-18 12:18:41 +05301081 pos_profile = (
1082 frappe.qb.from_(pf)
1083 .left_join(pfu)
1084 .on(pf.name == pfu.parent)
1085 .select(pf.star)
1086 .where((pf.company == company) & (pf.disabled == 0))
1087 ).run(as_dict=True)
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301088
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301089 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +05301090
Ankush Menat494bd9e2022-03-28 18:52:46 +05301091
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301092@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +05301093def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +05301094 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +05301095 filters = {"parent": item_code, "uom": uom}
s-aga-r58c027d2023-02-28 15:14:34 +05301096
Rushabh Mehta724f9e52014-10-07 15:29:58 +05301097 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +05301098 filters["parent"] = ("in", (item_code, variant_of))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301099 conversion_factor = frappe.db.get_value("UOM Conversion Detail", filters, "conversion_factor")
Sagar Vora508189e2018-09-11 17:22:25 +05301100 if not conversion_factor:
1101 stock_uom = frappe.db.get_value("Item", item_code, "stock_uom")
1102 conversion_factor = get_uom_conv_factor(uom, stock_uom)
s-aga-r6b144ba2023-02-18 12:18:41 +05301103
rohitwaghchaureffdadbf2019-01-08 16:21:25 +05301104 return {"conversion_factor": conversion_factor or 1.0}
Nabin Hait08222152014-02-28 11:30:47 +05301105
Ankush Menat494bd9e2022-03-28 18:52:46 +05301106
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301107@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +05301108def get_projected_qty(item_code, warehouse):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301109 return {
1110 "projected_qty": frappe.db.get_value(
1111 "Bin", {"item_code": item_code, "warehouse": warehouse}, "projected_qty"
1112 )
1113 }
1114
Nabin Hait08222152014-02-28 11:30:47 +05301115
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301116@frappe.whitelist()
s-aga-rc716dcc2022-12-29 12:34:18 +05301117def get_bin_details(item_code, warehouse, company=None, include_child_warehouses=False):
ruthra kumarbe382052023-01-16 08:50:39 +05301118 bin_details = {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
s-aga-rc716dcc2022-12-29 12:34:18 +05301119
1120 if warehouse:
s-aga-rc3911a52022-12-29 16:38:08 +05301121 from frappe.query_builder.functions import Coalesce, Sum
s-aga-r58c027d2023-02-28 15:14:34 +05301122
s-aga-rc716dcc2022-12-29 12:34:18 +05301123 from erpnext.stock.doctype.warehouse.warehouse import get_child_warehouses
1124
1125 warehouses = get_child_warehouses(warehouse) if include_child_warehouses else [warehouse]
s-aga-rc3911a52022-12-29 16:38:08 +05301126
1127 bin = frappe.qb.DocType("Bin")
1128 bin_details = (
1129 frappe.qb.from_(bin)
1130 .select(
1131 Coalesce(Sum(bin.projected_qty), 0).as_("projected_qty"),
1132 Coalesce(Sum(bin.actual_qty), 0).as_("actual_qty"),
1133 Coalesce(Sum(bin.reserved_qty), 0).as_("reserved_qty"),
1134 )
1135 .where((bin.item_code == item_code) & (bin.warehouse.isin(warehouses)))
1136 ).run(as_dict=True)[0]
s-aga-rc716dcc2022-12-29 12:34:18 +05301137
Anupam4980dd62021-03-15 11:37:46 +05301138 if company:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301139 bin_details["company_total_stock"] = get_company_total_stock(item_code, company)
s-aga-rb425c2d2023-01-02 11:25:13 +05301140
Anupam4980dd62021-03-15 11:37:46 +05301141 return bin_details
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301142
Ankush Menat494bd9e2022-03-28 18:52:46 +05301143
Anupam4980dd62021-03-15 11:37:46 +05301144def get_company_total_stock(item_code, company):
s-aga-r6b144ba2023-02-18 12:18:41 +05301145 bin = frappe.qb.DocType("Bin")
1146 wh = frappe.qb.DocType("Warehouse")
1147
1148 return (
1149 frappe.qb.from_(bin)
1150 .inner_join(wh)
1151 .on(bin.warehouse == wh.name)
1152 .select(Sum(bin.actual_qty))
1153 .where((wh.company == company) & (bin.item_code == item_code))
1154 ).run()[0][0]
Ankush Menat494bd9e2022-03-28 18:52:46 +05301155
Anupam4980dd62021-03-15 11:37:46 +05301156
1157@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +05301158def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +07001159 from erpnext.stock.doctype.batch import batch
Ankush Menat494bd9e2022-03-28 18:52:46 +05301160
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +05301161 if batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301162 return {"actual_batch_qty": batch.get_batch_qty(batch_no, warehouse)}
1163
Rushabh Mehta1e8025b2015-07-24 15:16:25 +05301164
Anand Doshidffec8f2014-07-01 17:45:15 +05301165@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301166def apply_price_list(args, as_doc=False):
1167 """Apply pricelist on a document-like dict object and return as
1168 {'parent': dict, 'children': list}
1169
1170 :param args: See below
1171 :param as_doc: Updates value in the passed dict
1172
Ankush Menat494bd9e2022-03-28 18:52:46 +05301173 args = {
1174 "doctype": "",
1175 "name": "",
1176 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
1177 "conversion_rate": 1.0,
1178 "selling_price_list": None,
1179 "price_list_currency": None,
1180 "price_list_uom_dependant": None,
1181 "plc_conversion_rate": 1.0,
1182 "doctype": "",
1183 "name": "",
1184 "supplier": None,
1185 "transaction_date": None,
1186 "conversion_rate": 1.0,
1187 "buying_price_list": None,
1188 "ignore_pricing_rule": 0/1
1189 }
Anand Doshidffec8f2014-07-01 17:45:15 +05301190 """
1191 args = process_args(args)
1192
1193 parent = get_price_list_currency_and_exchange_rate(args)
Maricae8bc9122021-04-19 11:05:21 +05301194 args.update(parent)
1195
Anand Doshidffec8f2014-07-01 17:45:15 +05301196 children = []
1197
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301198 if "items" in args:
1199 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +05301200 args.update(parent)
1201
1202 for item in item_list:
1203 args_copy = frappe._dict(args.copy())
1204 args_copy.update(item)
1205 item_details = apply_price_list_on_item(args_copy)
1206 children.append(item_details)
1207
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301208 if as_doc:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301209 args.price_list_currency = (parent.price_list_currency,)
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301210 args.plc_conversion_rate = parent.plc_conversion_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +05301211 if args.get("items"):
1212 for i, item in enumerate(args.get("items")):
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301213 for fieldname in children[i]:
1214 # if the field exists in the original doc
1215 # update the value
1216 if fieldname in item and fieldname not in ("name", "doctype"):
1217 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301218 return args
1219 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301220 return {"parent": parent, "children": children}
1221
Anand Doshidffec8f2014-07-01 17:45:15 +05301222
1223def apply_price_list_on_item(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301224 item_doc = frappe.db.get_value("Item", args.item_code, ["name", "variant_of"], as_dict=1)
Ankush16d4de52021-08-09 10:41:24 +05301225 item_details = get_price_list_rate(args, item_doc)
Deepesh Gargb741ae12022-12-02 17:14:06 +05301226 item_details.update(get_pricing_rule_for_item(args))
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301227
Anand Doshidffec8f2014-07-01 17:45:15 +05301228 return item_details
1229
Ankush Menat494bd9e2022-03-28 18:52:46 +05301230
Anand Doshidffec8f2014-07-01 17:45:15 +05301231def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +05301232 if not args.price_list:
1233 return {}
1234
Ankush Menat494bd9e2022-03-28 18:52:46 +05301235 if args.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
Shreya3f778522018-05-15 16:59:20 +05301236 args.update({"exchange_rate": "for_selling"})
Ankush Menat494bd9e2022-03-28 18:52:46 +05301237 elif args.doctype in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]:
Shreya3f778522018-05-15 16:59:20 +05301238 args.update({"exchange_rate": "for_buying"})
1239
rohitwaghchaurea85ddf22019-11-19 18:47:48 +05301240 price_list_details = get_price_list_details(args.price_list)
1241
1242 price_list_currency = price_list_details.get("currency")
1243 price_list_uom_dependant = price_list_details.get("price_list_uom_dependant")
1244
Anand Doshidffec8f2014-07-01 17:45:15 +05301245 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +01001246 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +05301247
Ankush Menat494bd9e2022-03-28 18:52:46 +05301248 if (not plc_conversion_rate) or (
1249 price_list_currency
1250 and args.price_list_currency
1251 and price_list_currency != args.price_list_currency
1252 ):
1253 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
1254 plc_conversion_rate = (
1255 get_exchange_rate(
1256 price_list_currency, company_currency, args.transaction_date, args.exchange_rate
1257 )
1258 or plc_conversion_rate
1259 )
Anand Doshidffec8f2014-07-01 17:45:15 +05301260
Ankush Menat494bd9e2022-03-28 18:52:46 +05301261 return frappe._dict(
1262 {
1263 "price_list_currency": price_list_currency,
1264 "price_list_uom_dependant": price_list_uom_dependant,
1265 "plc_conversion_rate": plc_conversion_rate or 1,
1266 }
1267 )
1268
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +05301269
1270@frappe.whitelist()
1271def get_default_bom(item_code=None):
marination9f2d3252022-06-14 17:20:44 +05301272 def _get_bom(item):
1273 bom = frappe.get_all(
1274 "BOM", dict(item=item, is_active=True, is_default=True, docstatus=1), limit=1
Ankush Menat494bd9e2022-03-28 18:52:46 +05301275 )
marination9f2d3252022-06-14 17:20:44 +05301276 return bom[0].name if bom else None
1277
1278 if not item_code:
1279 return
1280
1281 bom_name = _get_bom(item_code)
1282
1283 template_item = frappe.db.get_value("Item", item_code, "variant_of")
1284 if not bom_name and template_item:
1285 bom_name = _get_bom(template_item)
1286
1287 return bom_name
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301288
Ankush Menat494bd9e2022-03-28 18:52:46 +05301289
Deepesh Garg15ff6a52020-02-18 12:28:41 +05301290@frappe.whitelist()
Manas Solanki087a2252018-05-04 16:02:38 +05301291def get_valuation_rate(item_code, company, warehouse=None):
Manas Solankib16a4ec2018-05-04 16:49:33 +05301292 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +05301293 item_group = get_item_group_defaults(item_code, company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001294 brand = get_brand_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +05301295 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +05301296 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +05301297 if not warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301298 warehouse = (
1299 item.get("default_warehouse")
1300 or item_group.get("default_warehouse")
1301 or brand.get("default_warehouse")
1302 )
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301303
Ankush Menat494bd9e2022-03-28 18:52:46 +05301304 return frappe.db.get_value(
1305 "Bin", {"item_code": item_code, "warehouse": warehouse}, ["valuation_rate"], as_dict=True
1306 ) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301307
Manas Solankie3910fb2018-05-16 15:50:17 +05301308 elif not item.get("is_stock_item"):
s-aga-r6b144ba2023-02-18 12:18:41 +05301309 pi_item = frappe.qb.DocType("Purchase Invoice Item")
1310 valuation_rate = (
1311 frappe.qb.from_(pi_item)
1312 .select((Sum(pi_item.base_net_amount) / Sum(pi_item.qty * pi_item.conversion_factor)))
s-aga-r58c027d2023-02-28 15:14:34 +05301313 .where((pi_item.docstatus == 1) & (pi_item.item_code == item_code))
s-aga-r6b144ba2023-02-18 12:18:41 +05301314 ).run()
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301315
Saurabhbd01a812016-03-07 14:32:23 +05301316 if valuation_rate:
1317 return {"valuation_rate": valuation_rate[0][0] or 0.0}
1318 else:
1319 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301320
Ankush Menat494bd9e2022-03-28 18:52:46 +05301321
Saurabh2d7af632016-02-26 11:09:20 +05301322def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +05301323 if out.valuation_rate:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301324 out.update({"gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)})
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301325
Saurabhd3135532016-02-25 18:59:20 +05301326 return out
mbauskar6f603392016-01-21 16:10:22 +05301327
Ankush Menat494bd9e2022-03-28 18:52:46 +05301328
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301329@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301330def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaure648efca2023-03-28 12:16:27 +05301331 serial_nos = serial_nos or []
1332 return serial_nos
Manas Solankie5e87f72018-05-28 20:07:08 +05301333
1334
1335def update_party_blanket_order(args, out):
ronelvcabrera370cdc02019-12-04 18:37:11 +08001336 if out["against_blanket_order"]:
1337 blanket_order_details = get_blanket_order_details(args)
1338 if blanket_order_details:
1339 out.update(blanket_order_details)
Manas Solankie5e87f72018-05-28 20:07:08 +05301340
Ankush Menat494bd9e2022-03-28 18:52:46 +05301341
Manas Solankie5e87f72018-05-28 20:07:08 +05301342@frappe.whitelist()
1343def get_blanket_order_details(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301344 if isinstance(args, str):
Manas Solankie5e87f72018-05-28 20:07:08 +05301345 args = frappe._dict(json.loads(args))
1346
1347 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +05301348
s-aga-r6b144ba2023-02-18 12:18:41 +05301349 if args.item_code:
1350 bo = frappe.qb.DocType("Blanket Order")
1351 bo_item = frappe.qb.DocType("Blanket Order Item")
1352
1353 query = (
1354 frappe.qb.from_(bo)
1355 .from_(bo_item)
1356 .select(bo_item.rate.as_("blanket_order_rate"), bo.name.as_("blanket_order"))
1357 .where(
1358 (bo.company == args.company)
1359 & (bo_item.item_code == args.item_code)
1360 & (bo.docstatus == 1)
1361 & (bo.name == bo_item.parent)
1362 )
Ankush Menat494bd9e2022-03-28 18:52:46 +05301363 )
Nabin Hait2737b082018-06-14 18:07:22 +05301364
s-aga-r6b144ba2023-02-18 12:18:41 +05301365 if args.customer and args.doctype == "Sales Order":
1366 query = query.where(bo.customer == args.customer)
1367 elif args.supplier and args.doctype == "Purchase Order":
1368 query = query.where(bo.supplier == args.supplier)
1369 if args.blanket_order:
1370 query = query.where(bo.name == args.blanket_order)
1371 if args.transaction_date:
1372 query = query.where(bo.to_date >= args.transaction_date)
1373
1374 blanket_order_details = query.run(as_dict=True)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301375 blanket_order_details = blanket_order_details[0] if blanket_order_details else ""
s-aga-r6b144ba2023-02-18 12:18:41 +05301376
Manas Solankie5e87f72018-05-28 20:07:08 +05301377 return blanket_order_details