blob: 2cf3797a36b9ef228b625ba7b50ee7d77d36b05c [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
s-aga-r6b144ba2023-02-18 12:18:41 +053011from frappe.query_builder.functions import CombineDatetime, 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
22from erpnext.stock.doctype.batch.batch import get_batch_no
23from 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 Garg4c61ee32023-04-02 09:35:27 +053038def get_item_details(
39 args,
40 doc=None,
41 for_validate=False,
42 overwrite_warehouse=True,
43 return_basic_details=False,
44 basic_details=None,
45):
Nabin Hait436f5262014-02-10 14:47:54 +053046 """
Ankush Menat494bd9e2022-03-28 18:52:46 +053047 args = {
48 "item_code": "",
49 "warehouse": None,
50 "customer": "",
51 "conversion_rate": 1.0,
52 "selling_price_list": None,
53 "price_list_currency": None,
54 "plc_conversion_rate": 1.0,
55 "doctype": "",
56 "name": "",
57 "supplier": None,
58 "transaction_date": None,
59 "conversion_rate": 1.0,
60 "buying_price_list": None,
Sagar Sharma409df262022-04-19 14:57:31 +053061 "is_subcontracted": 0/1,
Ankush Menat494bd9e2022-03-28 18:52:46 +053062 "ignore_pricing_rule": 0/1
63 "project": ""
64 "set_warehouse": ""
65 }
Nabin Hait436f5262014-02-10 14:47:54 +053066 """
Suraj Shetty182f4de2019-08-16 08:16:22 +053067
Anand Doshidffec8f2014-07-01 17:45:15 +053068 args = process_args(args)
marination392f3232020-07-14 17:03:17 +053069 for_validate = process_string_args(for_validate)
70 overwrite_warehouse = process_string_args(overwrite_warehouse)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053071 item = frappe.get_cached_doc("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053072 validate_item_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053073
Ankush Menat8fe5feb2021-11-04 19:48:32 +053074 if isinstance(doc, str):
Deepesh Gargef0d26c2020-01-06 15:34:15 +053075 doc = json.loads(doc)
76
Deepesh Gargef0d26c2020-01-06 15:34:15 +053077 if doc:
Sagar Vora1a3997a2022-06-16 17:03:47 +000078 args["transaction_date"] = doc.get("transaction_date") or doc.get("posting_date")
Deepesh Gargef0d26c2020-01-06 15:34:15 +053079
Sagar Vora1a3997a2022-06-16 17:03:47 +000080 if doc.get("doctype") == "Purchase Invoice":
81 args["bill_date"] = doc.get("bill_date")
82
Deepesh Garg4c61ee32023-04-02 09:35:27 +053083 if not basic_details:
84 out = get_basic_details(args, item, overwrite_warehouse)
85 else:
86 out = basic_details
87
88 basic_details = out.copy()
89
Saif Ur Rehman67786682018-12-27 02:11:07 +050090 get_item_tax_template(args, item, out)
Ankush Menat494bd9e2022-03-28 18:52:46 +053091 out["item_tax_rate"] = get_item_tax_map(
92 args.company,
93 args.get("item_tax_template")
94 if out.get("item_tax_template") is None
95 else out.get("item_tax_template"),
96 as_json=True,
97 )
Saif Ur Rehman67786682018-12-27 02:11:07 +050098
Rushabh Mehta708e47a2018-08-08 16:37:31 +053099 get_party_item_code(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +0530100
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530101 set_valuation_rate(out, args)
Anand Doshibd67e872014-04-11 16:51:27 +0530102
Manas Solankie5e87f72018-05-28 20:07:08 +0530103 update_party_blanket_order(args, out)
104
HENRY Florian231fe412023-02-13 16:26:05 +0100105 # Never try to find a customer price if customer is set in these Doctype
106 current_customer = args.customer
107 if args.get("doctype") in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]:
108 args.customer = None
109
Ankush16d4de52021-08-09 10:41:24 +0530110 out.update(get_price_list_rate(args, item))
Nabin Hait436f5262014-02-10 14:47:54 +0530111
HENRY Florian231fe412023-02-13 16:26:05 +0100112 args.customer = current_customer
113
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530114 if args.customer and cint(args.is_pos):
Anuja Pawarf132ed42021-05-07 12:11:09 +0530115 out.update(get_pos_profile_item_details(args.company, args, update_data=True))
Rushabh Mehta6b537922017-03-14 16:59:11 +0530116
Ankush Menat494bd9e2022-03-28 18:52:46 +0530117 if (
118 args.get("doctype") == "Material Request"
119 and args.get("material_request_type") == "Material Transfer"
120 ):
Nabin Haitda17f9c2020-05-01 18:16:25 +0530121 out.update(get_bin_details(args.item_code, args.get("from_warehouse")))
122
123 elif out.get("warehouse"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530124 if doc and doc.get("doctype") == "Purchase Order":
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530125 # calculate company_total_stock only for po
s-aga-rc716dcc2022-12-29 12:34:18 +0530126 bin_details = get_bin_details(
127 args.item_code, out.warehouse, args.company, include_child_warehouses=True
128 )
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530129 else:
s-aga-rc716dcc2022-12-29 12:34:18 +0530130 bin_details = get_bin_details(args.item_code, out.warehouse, include_child_warehouses=True)
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530131
132 out.update(bin_details)
Anand Doshibd67e872014-04-11 16:51:27 +0530133
Nabin Haita3dd72a2014-05-28 12:49:20 +0530134 # update args with out, if key or value not exists
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530135 for key, value in out.items():
Nabin Haita3dd72a2014-05-28 12:49:20 +0530136 if args.get(key) is None:
137 args[key] = value
138
Deepesh Garg6192af52022-12-08 18:04:40 +0530139 data = get_pricing_rule_for_item(args, doc=doc, for_validate=for_validate)
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530140
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530141 out.update(data)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530142
143 update_stock(args, out)
144
145 if args.transaction_date and item.lead_time_days:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530146 out.schedule_date = out.lead_time_date = add_days(args.transaction_date, item.lead_time_days)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530147
Sagar Sharma409df262022-04-19 14:57:31 +0530148 if args.get("is_subcontracted"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530149 out.bom = args.get("bom") or get_default_bom(args.item_code)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530150
151 get_gross_profit(out)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530152 if args.doctype == "Material Request":
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530153 out.rate = args.rate or out.price_list_rate
Rohit Waghchaure1bc53a32021-03-31 15:28:26 +0530154 out.amount = flt(args.qty) * flt(out.rate)
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530155
Ankush Menat1e976642022-02-15 10:57:06 +0530156 out = remove_standard_fields(out)
Deepesh Garg4c61ee32023-04-02 09:35:27 +0530157
158 if return_basic_details:
159 return out, basic_details
160 else:
161 return out
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530162
Ankush Menat494bd9e2022-03-28 18:52:46 +0530163
Ankush Menat1e976642022-02-15 10:57:06 +0530164def remove_standard_fields(details):
165 for key in child_table_fields + default_fields:
166 details.pop(key, None)
167 return details
168
169
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530170def update_stock(args, out):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530171 if (
172 (
173 args.get("doctype") == "Delivery Note"
174 or (args.get("doctype") == "Sales Invoice" and args.get("update_stock"))
175 )
176 and out.warehouse
177 and out.stock_qty > 0
178 ):
pratu16x7577e4c42017-06-23 11:39:03 +0530179
Nabin Hait8fac2ad2017-05-18 11:54:24 +0530180 if out.has_batch_no and not args.get("batch_no"):
Rushabh Mehta551406a2017-04-21 12:40:19 +0530181 out.batch_no = get_batch_no(out.item_code, out.warehouse, out.qty)
rohitwaghchaure2fb8cc52017-11-29 13:50:04 +0530182 actual_batch_qty = get_batch_qty(out.batch_no, out.warehouse, out.item_code)
183 if actual_batch_qty:
184 out.update(actual_batch_qty)
Shreya14bd43d2018-04-27 16:24:05 +0530185
Ankush Menat494bd9e2022-03-28 18:52:46 +0530186 if out.has_serial_no and args.get("batch_no"):
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530187 reserved_so = get_so_reservation_for_item(args)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530188 out.batch_no = args.get("batch_no")
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530189 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Shreya14bd43d2018-04-27 16:24:05 +0530190
191 elif out.has_serial_no:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530192 reserved_so = get_so_reservation_for_item(args)
193 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Rushabh Mehta551406a2017-04-21 12:40:19 +0530194
Ankush Menatc8ead0a2022-04-01 20:25:30 +0530195 if not out.serial_no:
196 out.pop("serial_no", None)
197
Anand Doshibd67e872014-04-11 16:51:27 +0530198
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530199def set_valuation_rate(out, args):
Nabin Hait50238c32018-08-08 18:43:04 +0530200 if frappe.db.exists("Product Bundle", args.item_code, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530201 valuation_rate = 0.0
202 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530203
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530204 for bundle_item in bundled_items.items:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530205 valuation_rate += flt(
206 get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get(
207 "valuation_rate"
208 )
209 * bundle_item.qty
210 )
Anand Doshi70f57eb2015-11-27 14:37:40 +0530211
Ankush Menat494bd9e2022-03-28 18:52:46 +0530212 out.update({"valuation_rate": valuation_rate})
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530213
214 else:
215 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
216
Nabin Hait436f5262014-02-10 14:47:54 +0530217
Anand Doshidffec8f2014-07-01 17:45:15 +0530218def process_args(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530219 if isinstance(args, str):
Anand Doshidffec8f2014-07-01 17:45:15 +0530220 args = json.loads(args)
221
222 args = frappe._dict(args)
223
Anand Doshidffec8f2014-07-01 17:45:15 +0530224 if not args.get("price_list"):
225 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
226
Devin Slauenwhite55276f12022-05-25 00:05:22 -0400227 if not args.item_code and args.barcode:
Anand Doshidffec8f2014-07-01 17:45:15 +0530228 args.item_code = get_item_code(barcode=args.barcode)
229 elif not args.item_code and args.serial_no:
230 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530231
mbauskar6f603392016-01-21 16:10:22 +0530232 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530233 return args
234
Ankush Menat494bd9e2022-03-28 18:52:46 +0530235
marination392f3232020-07-14 17:03:17 +0530236def process_string_args(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530237 if isinstance(args, str):
marination392f3232020-07-14 17:03:17 +0530238 args = json.loads(args)
239 return args
tundebabzyacccdb32017-11-23 08:35:15 +0100240
Ankush Menat494bd9e2022-03-28 18:52:46 +0530241
Neil Trini Lasrado4abda672015-02-25 17:34:27 +0530242@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530243def get_item_code(barcode=None, serial_no=None):
244 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100245 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530246 if not item_code:
247 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530248 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530249 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530250 if not item_code:
251 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530252
Nabin Hait436f5262014-02-10 14:47:54 +0530253 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530254
tundebabzyacccdb32017-11-23 08:35:15 +0100255
Nabin Hait436f5262014-02-10 14:47:54 +0530256def validate_item_details(args, item):
257 if not args.company:
258 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530259
Nabin Hait436f5262014-02-10 14:47:54 +0530260 from erpnext.stock.doctype.item.item import validate_end_of_life
Ankush Menat494bd9e2022-03-28 18:52:46 +0530261
Anand Doshi21e09a22015-10-29 12:21:41 +0530262 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530263
Rohit Waghchaure2c83fff2023-01-18 23:21:29 +0530264 if cint(item.has_variants):
265 msg = f"Item {item.name} is a template, please select one of its variants"
266
267 throw(_(msg), title=_("Template Item Selected"))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530268
tundebabzyacccdb32017-11-23 08:35:15 +0100269 elif args.transaction_type == "buying" and args.doctype != "Material Request":
s-aga-r6d89b2f2022-06-18 15:46:59 +0530270 if args.get("is_subcontracted"):
271 if args.get("is_old_subcontracting_flow"):
272 if item.is_sub_contracted_item != 1:
273 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
274 else:
275 if item.is_stock_item:
276 throw(_("Item {0} must be a Non-Stock Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530277
tundebabzyacccdb32017-11-23 08:35:15 +0100278
Suraj Shetty182f4de2019-08-16 08:16:22 +0530279def get_basic_details(args, item, overwrite_warehouse=True):
tundebabzyacccdb32017-11-23 08:35:15 +0100280 """
281 :param args: {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530282 "item_code": "",
283 "warehouse": None,
284 "customer": "",
285 "conversion_rate": 1.0,
286 "selling_price_list": None,
287 "price_list_currency": None,
288 "price_list_uom_dependant": None,
289 "plc_conversion_rate": 1.0,
290 "doctype": "",
291 "name": "",
292 "supplier": None,
293 "transaction_date": None,
294 "conversion_rate": 1.0,
295 "buying_price_list": None,
Sagar Sharma409df262022-04-19 14:57:31 +0530296 "is_subcontracted": 0/1,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530297 "ignore_pricing_rule": 0/1
298 "project": "",
299 barcode: "",
300 serial_no: "",
301 currency: "",
302 update_stock: "",
303 price_list: "",
304 company: "",
305 order_type: "",
306 is_pos: "",
307 project: "",
308 qty: "",
309 stock_qty: "",
310 conversion_factor: "",
311 against_blanket_order: 0/1
312 }
tundebabzyacccdb32017-11-23 08:35:15 +0100313 :param item: `item_code` of Item object
314 :return: frappe._dict
315 """
316
Rushabh Mehta1a763742014-10-03 16:36:43 +0530317 if not item:
318 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530319
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530320 if item.variant_of:
321 item.update_template_tables()
322
Manas Solankib16a4ec2018-05-04 16:49:33 +0530323 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530324 item_group_defaults = get_item_group_defaults(item.name, args.company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500325 brand_defaults = get_brand_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530326
Ankush Menat494bd9e2022-03-28 18:52:46 +0530327 defaults = frappe._dict(
328 {
329 "item_defaults": item_defaults,
330 "item_group_defaults": item_group_defaults,
331 "brand_defaults": brand_defaults,
332 }
333 )
marinatione05013e2020-04-06 22:13:13 +0530334
Saqib438e0432020-04-03 10:02:56 +0530335 warehouse = get_item_warehouse(item, args, overwrite_warehouse, defaults)
Nabin Hait36028bf2014-02-12 19:09:28 +0530336
Ankush Menat494bd9e2022-03-28 18:52:46 +0530337 if args.get("doctype") == "Material Request" and not args.get("material_request_type"):
338 args["material_request_type"] = frappe.db.get_value(
339 "Material Request", args.get("name"), "material_request_type", cache=True
340 )
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530341
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530342 expense_account = None
343
Ankush Menat494bd9e2022-03-28 18:52:46 +0530344 if args.get("doctype") == "Purchase Invoice" and item.is_fixed_asset:
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530345 from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530346
Ankush Menat494bd9e2022-03-28 18:52:46 +0530347 expense_account = get_asset_category_account(
348 fieldname="fixed_asset_account", item=args.item_code, company=args.company
349 )
350
351 # Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
352 if not args.get("uom"):
353 if args.get("doctype") in sales_doctypes:
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530354 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
Ankush Menat494bd9e2022-03-28 18:52:46 +0530355 elif (args.get("doctype") in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]) or (
356 args.get("doctype") == "Material Request" and args.get("material_request_type") == "Purchase"
357 ):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530358 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
359 else:
360 args.uom = item.stock_uom
361
Sagar Vora57038c32022-11-09 18:56:09 +0530362 # Set stock UOM in args, so that it can be used while fetching item price
363 args.stock_uom = item.stock_uom
364
Ankush Menat494bd9e2022-03-28 18:52:46 +0530365 if args.get("batch_no") and item.name != frappe.get_cached_value(
366 "Batch", args.get("batch_no"), "item"
367 ):
368 args["batch_no"] = ""
Rohit Waghchauree1f07042021-08-23 14:27:55 +0530369
Ankush Menat494bd9e2022-03-28 18:52:46 +0530370 out = frappe._dict(
371 {
372 "item_code": item.name,
373 "item_name": item.item_name,
374 "description": cstr(item.description).strip(),
375 "image": cstr(item.image).strip(),
376 "warehouse": warehouse,
377 "income_account": get_default_income_account(
378 args, item_defaults, item_group_defaults, brand_defaults
379 ),
380 "expense_account": expense_account
381 or get_default_expense_account(args, item_defaults, item_group_defaults, brand_defaults),
382 "discount_account": get_default_discount_account(args, item_defaults),
Deepesh Garg3ce64172022-04-11 14:35:22 +0530383 "provisional_expense_account": get_provisional_account(args, item_defaults),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530384 "cost_center": get_default_cost_center(
385 args, item_defaults, item_group_defaults, brand_defaults
386 ),
387 "has_serial_no": item.has_serial_no,
388 "has_batch_no": item.has_batch_no,
389 "batch_no": args.get("batch_no"),
390 "uom": args.uom,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530391 "stock_uom": item.stock_uom,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530392 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
393 "qty": flt(args.qty) or 1.0,
394 "stock_qty": flt(args.qty) or 1.0,
395 "price_list_rate": 0.0,
396 "base_price_list_rate": 0.0,
397 "rate": 0.0,
398 "base_rate": 0.0,
399 "amount": 0.0,
400 "base_amount": 0.0,
401 "net_rate": 0.0,
402 "net_amount": 0.0,
403 "discount_percentage": 0.0,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530404 "discount_amount": flt(args.discount_amount) or 0.0,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530405 "supplier": get_default_supplier(args, item_defaults, item_group_defaults, brand_defaults),
406 "update_stock": args.get("update_stock")
407 if args.get("doctype") in ["Sales Invoice", "Purchase Invoice"]
408 else 0,
409 "delivered_by_supplier": item.delivered_by_supplier
410 if args.get("doctype") in ["Sales Order", "Sales Invoice"]
411 else 0,
412 "is_fixed_asset": item.is_fixed_asset,
413 "last_purchase_rate": item.last_purchase_rate
414 if args.get("doctype") in ["Purchase Order"]
415 else 0,
416 "transaction_date": args.get("transaction_date"),
417 "against_blanket_order": args.get("against_blanket_order"),
418 "bom_no": item.get("default_bom"),
419 "weight_per_unit": args.get("weight_per_unit") or item.get("weight_per_unit"),
420 "weight_uom": args.get("weight_uom") or item.get("weight_uom"),
421 "grant_commission": item.get("grant_commission"),
422 }
423 )
Anand Doshibd67e872014-04-11 16:51:27 +0530424
Zlash65627be1d2019-01-15 14:16:32 +0530425 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zlash6580f5cb02018-08-29 11:39:08 +0530426 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530427
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530428 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530429 if item.stock_uom == args.uom:
430 out.conversion_factor = 1.0
431 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530432 out.conversion_factor = args.conversion_factor or get_conversion_factor(item.name, args.uom).get(
433 "conversion_factor"
434 )
mbauskar287fe812017-04-10 19:15:57 +0530435
436 args.conversion_factor = out.conversion_factor
437 out.stock_qty = out.qty * out.conversion_factor
Saqib Ansari3713ae72022-02-14 11:33:34 +0530438 args.stock_qty = out.stock_qty
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530439
Shreya Shah44fa9a62018-01-08 14:58:20 +0530440 # calculate last purchase rate
Rohit Waghchaureec171fc2023-01-09 18:49:48 +0530441 if args.get("doctype") in purchase_doctypes and not frappe.db.get_single_value(
442 "Buying Settings", "disable_last_purchase_rate"
443 ):
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530444 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +0530445
446 out.last_purchase_rate = item_last_purchase_rate(
447 args.name, args.conversion_rate, item.name, out.conversion_factor
448 )
Shreya Shah44fa9a62018-01-08 14:58:20 +0530449
Nabin Haitb09ed412015-02-17 10:33:58 +0530450 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530451 for d in [
452 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530453 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530454 ["Cost Center", "cost_center", "cost_center"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530455 ["Warehouse", "warehouse", ""],
456 ]:
457 if not out[d[1]]:
458 out[d[1]] = frappe.get_cached_value("Company", args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530459
Ankush Menat64905182022-03-09 15:37:14 +0530460 for fieldname in ("item_name", "item_group", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530461 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530462
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530463 if args.get("manufacturer"):
464 part_no = get_item_manufacturer_part_no(args.get("item_code"), args.get("manufacturer"))
465 if part_no:
466 out["manufacturer_part_no"] = part_no
467 else:
468 out["manufacturer_part_no"] = None
469 out["manufacturer"] = None
marination3e7a8ab2020-04-07 21:00:57 +0530470 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530471 data = frappe.get_value(
472 "Item", item.name, ["default_item_manufacturer", "default_manufacturer_part_no"], as_dict=1
473 )
rohitwaghchaurebe16e5c2020-05-01 10:50:17 +0530474
475 if data:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530476 out.update(
477 {
478 "manufacturer": data.default_item_manufacturer,
479 "manufacturer_part_no": data.default_manufacturer_part_no,
480 }
481 )
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530482
Ankush Menat494bd9e2022-03-28 18:52:46 +0530483 child_doctype = args.doctype + " Item"
Nabin Hait34c551d2019-07-03 10:34:31 +0530484 meta = frappe.get_meta(child_doctype)
485 if meta.get_field("barcode"):
486 update_barcode_value(out)
487
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530488 if out.get("weight_per_unit"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530489 out["total_weight"] = out.weight_per_unit * out.stock_qty
Rohit Waghchaurebde159a2021-03-22 23:36:48 +0530490
Nabin Hait436f5262014-02-10 14:47:54 +0530491 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530492
Ankush Menat494bd9e2022-03-28 18:52:46 +0530493
Chillar Anand772d4752021-10-06 22:28:48 +0530494def get_item_warehouse(item, args, overwrite_warehouse, defaults=None):
Saqib438e0432020-04-03 10:02:56 +0530495 if not defaults:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530496 defaults = frappe._dict(
497 {
498 "item_defaults": get_item_defaults(item.name, args.company),
499 "item_group_defaults": get_item_group_defaults(item.name, args.company),
500 "brand_defaults": get_brand_defaults(item.name, args.company),
501 }
502 )
Saqib438e0432020-04-03 10:02:56 +0530503
504 if overwrite_warehouse or not args.warehouse:
505 warehouse = (
Ankush Menat494bd9e2022-03-28 18:52:46 +0530506 args.get("set_warehouse")
507 or defaults.item_defaults.get("default_warehouse")
508 or defaults.item_group_defaults.get("default_warehouse")
509 or defaults.brand_defaults.get("default_warehouse")
510 or args.get("warehouse")
Saqib438e0432020-04-03 10:02:56 +0530511 )
512
513 if not warehouse:
514 defaults = frappe.defaults.get_defaults() or {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530515 warehouse_exists = frappe.db.exists(
516 "Warehouse", {"name": defaults.default_warehouse, "company": args.company}
517 )
Saqib438e0432020-04-03 10:02:56 +0530518 if defaults.get("default_warehouse") and warehouse_exists:
519 warehouse = defaults.default_warehouse
520
521 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530522 warehouse = args.get("warehouse")
marinatione05013e2020-04-06 22:13:13 +0530523
Marica3b1be2b2020-10-22 17:04:31 +0530524 if not warehouse:
525 default_warehouse = frappe.db.get_single_value("Stock Settings", "default_warehouse")
526 if frappe.db.get_value("Warehouse", default_warehouse, "company") == args.company:
527 return default_warehouse
528
Saqib438e0432020-04-03 10:02:56 +0530529 return warehouse
530
Ankush Menat494bd9e2022-03-28 18:52:46 +0530531
Nabin Hait34c551d2019-07-03 10:34:31 +0530532def update_barcode_value(out):
Nabin Hait34c551d2019-07-03 10:34:31 +0530533 barcode_data = get_barcode_data([out])
534
535 # If item has one barcode then update the value of the barcode field
536 if barcode_data and len(barcode_data.get(out.item_code)) == 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530537 out["barcode"] = barcode_data.get(out.item_code)[0]
538
Nabin Hait34c551d2019-07-03 10:34:31 +0530539
Saqiba6f98d42020-07-23 18:51:26 +0530540def get_barcode_data(items_list):
541 # get itemwise batch no data
542 # exmaple: {'LED-GRE': [Batch001, Batch002]}
543 # where LED-GRE is item code, SN0001 is serial no and Pune is warehouse
544
545 itemwise_barcode = {}
546 for item in items_list:
s-aga-r6b144ba2023-02-18 12:18:41 +0530547 barcodes = frappe.db.get_all(
548 "Item Barcode", filters={"parent": item.item_code}, fields="barcode"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530549 )
Saqiba6f98d42020-07-23 18:51:26 +0530550
551 for barcode in barcodes:
552 if item.item_code not in itemwise_barcode:
553 itemwise_barcode.setdefault(item.item_code, [])
554 itemwise_barcode[item.item_code].append(barcode.get("barcode"))
555
556 return itemwise_barcode
557
Ankush Menat494bd9e2022-03-28 18:52:46 +0530558
Zlash6580f5cb02018-08-29 11:39:08 +0530559@frappe.whitelist()
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530560def get_item_tax_info(company, tax_category, item_codes, item_rates=None, item_tax_templates=None):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500561 out = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530562
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530563 if item_tax_templates is None:
Deepesh Gargcae42b482021-06-25 13:34:00 +0530564 item_tax_templates = {}
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +0530565
Deepesh Garg8dd99c02021-06-25 13:38:06 +0530566 if item_rates is None:
567 item_rates = {}
Deepesh Gargcae42b482021-06-25 13:34:00 +0530568
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530569 if isinstance(item_codes, (str,)):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500570 item_codes = json.loads(item_codes)
571
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530572 if isinstance(item_rates, (str,)):
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530573 item_rates = json.loads(item_rates)
574
Deepesh Garg8cdd7ce2021-06-24 19:17:58 +0530575 if isinstance(item_tax_templates, (str,)):
Deepesh Garg94d46042021-06-23 20:56:27 +0530576 item_tax_templates = json.loads(item_tax_templates)
577
Saif Ur Rehman67786682018-12-27 02:11:07 +0500578 for item_code in item_codes:
Deepesh Garg94d46042021-06-23 20:56:27 +0530579 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 +0500580 continue
Deepesh Garg94d46042021-06-23 20:56:27 +0530581
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530582 out[item_code[1]] = {}
583 item = frappe.get_cached_doc("Item", item_code[0])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530584 args = {
585 "company": company,
586 "tax_category": tax_category,
587 "net_rate": item_rates.get(item_code[1]),
588 }
Deepesh Garg269962a2021-06-23 22:52:51 +0530589
590 if item_tax_templates:
591 args.update({"item_tax_template": item_tax_templates.get(item_code[1])})
Deepesh Garg94d46042021-06-23 20:56:27 +0530592
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530593 get_item_tax_template(args, item, out[item_code[1]])
Ankush Menat494bd9e2022-03-28 18:52:46 +0530594 out[item_code[1]]["item_tax_rate"] = get_item_tax_map(
595 company, out[item_code[1]].get("item_tax_template"), as_json=True
596 )
Saif Ur Rehman67786682018-12-27 02:11:07 +0500597
598 return out
599
Ankush Menat494bd9e2022-03-28 18:52:46 +0530600
Saif Ur Rehman67786682018-12-27 02:11:07 +0500601def get_item_tax_template(args, item, out):
602 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530603 args = {
604 "tax_category": None
605 "item_tax_template": None
606 }
Saif Ur Rehman67786682018-12-27 02:11:07 +0500607 """
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530608 item_tax_template = None
609 if item.taxes:
610 item_tax_template = _get_item_tax_template(args, item.taxes, out)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500611
612 if not item_tax_template:
613 item_group = item.item_group
614 while item_group and not item_tax_template:
615 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
616 item_tax_template = _get_item_tax_template(args, item_group_doc.taxes, out)
617 item_group = item_group_doc.parent_item_group
618
Ankush Menat494bd9e2022-03-28 18:52:46 +0530619
18alantom308905b2021-05-03 23:34:34 +0530620def _get_item_tax_template(args, taxes, out=None, for_validate=False):
621 if out is None:
622 out = {}
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530623 taxes_with_validity = []
624 taxes_with_no_validity = []
625
626 for tax in taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530627 tax_company = frappe.get_cached_value("Item Tax Template", tax.item_tax_template, "company")
628 if tax_company == args["company"]:
629 if tax.valid_from or tax.maximum_net_rate:
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530630 # In purchase Invoice first preference will be given to supplier invoice date
631 # if supplier date is not present then posting date
Sagar Vora1a3997a2022-06-16 17:03:47 +0000632 validation_date = args.get("bill_date") or args.get("transaction_date")
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530633
Ankush Menat494bd9e2022-03-28 18:52:46 +0530634 if getdate(tax.valid_from) <= getdate(validation_date) and is_within_valid_range(args, tax):
Saqib Ansarieb3aae82021-10-12 13:29:32 +0530635 taxes_with_validity.append(tax)
636 else:
mohammadahmad1990e39649b2020-06-18 11:42:53 +0500637 taxes_with_no_validity.append(tax)
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530638
639 if taxes_with_validity:
Deepesh Garg6f6928f2023-04-09 09:38:13 +0530640 taxes = sorted(
641 taxes_with_validity, key=lambda i: i.valid_from or tax.maximum_net_rate, reverse=True
642 )
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530643 else:
644 taxes = taxes_with_no_validity
645
646 if for_validate:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530647 return [
648 tax.item_tax_template
649 for tax in taxes
650 if (
651 cstr(tax.tax_category) == cstr(args.get("tax_category"))
652 and (tax.item_tax_template not in taxes)
653 )
654 ]
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530655
656 # all templates have validity and no template is valid
657 if not taxes_with_validity and (not taxes_with_no_validity):
658 return None
659
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530660 # do not change if already a valid template
Ankush Menat494bd9e2022-03-28 18:52:46 +0530661 if args.get("item_tax_template") in {t.item_tax_template for t in taxes}:
662 out["item_tax_template"] = args.get("item_tax_template")
663 return args.get("item_tax_template")
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530664
Saif Ur Rehman67786682018-12-27 02:11:07 +0500665 for tax in taxes:
666 if cstr(tax.tax_category) == cstr(args.get("tax_category")):
667 out["item_tax_template"] = tax.item_tax_template
668 return tax.item_tax_template
669 return None
670
Ankush Menat494bd9e2022-03-28 18:52:46 +0530671
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530672def is_within_valid_range(args, tax):
673 if not flt(tax.maximum_net_rate):
674 # No range specified, just ignore
675 return True
Ankush Menat494bd9e2022-03-28 18:52:46 +0530676 elif flt(tax.minimum_net_rate) <= flt(args.get("net_rate")) <= flt(tax.maximum_net_rate):
Deepesh Garg8a7e2832021-06-04 22:53:26 +0530677 return True
678
679 return False
680
Ankush Menat494bd9e2022-03-28 18:52:46 +0530681
Saif Ur Rehman67786682018-12-27 02:11:07 +0500682@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500683def get_item_tax_map(company, item_tax_template, as_json=True):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500684 item_tax_map = {}
685 if item_tax_template:
686 template = frappe.get_cached_doc("Item Tax Template", item_tax_template)
687 for d in template.taxes:
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500688 if frappe.get_cached_value("Account", d.tax_type, "company") == company:
689 item_tax_map[d.tax_type] = d.tax_rate
Saif Ur Rehman67786682018-12-27 02:11:07 +0500690
691 return json.dumps(item_tax_map) if as_json else item_tax_map
692
Ankush Menat494bd9e2022-03-28 18:52:46 +0530693
Saif Ur Rehman67786682018-12-27 02:11:07 +0500694@frappe.whitelist()
Zlash6580f5cb02018-08-29 11:39:08 +0530695def calculate_service_end_date(args, item=None):
696 args = process_args(args)
697 if not item:
698 item = frappe.get_cached_doc("Item", args.item_code)
699
Zlash65627be1d2019-01-15 14:16:32 +0530700 doctype = args.get("parenttype") or args.get("doctype")
Zlash65a3dd7982019-01-15 14:36:11 +0530701 if doctype == "Sales Invoice":
702 enable_deferred = "enable_deferred_revenue"
703 no_of_months = "no_of_months"
704 account = "deferred_revenue_account"
705 else:
706 enable_deferred = "enable_deferred_expense"
707 no_of_months = "no_of_months_exp"
708 account = "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530709
Zlash6580f5cb02018-08-29 11:39:08 +0530710 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
Zarrare83ff382018-09-21 15:45:40 +0530711 service_end_date = add_months(service_start_date, item.get(no_of_months))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530712 deferred_detail = {"service_start_date": service_start_date, "service_end_date": service_end_date}
Zarrare83ff382018-09-21 15:45:40 +0530713 deferred_detail[enable_deferred] = item.get(enable_deferred)
714 deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)
Zlash6580f5cb02018-08-29 11:39:08 +0530715
716 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100717
Ankush Menat494bd9e2022-03-28 18:52:46 +0530718
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500719def get_default_income_account(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530720 return (
721 item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530722 or item_group.get("income_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500723 or brand.get("income_account")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530724 or args.income_account
725 )
726
Rushabh Mehta1a763742014-10-03 16:36:43 +0530727
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500728def get_default_expense_account(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530729 return (
730 item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530731 or item_group.get("expense_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500732 or brand.get("expense_account")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530733 or args.expense_account
734 )
735
Rushabh Mehta1a763742014-10-03 16:36:43 +0530736
Deepesh Garg3ce64172022-04-11 14:35:22 +0530737def get_provisional_account(args, item):
738 return item.get("default_provisional_account") or args.default_provisional_account
739
740
GangaManoj0b7d8fb2021-07-13 01:37:30 +0530741def get_default_discount_account(args, item):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530742 return item.get("default_discount_account") or args.discount_account
743
GangaManoj657e9b52021-07-06 16:51:12 +0530744
Zarrare83ff382018-09-21 15:45:40 +0530745def get_default_deferred_account(args, item, fieldname=None):
Zlash65627be1d2019-01-15 14:16:32 +0530746 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530747 return (
748 item.get(fieldname)
Zarrare83ff382018-09-21 15:45:40 +0530749 or args.get(fieldname)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530750 or frappe.get_cached_value("Company", args.company, "default_" + fieldname)
751 )
Manas Solanki03938482018-05-14 16:16:46 +0530752 else:
753 return None
754
Ankush Menat494bd9e2022-03-28 18:52:46 +0530755
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530756def get_default_cost_center(args, item=None, item_group=None, brand=None, company=None):
Nabin Hait50238c32018-08-08 18:43:04 +0530757 cost_center = None
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530758
759 if not company and args.get("company"):
760 company = args.get("company")
761
Ankush Menat494bd9e2022-03-28 18:52:46 +0530762 if args.get("project"):
Nabin Hait50238c32018-08-08 18:43:04 +0530763 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530764
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530765 if not cost_center and (item and item_group and brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530766 if args.get("customer"):
767 cost_center = (
768 item.get("selling_cost_center")
769 or item_group.get("selling_cost_center")
770 or brand.get("selling_cost_center")
771 )
Nabin Hait50238c32018-08-08 18:43:04 +0530772 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530773 cost_center = (
774 item.get("buying_cost_center")
775 or item_group.get("buying_cost_center")
776 or brand.get("buying_cost_center")
777 )
Rushabh Mehta49f97472018-08-30 18:50:48 +0530778
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530779 elif not cost_center and args.get("item_code") and company:
780 for method in ["get_item_defaults", "get_item_group_defaults", "get_brand_defaults"]:
781 path = "erpnext.stock.get_item_details.{0}".format(method)
782 data = frappe.get_attr(path)(args.get("item_code"), company)
783
784 if data and (data.selling_cost_center or data.buying_cost_center):
785 return data.selling_cost_center or data.buying_cost_center
786
787 if not cost_center and args.get("cost_center"):
788 cost_center = args.get("cost_center")
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530789
Ankush Menat494bd9e2022-03-28 18:52:46 +0530790 if (
791 company
792 and cost_center
793 and frappe.get_cached_value("Cost Center", cost_center, "company") != company
794 ):
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530795 return None
796
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530797 if not cost_center and company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530798 cost_center = frappe.get_cached_value("Company", company, "cost_center")
rohitwaghchaure1c8c1d72020-11-15 09:40:44 +0530799
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530800 return cost_center
Rushabh Mehta1a763742014-10-03 16:36:43 +0530801
Ankush Menat494bd9e2022-03-28 18:52:46 +0530802
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500803def get_default_supplier(args, item, item_group, brand):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530804 return (
805 item.get("default_supplier")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500806 or item_group.get("default_supplier")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530807 or brand.get("default_supplier")
808 )
809
Shreya Shah3c9839f2018-07-17 18:01:44 +0530810
Ankush16d4de52021-08-09 10:41:24 +0530811def get_price_list_rate(args, item_doc, out=None):
812 if out is None:
813 out = frappe._dict()
814
Anand Doshi39a28912016-02-15 11:42:18 +0530815 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530816
Ankush Menat494bd9e2022-03-28 18:52:46 +0530817 if meta.get_field("currency") or args.get("currency"):
Maricae8bc9122021-04-19 11:05:21 +0530818 if not args.get("price_list_currency") or not args.get("plc_conversion_rate"):
819 # if currency and plc_conversion_rate exist then
820 # `get_price_list_currency_and_exchange_rate` has already been called
821 pl_details = get_price_list_currency_and_exchange_rate(args)
822 args.update(pl_details)
823
Nabin Hait06c8cf42019-05-16 19:17:02 +0530824 if meta.get_field("currency"):
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530825 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530826
Ankush16d4de52021-08-09 10:41:24 +0530827 price_list_rate = get_price_list_rate_for(args, item_doc.name)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530828
hiousi1516e292019-01-08 18:34:08 +0100829 # variant
Ankush16d4de52021-08-09 10:41:24 +0530830 if price_list_rate is None and item_doc.variant_of:
hiousi1516e292019-01-08 18:34:08 +0100831 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530832
833 # insert in database
Ankush16d4de52021-08-09 10:41:24 +0530834 if price_list_rate is None:
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530835 if args.price_list and args.rate:
836 insert_item_price(args)
Ankush16d4de52021-08-09 10:41:24 +0530837 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530838
Ankush Menat494bd9e2022-03-28 18:52:46 +0530839 out.price_list_rate = (
840 flt(price_list_rate) * flt(args.plc_conversion_rate) / flt(args.conversion_rate)
841 )
mbauskar287fe812017-04-10 19:15:57 +0530842
Rohit Waghchaured1d46712023-01-09 15:12:46 +0530843 if frappe.db.get_single_value("Buying Settings", "disable_last_purchase_rate"):
844 return out
845
Ankush Menat494bd9e2022-03-28 18:52:46 +0530846 if not out.price_list_rate and args.transaction_type == "buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530847 from erpnext.stock.doctype.item.item import get_last_purchase_details
Ankush Menat494bd9e2022-03-28 18:52:46 +0530848
849 out.update(get_last_purchase_details(item_doc.name, args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530850
Ankush16d4de52021-08-09 10:41:24 +0530851 return out
852
Ankush Menat494bd9e2022-03-28 18:52:46 +0530853
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530854def insert_item_price(args):
855 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530856 if frappe.db.get_value(
857 "Price List", args.price_list, "currency", cache=True
858 ) == args.currency and cint(
859 frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")
860 ):
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530861 if frappe.has_permission("Item Price", "write"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530862 price_list_rate = (
Rohit Waghchaure0f280742022-12-15 16:34:06 +0530863 (flt(args.rate) + flt(args.discount_amount)) / args.get("conversion_factor")
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530864 if args.get("conversion_factor")
Rohit Waghchaure0f280742022-12-15 16:34:06 +0530865 else (flt(args.rate) + flt(args.discount_amount))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530866 )
Rushabh Mehta985cb822016-12-30 15:06:54 +0530867
Ankush Menat494bd9e2022-03-28 18:52:46 +0530868 item_price = frappe.db.get_value(
869 "Item Price",
870 {"item_code": args.item_code, "price_list": args.price_list, "currency": args.currency},
871 ["name", "price_list_rate"],
872 as_dict=1,
873 )
Nabin Haitb479a872018-09-07 13:17:11 +0530874 if item_price and item_price.name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530875 if item_price.price_list_rate != price_list_rate and frappe.db.get_single_value(
876 "Stock Settings", "update_existing_price_list_rate"
877 ):
878 frappe.db.set_value("Item Price", item_price.name, "price_list_rate", price_list_rate)
879 frappe.msgprint(
880 _("Item Price updated for {0} in Price List {1}").format(args.item_code, args.price_list),
881 alert=True,
882 )
Rushabh Mehta985cb822016-12-30 15:06:54 +0530883 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530884 item_price = frappe.get_doc(
885 {
886 "doctype": "Item Price",
887 "price_list": args.price_list,
888 "item_code": args.item_code,
889 "currency": args.currency,
890 "price_list_rate": price_list_rate,
maharshivpatelb3ccc4b2022-05-31 19:48:30 +0530891 "uom": args.stock_uom,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530892 }
893 )
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530894 item_price.insert()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530895 frappe.msgprint(
896 _("Item Price added for {0} in Price List {1}").format(args.item_code, args.price_list),
897 alert=True,
898 )
899
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530900
Nabin Hait01ca3e52019-01-25 16:25:15 +0530901def get_item_price(args, item_code, ignore_party=False):
Nabin Haite45ec662018-08-01 17:44:34 +0530902 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530903 Get name, price_list_rate from Item Price based on conditions
904 Check if the desired qty is within the increment of the packing list.
905 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
906 optional fields transaction_date, customer, supplier
907 :param item_code: str, Item Doctype field item_code
Nabin Haite45ec662018-08-01 17:44:34 +0530908 """
909
s-aga-r6b144ba2023-02-18 12:18:41 +0530910 ip = frappe.qb.DocType("Item Price")
911 query = (
912 frappe.qb.from_(ip)
913 .select(ip.name, ip.price_list_rate, ip.uom)
914 .where(
915 (ip.item_code == item_code)
916 & (ip.price_list == args.get("price_list"))
917 & (IfNull(ip.uom, "").isin(["", args.get("uom")]))
918 & (IfNull(ip.batch_no, "").isin(["", args.get("batch_no")]))
919 )
920 .orderby(ip.valid_from, order=frappe.qb.desc)
921 .orderby(IfNull(ip.batch_no, ""), order=frappe.qb.desc)
922 .orderby(ip.uom, order=frappe.qb.desc)
923 )
Deepesh Gargbd9bdc52021-01-28 12:05:57 +0530924
Nabin Hait01ca3e52019-01-25 16:25:15 +0530925 if not ignore_party:
Nabin Hait01ca3e52019-01-25 16:25:15 +0530926 if args.get("customer"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530927 query = query.where(ip.customer == args.get("customer"))
Nabin Hait4e456632019-01-29 14:02:08 +0530928 elif args.get("supplier"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530929 query = query.where(ip.supplier == args.get("supplier"))
Nabin Hait4e456632019-01-29 14:02:08 +0530930 else:
s-aga-r6b144ba2023-02-18 12:18:41 +0530931 query = query.where((IfNull(ip.customer, "") == "") & (IfNull(ip.supplier, "") == ""))
Nabin Hait01ca3e52019-01-25 16:25:15 +0530932
Ankush Menat494bd9e2022-03-28 18:52:46 +0530933 if args.get("transaction_date"):
s-aga-r6b144ba2023-02-18 12:18:41 +0530934 query = query.where(
935 (IfNull(ip.valid_from, "2000-01-01") <= args["transaction_date"])
936 & (IfNull(ip.valid_upto, "2500-12-31") >= args["transaction_date"])
937 )
Deepesh Gargf15ff5f2020-07-11 13:58:53 +0530938
s-aga-r6b144ba2023-02-18 12:18:41 +0530939 return query.run()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530940
Nabin Haite45ec662018-08-01 17:44:34 +0530941
942def get_price_list_rate_for(args, item_code):
943 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530944 :param customer: link to Customer DocType
945 :param supplier: link to Supplier DocType
946 :param price_list: str (Standard Buying or Standard Selling)
947 :param item_code: str, Item Doctype field item_code
948 :param qty: Desired Qty
949 :param transaction_date: Date of the price
Nabin Haite45ec662018-08-01 17:44:34 +0530950 """
951 item_price_args = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530952 "item_code": item_code,
953 "price_list": args.get("price_list"),
954 "customer": args.get("customer"),
955 "supplier": args.get("supplier"),
956 "uom": args.get("uom"),
957 "transaction_date": args.get("transaction_date"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530958 "batch_no": args.get("batch_no"),
Nabin Haite45ec662018-08-01 17:44:34 +0530959 }
960
961 item_price_data = 0
962 price_list_rate = get_item_price(item_price_args, item_code)
963 if price_list_rate:
964 desired_qty = args.get("qty")
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530965 if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
Nabin Haite45ec662018-08-01 17:44:34 +0530966 item_price_data = price_list_rate
967 else:
Don-Leopardoccdf1932020-01-09 03:54:43 -0300968 for field in ["customer", "supplier"]:
Nabin Haite45ec662018-08-01 17:44:34 +0530969 del item_price_args[field]
970
Ankush Menat494bd9e2022-03-28 18:52:46 +0530971 general_price_list_rate = get_item_price(
972 item_price_args, item_code, ignore_party=args.get("ignore_party")
973 )
Don-Leopardoccdf1932020-01-09 03:54:43 -0300974
Nabin Haite45ec662018-08-01 17:44:34 +0530975 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530976 item_price_args["uom"] = args.get("stock_uom")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530977 general_price_list_rate = get_item_price(
978 item_price_args, item_code, ignore_party=args.get("ignore_party")
979 )
Nabin Haite45ec662018-08-01 17:44:34 +0530980
981 if general_price_list_rate:
982 item_price_data = general_price_list_rate
983
984 if item_price_data:
985 if item_price_data[0][2] == args.get("uom"):
986 return item_price_data[0][1]
Ankush Menat494bd9e2022-03-28 18:52:46 +0530987 elif not args.get("price_list_uom_dependant"):
Nabin Haite45ec662018-08-01 17:44:34 +0530988 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
989 else:
990 return item_price_data[0][1]
991
Ankush Menat494bd9e2022-03-28 18:52:46 +0530992
Nabin Haite45ec662018-08-01 17:44:34 +0530993def check_packing_list(price_list_rate_name, desired_qty, item_code):
994 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530995 Check if the desired qty is within the increment of the packing list.
996 :param price_list_rate_name: Name of Item Price
997 :param desired_qty: Desired Qt
998 :param item_code: str, Item Doctype field item_code
999 :param qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +05301000 """
1001
Rohit Waghchaurecd34c702019-02-27 18:01:25 +05301002 flag = True
Nabin Haite45ec662018-08-01 17:44:34 +05301003 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Rohit Waghchaureb48effe2019-02-27 19:31:32 +05301004 if item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +05301005 packing_increment = desired_qty % item_price.packing_unit
1006
Rohit Waghchaurecd34c702019-02-27 18:01:25 +05301007 if packing_increment != 0:
1008 flag = False
1009
1010 return flag
Rushabh Mehta1a763742014-10-03 16:36:43 +05301011
Ankush Menat494bd9e2022-03-28 18:52:46 +05301012
Nabin Hait436f5262014-02-10 14:47:54 +05301013def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +05301014 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +05301015
Ankush Menat494bd9e2022-03-28 18:52:46 +05301016 company_currency = frappe.get_cached_value("Company", args.company, "default_currency")
1017 if not args.conversion_rate and args.currency == company_currency:
Anand Doshife13bfe2015-08-25 12:49:40 +05301018 args.conversion_rate = 1.0
1019
Ankush Menat494bd9e2022-03-28 18:52:46 +05301020 if (
1021 not args.ignore_conversion_rate
1022 and args.conversion_rate == 1
1023 and args.currency != company_currency
1024 ):
1025 args.conversion_rate = (
1026 get_exchange_rate(args.currency, company_currency, args.transaction_date, "for_buying") or 1.0
1027 )
Rohit Waghchaure4acbeec2021-07-13 11:45:41 +05301028
Nabin Hait436f5262014-02-10 14:47:54 +05301029 # validate currency conversion rate
Ankush Menat494bd9e2022-03-28 18:52:46 +05301030 validate_conversion_rate(
1031 args.currency, args.conversion_rate, meta.get_label("conversion_rate"), args.company
1032 )
Anand Doshibd67e872014-04-11 16:51:27 +05301033
Ankush Menat494bd9e2022-03-28 18:52:46 +05301034 args.conversion_rate = flt(
1035 args.conversion_rate,
1036 get_field_precision(meta.get_field("conversion_rate"), frappe._dict({"fields": args})),
1037 )
Anand Doshibd67e872014-04-11 16:51:27 +05301038
Nabin Hait06c8cf42019-05-16 19:17:02 +05301039 if args.price_list:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301040 if not args.plc_conversion_rate and args.price_list_currency == frappe.db.get_value(
1041 "Price List", args.price_list, "currency", cache=True
1042 ):
Nabin Hait06c8cf42019-05-16 19:17:02 +05301043 args.plc_conversion_rate = 1.0
Manas Solanki3504a232018-06-06 12:46:06 +05301044
Nabin Hait06c8cf42019-05-16 19:17:02 +05301045 # validate price list currency conversion rate
1046 if not args.get("price_list_currency"):
1047 throw(_("Price List Currency not selected"))
1048 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301049 validate_conversion_rate(
1050 args.price_list_currency,
1051 args.plc_conversion_rate,
1052 meta.get_label("plc_conversion_rate"),
1053 args.company,
1054 )
Anand Doshibd67e872014-04-11 16:51:27 +05301055
Nabin Hait06c8cf42019-05-16 19:17:02 +05301056 if meta.get_field("plc_conversion_rate"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301057 args.plc_conversion_rate = flt(
1058 args.plc_conversion_rate,
1059 get_field_precision(meta.get_field("plc_conversion_rate"), frappe._dict({"fields": args})),
1060 )
1061
Anand Doshibd67e872014-04-11 16:51:27 +05301062
Rushabh Mehtaf14b8092014-04-03 14:30:42 +05301063def get_party_item_code(args, item_doc, out):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301064 if args.transaction_type == "selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +05301065 out.customer_item_code = None
Nabin Hait34c551d2019-07-03 10:34:31 +05301066
Ankush Menat494bd9e2022-03-28 18:52:46 +05301067 if args.quotation_to and args.quotation_to != "Customer":
Nabin Hait34c551d2019-07-03 10:34:31 +05301068 return
1069
Nabin Hait79f091e2014-12-26 11:41:15 +05301070 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +05301071
1072 if customer_item_code:
1073 out.customer_item_code = customer_item_code[0].ref_code
1074 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +05301075 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +05301076 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
1077 if customer_group_item_code and not customer_group_item_code[0].customer_name:
1078 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +05301079
Ankush Menat494bd9e2022-03-28 18:52:46 +05301080 if args.transaction_type == "buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +05301081 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +05301082 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +05301083
Ankush Menat494bd9e2022-03-28 18:52:46 +05301084
rohitwaghchaure2ea593b2018-04-12 13:37:08 +05301085def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301086 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +05301087
Rushabh Mehta708e47a2018-08-08 16:37:31 +05301088 if not frappe.flags.pos_profile and not pos_profile:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301089 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get("pos_profile"))
Anand Doshibd67e872014-04-11 16:51:27 +05301090
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301091 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +05301092 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +05301093 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301094 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +05301095
Nabin Hait436f5262014-02-10 14:47:54 +05301096 if res.get("warehouse"):
s-aga-rc716dcc2022-12-29 12:34:18 +05301097 res.actual_qty = get_bin_details(
1098 args.item_code, res.warehouse, include_child_warehouses=True
1099 ).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +05301100
Nabin Hait436f5262014-02-10 14:47:54 +05301101 return res
1102
Ankush Menat494bd9e2022-03-28 18:52:46 +05301103
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301104@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301105def get_pos_profile(company, pos_profile=None, user=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301106 if pos_profile:
1107 return frappe.get_cached_doc("POS Profile", pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301108
1109 if not user:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301110 user = frappe.session["user"]
rohitwaghchaurec037dc72017-11-28 16:11:15 +05301111
s-aga-r6b144ba2023-02-18 12:18:41 +05301112 pf = frappe.qb.DocType("POS Profile")
1113 pfu = frappe.qb.DocType("POS Profile User")
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301114
s-aga-r6b144ba2023-02-18 12:18:41 +05301115 query = (
1116 frappe.qb.from_(pf)
1117 .left_join(pfu)
1118 .on(pf.name == pfu.parent)
1119 .select(pf.star)
1120 .where((pfu.user == user) & (pfu.default == 1))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301121 )
Anand Doshibd67e872014-04-11 16:51:27 +05301122
s-aga-r6b144ba2023-02-18 12:18:41 +05301123 if company:
1124 query = query.where(pf.company == company)
1125
1126 pos_profile = query.run(as_dict=True)
1127
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301128 if not pos_profile and company:
s-aga-r6b144ba2023-02-18 12:18:41 +05301129 pos_profile = (
1130 frappe.qb.from_(pf)
1131 .left_join(pfu)
1132 .on(pf.name == pfu.parent)
1133 .select(pf.star)
1134 .where((pf.company == company) & (pf.disabled == 0))
1135 ).run(as_dict=True)
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +05301136
Rushabh Mehtaad9156a2015-08-18 15:29:42 +05301137 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +05301138
Ankush Menat494bd9e2022-03-28 18:52:46 +05301139
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301140def get_serial_nos_by_fifo(args, sales_order=None):
Rushabh Mehta85abdc42015-09-03 10:29:38 +05301141 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
s-aga-r6b144ba2023-02-18 12:18:41 +05301142 sn = frappe.qb.DocType("Serial No")
1143 query = (
1144 frappe.qb.from_(sn)
1145 .select(sn.name)
1146 .where((sn.item_code == args.item_code) & (sn.warehouse == args.warehouse))
1147 .orderby(CombineDatetime(sn.purchase_date, sn.purchase_time))
1148 .limit(abs(cint(args.stock_qty)))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301149 )
1150
s-aga-r6b144ba2023-02-18 12:18:41 +05301151 if sales_order:
1152 query = query.where(sn.sales_order == sales_order)
s-aga-r6b144ba2023-02-18 12:18:41 +05301153 if args.batch_no:
1154 query = query.where(sn.batch_no == args.batch_no)
1155
1156 serial_nos = query.run(as_list=True)
1157 serial_nos = [s[0] for s in serial_nos]
1158
1159 return "\n".join(serial_nos)
1160
Shreyaa20157a2018-04-13 12:03:42 +05301161
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301162@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +05301163def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +05301164 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +05301165 filters = {"parent": item_code, "uom": uom}
s-aga-r58c027d2023-02-28 15:14:34 +05301166
Rushabh Mehta724f9e52014-10-07 15:29:58 +05301167 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +05301168 filters["parent"] = ("in", (item_code, variant_of))
Ankush Menat494bd9e2022-03-28 18:52:46 +05301169 conversion_factor = frappe.db.get_value("UOM Conversion Detail", filters, "conversion_factor")
Sagar Vora508189e2018-09-11 17:22:25 +05301170 if not conversion_factor:
1171 stock_uom = frappe.db.get_value("Item", item_code, "stock_uom")
1172 conversion_factor = get_uom_conv_factor(uom, stock_uom)
s-aga-r6b144ba2023-02-18 12:18:41 +05301173
rohitwaghchaureffdadbf2019-01-08 16:21:25 +05301174 return {"conversion_factor": conversion_factor or 1.0}
Nabin Hait08222152014-02-28 11:30:47 +05301175
Ankush Menat494bd9e2022-03-28 18:52:46 +05301176
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301177@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +05301178def get_projected_qty(item_code, warehouse):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301179 return {
1180 "projected_qty": frappe.db.get_value(
1181 "Bin", {"item_code": item_code, "warehouse": warehouse}, "projected_qty"
1182 )
1183 }
1184
Nabin Hait08222152014-02-28 11:30:47 +05301185
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05301186@frappe.whitelist()
s-aga-rc716dcc2022-12-29 12:34:18 +05301187def get_bin_details(item_code, warehouse, company=None, include_child_warehouses=False):
ruthra kumarbe382052023-01-16 08:50:39 +05301188 bin_details = {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
s-aga-rc716dcc2022-12-29 12:34:18 +05301189
1190 if warehouse:
s-aga-rc3911a52022-12-29 16:38:08 +05301191 from frappe.query_builder.functions import Coalesce, Sum
s-aga-r58c027d2023-02-28 15:14:34 +05301192
s-aga-rc716dcc2022-12-29 12:34:18 +05301193 from erpnext.stock.doctype.warehouse.warehouse import get_child_warehouses
1194
1195 warehouses = get_child_warehouses(warehouse) if include_child_warehouses else [warehouse]
s-aga-rc3911a52022-12-29 16:38:08 +05301196
1197 bin = frappe.qb.DocType("Bin")
1198 bin_details = (
1199 frappe.qb.from_(bin)
1200 .select(
1201 Coalesce(Sum(bin.projected_qty), 0).as_("projected_qty"),
1202 Coalesce(Sum(bin.actual_qty), 0).as_("actual_qty"),
1203 Coalesce(Sum(bin.reserved_qty), 0).as_("reserved_qty"),
1204 )
1205 .where((bin.item_code == item_code) & (bin.warehouse.isin(warehouses)))
1206 ).run(as_dict=True)[0]
s-aga-rc716dcc2022-12-29 12:34:18 +05301207
Anupam4980dd62021-03-15 11:37:46 +05301208 if company:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301209 bin_details["company_total_stock"] = get_company_total_stock(item_code, company)
s-aga-rb425c2d2023-01-02 11:25:13 +05301210
Anupam4980dd62021-03-15 11:37:46 +05301211 return bin_details
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301212
Ankush Menat494bd9e2022-03-28 18:52:46 +05301213
Anupam4980dd62021-03-15 11:37:46 +05301214def get_company_total_stock(item_code, company):
s-aga-r6b144ba2023-02-18 12:18:41 +05301215 bin = frappe.qb.DocType("Bin")
1216 wh = frappe.qb.DocType("Warehouse")
1217
1218 return (
1219 frappe.qb.from_(bin)
1220 .inner_join(wh)
1221 .on(bin.warehouse == wh.name)
1222 .select(Sum(bin.actual_qty))
1223 .where((wh.company == company) & (bin.item_code == item_code))
1224 ).run()[0][0]
Ankush Menat494bd9e2022-03-28 18:52:46 +05301225
Anupam4980dd62021-03-15 11:37:46 +05301226
1227@frappe.whitelist()
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301228def get_serial_no_details(item_code, warehouse, stock_qty, serial_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301229 args = frappe._dict(
1230 {"item_code": item_code, "warehouse": warehouse, "stock_qty": stock_qty, "serial_no": serial_no}
1231 )
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301232 serial_no = get_serial_no(args)
s-aga-r6b144ba2023-02-18 12:18:41 +05301233
Ankush Menat494bd9e2022-03-28 18:52:46 +05301234 return {"serial_no": serial_no}
1235
Rushabh Mehta985cb822016-12-30 15:06:54 +05301236
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301237@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +05301238def get_bin_details_and_serial_nos(
1239 item_code, warehouse, has_batch_no=None, stock_qty=None, serial_no=None
1240):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301241 bin_details_and_serial_nos = {}
1242 bin_details_and_serial_nos.update(get_bin_details(item_code, warehouse))
Rushabh Mehta49f97472018-08-30 18:50:48 +05301243 if flt(stock_qty) > 0:
Shreyaa20157a2018-04-13 12:03:42 +05301244 if has_batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301245 args = frappe._dict({"item_code": item_code, "warehouse": warehouse, "stock_qty": stock_qty})
Shreyaa20157a2018-04-13 12:03:42 +05301246 serial_no = get_serial_no(args)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301247 bin_details_and_serial_nos.update({"serial_no": serial_no})
Shreyaa20157a2018-04-13 12:03:42 +05301248 return bin_details_and_serial_nos
1249
Ankush Menat494bd9e2022-03-28 18:52:46 +05301250 bin_details_and_serial_nos.update(
1251 get_serial_no_details(item_code, warehouse, stock_qty, serial_no)
1252 )
s-aga-r6b144ba2023-02-18 12:18:41 +05301253
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301254 return bin_details_and_serial_nos
Anand Doshidffec8f2014-07-01 17:45:15 +05301255
Ankush Menat494bd9e2022-03-28 18:52:46 +05301256
Anand Doshidffec8f2014-07-01 17:45:15 +05301257@frappe.whitelist()
Shreyaa20157a2018-04-13 12:03:42 +05301258def get_batch_qty_and_serial_no(batch_no, stock_qty, warehouse, item_code, has_serial_no):
1259 batch_qty_and_serial_no = {}
1260 batch_qty_and_serial_no.update(get_batch_qty(batch_no, warehouse, item_code))
1261
Ankush Menat494bd9e2022-03-28 18:52:46 +05301262 if (flt(batch_qty_and_serial_no.get("actual_batch_qty")) >= flt(stock_qty)) and has_serial_no:
1263 args = frappe._dict(
1264 {"item_code": item_code, "warehouse": warehouse, "stock_qty": stock_qty, "batch_no": batch_no}
1265 )
Shreyaa20157a2018-04-13 12:03:42 +05301266 serial_no = get_serial_no(args)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301267 batch_qty_and_serial_no.update({"serial_no": serial_no})
s-aga-r58c027d2023-02-28 15:14:34 +05301268
Shreyaa20157a2018-04-13 12:03:42 +05301269 return batch_qty_and_serial_no
1270
Ankush Menat494bd9e2022-03-28 18:52:46 +05301271
Shreyaa20157a2018-04-13 12:03:42 +05301272@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +05301273def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +07001274 from erpnext.stock.doctype.batch import batch
Ankush Menat494bd9e2022-03-28 18:52:46 +05301275
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +05301276 if batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301277 return {"actual_batch_qty": batch.get_batch_qty(batch_no, warehouse)}
1278
Rushabh Mehta1e8025b2015-07-24 15:16:25 +05301279
Anand Doshidffec8f2014-07-01 17:45:15 +05301280@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301281def apply_price_list(args, as_doc=False):
1282 """Apply pricelist on a document-like dict object and return as
1283 {'parent': dict, 'children': list}
1284
1285 :param args: See below
1286 :param as_doc: Updates value in the passed dict
1287
Ankush Menat494bd9e2022-03-28 18:52:46 +05301288 args = {
1289 "doctype": "",
1290 "name": "",
1291 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
1292 "conversion_rate": 1.0,
1293 "selling_price_list": None,
1294 "price_list_currency": None,
1295 "price_list_uom_dependant": None,
1296 "plc_conversion_rate": 1.0,
1297 "doctype": "",
1298 "name": "",
1299 "supplier": None,
1300 "transaction_date": None,
1301 "conversion_rate": 1.0,
1302 "buying_price_list": None,
1303 "ignore_pricing_rule": 0/1
1304 }
Anand Doshidffec8f2014-07-01 17:45:15 +05301305 """
1306 args = process_args(args)
1307
1308 parent = get_price_list_currency_and_exchange_rate(args)
Maricae8bc9122021-04-19 11:05:21 +05301309 args.update(parent)
1310
Anand Doshidffec8f2014-07-01 17:45:15 +05301311 children = []
1312
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301313 if "items" in args:
1314 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +05301315 args.update(parent)
1316
1317 for item in item_list:
1318 args_copy = frappe._dict(args.copy())
1319 args_copy.update(item)
1320 item_details = apply_price_list_on_item(args_copy)
1321 children.append(item_details)
1322
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301323 if as_doc:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301324 args.price_list_currency = (parent.price_list_currency,)
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301325 args.plc_conversion_rate = parent.plc_conversion_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +05301326 if args.get("items"):
1327 for i, item in enumerate(args.get("items")):
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301328 for fieldname in children[i]:
1329 # if the field exists in the original doc
1330 # update the value
1331 if fieldname in item and fieldname not in ("name", "doctype"):
1332 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301333 return args
1334 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301335 return {"parent": parent, "children": children}
1336
Anand Doshidffec8f2014-07-01 17:45:15 +05301337
1338def apply_price_list_on_item(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301339 item_doc = frappe.db.get_value("Item", args.item_code, ["name", "variant_of"], as_dict=1)
Ankush16d4de52021-08-09 10:41:24 +05301340 item_details = get_price_list_rate(args, item_doc)
Deepesh Gargb741ae12022-12-02 17:14:06 +05301341 item_details.update(get_pricing_rule_for_item(args))
Rushabh Mehtab46069d2016-01-15 16:59:26 +05301342
Anand Doshidffec8f2014-07-01 17:45:15 +05301343 return item_details
1344
Ankush Menat494bd9e2022-03-28 18:52:46 +05301345
Anand Doshidffec8f2014-07-01 17:45:15 +05301346def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +05301347 if not args.price_list:
1348 return {}
1349
Ankush Menat494bd9e2022-03-28 18:52:46 +05301350 if args.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
Shreya3f778522018-05-15 16:59:20 +05301351 args.update({"exchange_rate": "for_selling"})
Ankush Menat494bd9e2022-03-28 18:52:46 +05301352 elif args.doctype in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]:
Shreya3f778522018-05-15 16:59:20 +05301353 args.update({"exchange_rate": "for_buying"})
1354
rohitwaghchaurea85ddf22019-11-19 18:47:48 +05301355 price_list_details = get_price_list_details(args.price_list)
1356
1357 price_list_currency = price_list_details.get("currency")
1358 price_list_uom_dependant = price_list_details.get("price_list_uom_dependant")
1359
Anand Doshidffec8f2014-07-01 17:45:15 +05301360 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +01001361 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +05301362
Ankush Menat494bd9e2022-03-28 18:52:46 +05301363 if (not plc_conversion_rate) or (
1364 price_list_currency
1365 and args.price_list_currency
1366 and price_list_currency != args.price_list_currency
1367 ):
1368 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
1369 plc_conversion_rate = (
1370 get_exchange_rate(
1371 price_list_currency, company_currency, args.transaction_date, args.exchange_rate
1372 )
1373 or plc_conversion_rate
1374 )
Anand Doshidffec8f2014-07-01 17:45:15 +05301375
Ankush Menat494bd9e2022-03-28 18:52:46 +05301376 return frappe._dict(
1377 {
1378 "price_list_currency": price_list_currency,
1379 "price_list_uom_dependant": price_list_uom_dependant,
1380 "plc_conversion_rate": plc_conversion_rate or 1,
1381 }
1382 )
1383
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +05301384
1385@frappe.whitelist()
1386def get_default_bom(item_code=None):
marination9f2d3252022-06-14 17:20:44 +05301387 def _get_bom(item):
1388 bom = frappe.get_all(
1389 "BOM", dict(item=item, is_active=True, is_default=True, docstatus=1), limit=1
Ankush Menat494bd9e2022-03-28 18:52:46 +05301390 )
marination9f2d3252022-06-14 17:20:44 +05301391 return bom[0].name if bom else None
1392
1393 if not item_code:
1394 return
1395
1396 bom_name = _get_bom(item_code)
1397
1398 template_item = frappe.db.get_value("Item", item_code, "variant_of")
1399 if not bom_name and template_item:
1400 bom_name = _get_bom(template_item)
1401
1402 return bom_name
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301403
Ankush Menat494bd9e2022-03-28 18:52:46 +05301404
Deepesh Garg15ff6a52020-02-18 12:28:41 +05301405@frappe.whitelist()
Manas Solanki087a2252018-05-04 16:02:38 +05301406def get_valuation_rate(item_code, company, warehouse=None):
Manas Solankib16a4ec2018-05-04 16:49:33 +05301407 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +05301408 item_group = get_item_group_defaults(item_code, company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001409 brand = get_brand_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +05301410 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +05301411 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +05301412 if not warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301413 warehouse = (
1414 item.get("default_warehouse")
1415 or item_group.get("default_warehouse")
1416 or brand.get("default_warehouse")
1417 )
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301418
Ankush Menat494bd9e2022-03-28 18:52:46 +05301419 return frappe.db.get_value(
1420 "Bin", {"item_code": item_code, "warehouse": warehouse}, ["valuation_rate"], as_dict=True
1421 ) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301422
Manas Solankie3910fb2018-05-16 15:50:17 +05301423 elif not item.get("is_stock_item"):
s-aga-r6b144ba2023-02-18 12:18:41 +05301424 pi_item = frappe.qb.DocType("Purchase Invoice Item")
1425 valuation_rate = (
1426 frappe.qb.from_(pi_item)
1427 .select((Sum(pi_item.base_net_amount) / Sum(pi_item.qty * pi_item.conversion_factor)))
s-aga-r58c027d2023-02-28 15:14:34 +05301428 .where((pi_item.docstatus == 1) & (pi_item.item_code == item_code))
s-aga-r6b144ba2023-02-18 12:18:41 +05301429 ).run()
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301430
Saurabhbd01a812016-03-07 14:32:23 +05301431 if valuation_rate:
1432 return {"valuation_rate": valuation_rate[0][0] or 0.0}
1433 else:
1434 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301435
Ankush Menat494bd9e2022-03-28 18:52:46 +05301436
Saurabh2d7af632016-02-26 11:09:20 +05301437def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +05301438 if out.valuation_rate:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301439 out.update({"gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)})
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301440
Saurabhd3135532016-02-25 18:59:20 +05301441 return out
mbauskar6f603392016-01-21 16:10:22 +05301442
Ankush Menat494bd9e2022-03-28 18:52:46 +05301443
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301444@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301445def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +05301446 serial_no = None
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301447 if isinstance(args, str):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301448 args = json.loads(args)
1449 args = frappe._dict(args)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301450 if args.get("doctype") == "Sales Invoice" and not args.get("update_stock"):
Rohit Waghchauredc981dc2017-04-03 14:17:08 +05301451 return ""
Ankush Menat494bd9e2022-03-28 18:52:46 +05301452 if args.get("warehouse") and args.get("stock_qty") and args.get("item_code"):
1453 has_serial_no = frappe.get_value("Item", {"item_code": args.item_code}, "has_serial_no")
1454 if args.get("batch_no") and has_serial_no == 1:
s-aga-r35489fb2023-02-18 14:33:31 +05301455 return get_serial_nos_by_fifo(args, sales_order)
Shreyaa20157a2018-04-13 12:03:42 +05301456 elif has_serial_no == 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301457 args = json.dumps(
1458 {
1459 "item_code": args.get("item_code"),
1460 "warehouse": args.get("warehouse"),
1461 "stock_qty": args.get("stock_qty"),
1462 }
1463 )
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301464 args = process_args(args)
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301465 serial_no = get_serial_nos_by_fifo(args, sales_order)
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +05301466
1467 if not serial_no and serial_nos:
1468 # For POS
1469 serial_no = serial_nos
1470
1471 return serial_no
Manas Solankie5e87f72018-05-28 20:07:08 +05301472
1473
1474def update_party_blanket_order(args, out):
ronelvcabrera370cdc02019-12-04 18:37:11 +08001475 if out["against_blanket_order"]:
1476 blanket_order_details = get_blanket_order_details(args)
1477 if blanket_order_details:
1478 out.update(blanket_order_details)
Manas Solankie5e87f72018-05-28 20:07:08 +05301479
Ankush Menat494bd9e2022-03-28 18:52:46 +05301480
Manas Solankie5e87f72018-05-28 20:07:08 +05301481@frappe.whitelist()
1482def get_blanket_order_details(args):
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301483 if isinstance(args, str):
Manas Solankie5e87f72018-05-28 20:07:08 +05301484 args = frappe._dict(json.loads(args))
1485
1486 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +05301487
s-aga-r6b144ba2023-02-18 12:18:41 +05301488 if args.item_code:
1489 bo = frappe.qb.DocType("Blanket Order")
1490 bo_item = frappe.qb.DocType("Blanket Order Item")
1491
1492 query = (
1493 frappe.qb.from_(bo)
1494 .from_(bo_item)
1495 .select(bo_item.rate.as_("blanket_order_rate"), bo.name.as_("blanket_order"))
1496 .where(
1497 (bo.company == args.company)
1498 & (bo_item.item_code == args.item_code)
1499 & (bo.docstatus == 1)
1500 & (bo.name == bo_item.parent)
1501 )
Ankush Menat494bd9e2022-03-28 18:52:46 +05301502 )
Nabin Hait2737b082018-06-14 18:07:22 +05301503
s-aga-r6b144ba2023-02-18 12:18:41 +05301504 if args.customer and args.doctype == "Sales Order":
1505 query = query.where(bo.customer == args.customer)
1506 elif args.supplier and args.doctype == "Purchase Order":
1507 query = query.where(bo.supplier == args.supplier)
1508 if args.blanket_order:
1509 query = query.where(bo.name == args.blanket_order)
1510 if args.transaction_date:
1511 query = query.where(bo.to_date >= args.transaction_date)
1512
1513 blanket_order_details = query.run(as_dict=True)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301514 blanket_order_details = blanket_order_details[0] if blanket_order_details else ""
s-aga-r6b144ba2023-02-18 12:18:41 +05301515
Manas Solankie5e87f72018-05-28 20:07:08 +05301516 return blanket_order_details
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301517
Ankush Menat494bd9e2022-03-28 18:52:46 +05301518
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301519def get_so_reservation_for_item(args):
1520 reserved_so = None
Ankush Menat494bd9e2022-03-28 18:52:46 +05301521 if args.get("against_sales_order"):
1522 if get_reserved_qty_for_so(args.get("against_sales_order"), args.get("item_code")):
1523 reserved_so = args.get("against_sales_order")
1524 elif args.get("against_sales_invoice"):
s-aga-r6b144ba2023-02-18 12:18:41 +05301525 sales_order = frappe.db.get_all(
1526 "Sales Invoice Item",
1527 filters={"parent": args.get("against_sales_invoice"), "item_code": args.get("item_code")},
1528 fields="sales_order",
Ankush Menat494bd9e2022-03-28 18:52:46 +05301529 )
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301530 if sales_order and sales_order[0]:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301531 if get_reserved_qty_for_so(sales_order[0][0], args.get("item_code")):
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301532 reserved_so = sales_order[0]
1533 elif args.get("sales_order"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301534 if get_reserved_qty_for_so(args.get("sales_order"), args.get("item_code")):
1535 reserved_so = args.get("sales_order")
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301536 return reserved_so
1537
Ankush Menat494bd9e2022-03-28 18:52:46 +05301538
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301539def get_reserved_qty_for_so(sales_order, item_code):
s-aga-r6b144ba2023-02-18 12:18:41 +05301540 reserved_qty = frappe.db.get_value(
1541 "Sales Order Item",
1542 filters={
1543 "parent": sales_order,
1544 "item_code": item_code,
1545 "ensure_delivery_based_on_produced_serial_no": 1,
1546 },
1547 fieldname="sum(qty)",
Ankush Menat494bd9e2022-03-28 18:52:46 +05301548 )
s-aga-r6b144ba2023-02-18 12:18:41 +05301549
1550 return reserved_qty or 0