blob: 0ed3b276e39e44ed795a849b82d7b86829505f93 [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
4from __future__ import unicode_literals
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
6from frappe import _, throw
Deepesh Gargef0d26c2020-01-06 15:34:15 +05307from frappe.utils import flt, cint, add_days, cstr, add_months, getdate
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +05308import json, copy
Nabin Hait34d28222016-01-19 15:45:49 +05309from erpnext.accounts.doctype.pricing_rule.pricing_rule import get_pricing_rule_for_item, set_transaction_type
Anand Doshidffec8f2014-07-01 17:45:15 +053010from erpnext.setup.utils import get_exchange_rate
Rushabh Mehta66e08e32014-09-29 12:17:03 +053011from frappe.model.meta import get_field_precision
Rushabh Mehta551406a2017-04-21 12:40:19 +053012from erpnext.stock.doctype.batch.batch import get_batch_no
tundebabzy6e90f492018-02-12 10:48:57 +010013from erpnext import get_company_currency
Sagar Vora508189e2018-09-11 17:22:25 +053014from erpnext.stock.doctype.item.item import get_item_defaults, get_uom_conv_factor
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053015from erpnext.stock.doctype.price_list.price_list import get_price_list_details
Shreya Shah3c9839f2018-07-17 18:01:44 +053016from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +050017from erpnext.setup.doctype.brand.brand import get_brand_defaults
Rohit Waghchaure3cf24362019-06-02 16:03:05 +053018from erpnext.stock.doctype.item_manufacturer.item_manufacturer import get_item_manufacturer_part_no
Nabin Hait98c2a052014-05-05 18:41:41 +053019
Achilles Rasquinha714c7462018-02-15 11:28:55 +053020from six import string_types, iteritems
tundebabzyacccdb32017-11-23 08:35:15 +010021
Nabin Hait0d1ccc32019-02-14 18:30:10 +053022sales_doctypes = ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']
23purchase_doctypes = ['Material Request', 'Supplier Quotation', 'Purchase Order', 'Purchase Receipt', 'Purchase Invoice']
24
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053025@frappe.whitelist()
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053026def get_item_details(args, doc=None, for_validate=False, overwrite_warehouse=True):
Nabin Hait436f5262014-02-10 14:47:54 +053027 """
28 args = {
29 "item_code": "",
30 "warehouse": None,
31 "customer": "",
32 "conversion_rate": 1.0,
33 "selling_price_list": None,
34 "price_list_currency": None,
Nabin Hait615d3422014-02-25 19:01:20 +053035 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +053036 "doctype": "",
37 "name": "",
Nabin Hait436f5262014-02-10 14:47:54 +053038 "supplier": None,
39 "transaction_date": None,
40 "conversion_rate": 1.0,
41 "buying_price_list": None,
42 "is_subcontracted": "Yes" / "No",
Nabin Hait444f9562014-06-20 15:59:49 +053043 "ignore_pricing_rule": 0/1
Neil Trini Lasrado6e343e22016-03-09 17:02:59 +053044 "project": ""
Saif Ur Rehman2689dea2019-01-09 13:43:06 +050045 "set_warehouse": ""
Nabin Hait436f5262014-02-10 14:47:54 +053046 }
47 """
Suraj Shetty182f4de2019-08-16 08:16:22 +053048
Anand Doshidffec8f2014-07-01 17:45:15 +053049 args = process_args(args)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053050 item = frappe.get_cached_doc("Item", args.item_code)
Nabin Hait436f5262014-02-10 14:47:54 +053051 validate_item_details(args, item)
Anand Doshibd67e872014-04-11 16:51:27 +053052
Suraj Shetty182f4de2019-08-16 08:16:22 +053053 out = get_basic_details(args, item, overwrite_warehouse)
54
Deepesh Gargef0d26c2020-01-06 15:34:15 +053055 if isinstance(doc, string_types):
56 doc = json.loads(doc)
57
58 if doc and doc.get('doctype') == 'Purchase Invoice':
59 args['bill_date'] = doc.get('bill_date')
60
61 if doc:
62 args['posting_date'] = doc.get('posting_date')
63 args['transaction_date'] = doc.get('transaction_date')
64
Saif Ur Rehman67786682018-12-27 02:11:07 +050065 get_item_tax_template(args, item, out)
Saif Ur Rehman648bd152019-01-03 03:48:01 +050066 out["item_tax_rate"] = get_item_tax_map(args.company, args.get("item_tax_template") if out.get("item_tax_template") is None \
67 else out.get("item_tax_template"), as_json=True)
Saif Ur Rehman67786682018-12-27 02:11:07 +050068
Rushabh Mehta708e47a2018-08-08 16:37:31 +053069 get_party_item_code(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053070
Rushabh Mehta708e47a2018-08-08 16:37:31 +053071 set_valuation_rate(out, args)
Anand Doshibd67e872014-04-11 16:51:27 +053072
Manas Solankie5e87f72018-05-28 20:07:08 +053073 update_party_blanket_order(args, out)
74
Rushabh Mehta708e47a2018-08-08 16:37:31 +053075 get_price_list_rate(args, item, out)
Nabin Hait436f5262014-02-10 14:47:54 +053076
Rushabh Mehtab46069d2016-01-15 16:59:26 +053077 if args.customer and cint(args.is_pos):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +053078 out.update(get_pos_profile_item_details(args.company, args))
Rushabh Mehta6b537922017-03-14 16:59:11 +053079
Nabin Haitda17f9c2020-05-01 18:16:25 +053080 if (args.get("doctype") == "Material Request" and
81 args.get("material_request_type") == "Material Transfer"):
82 out.update(get_bin_details(args.item_code, args.get("from_warehouse")))
83
84 elif out.get("warehouse"):
Nabin Hait0287d312017-01-11 10:31:33 +053085 out.update(get_bin_details(args.item_code, out.warehouse))
Anand Doshibd67e872014-04-11 16:51:27 +053086
Nabin Haita3dd72a2014-05-28 12:49:20 +053087 # update args with out, if key or value not exists
Achilles Rasquinha714c7462018-02-15 11:28:55 +053088 for key, value in iteritems(out):
Nabin Haita3dd72a2014-05-28 12:49:20 +053089 if args.get(key) is None:
90 args[key] = value
91
rohitwaghchaurea85ddf22019-11-19 18:47:48 +053092 data = get_pricing_rule_for_item(args, out.price_list_rate,
93 doc, for_validate=for_validate)
94
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +053095 out.update(data)
Rushabh Mehta708e47a2018-08-08 16:37:31 +053096
97 update_stock(args, out)
98
99 if args.transaction_date and item.lead_time_days:
100 out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
101 item.lead_time_days)
102
103 if args.get("is_subcontracted") == "Yes":
104 out.bom = args.get('bom') or get_default_bom(args.item_code)
105
106 get_gross_profit(out)
107 if args.doctype == 'Material Request':
108 out.rate = args.rate or out.price_list_rate
109 out.amount = flt(args.qty * out.rate)
110
111 return out
112
113def update_stock(args, out):
pratu16x7577e4c42017-06-23 11:39:03 +0530114 if (args.get("doctype") == "Delivery Note" or
Nabin Hait3ce41d62017-05-03 18:22:24 +0530115 (args.get("doctype") == "Sales Invoice" and args.get('update_stock'))) \
116 and out.warehouse and out.stock_qty > 0:
pratu16x7577e4c42017-06-23 11:39:03 +0530117
Nabin Hait8fac2ad2017-05-18 11:54:24 +0530118 if out.has_batch_no and not args.get("batch_no"):
Rushabh Mehta551406a2017-04-21 12:40:19 +0530119 out.batch_no = get_batch_no(out.item_code, out.warehouse, out.qty)
rohitwaghchaure2fb8cc52017-11-29 13:50:04 +0530120 actual_batch_qty = get_batch_qty(out.batch_no, out.warehouse, out.item_code)
121 if actual_batch_qty:
122 out.update(actual_batch_qty)
Shreya14bd43d2018-04-27 16:24:05 +0530123
124 if out.has_serial_no and args.get('batch_no'):
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530125 reserved_so = get_so_reservation_for_item(args)
Shreya14bd43d2018-04-27 16:24:05 +0530126 out.batch_no = args.get('batch_no')
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530127 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Shreya14bd43d2018-04-27 16:24:05 +0530128
129 elif out.has_serial_no:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530130 reserved_so = get_so_reservation_for_item(args)
131 out.serial_no = get_serial_no(out, args.serial_no, sales_order=reserved_so)
Rushabh Mehta551406a2017-04-21 12:40:19 +0530132
Anand Doshibd67e872014-04-11 16:51:27 +0530133
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530134def set_valuation_rate(out, args):
Nabin Hait50238c32018-08-08 18:43:04 +0530135 if frappe.db.exists("Product Bundle", args.item_code, cache=True):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530136 valuation_rate = 0.0
137 bundled_items = frappe.get_doc("Product Bundle", args.item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530138
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530139 for bundle_item in bundled_items.items:
140 valuation_rate += \
141 flt(get_valuation_rate(bundle_item.item_code, args.company, out.get("warehouse")).get("valuation_rate") \
142 * bundle_item.qty)
Anand Doshi70f57eb2015-11-27 14:37:40 +0530143
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530144 out.update({
145 "valuation_rate": valuation_rate
146 })
147
148 else:
149 out.update(get_valuation_rate(args.item_code, args.company, out.get("warehouse")))
150
Nabin Hait436f5262014-02-10 14:47:54 +0530151
Anand Doshidffec8f2014-07-01 17:45:15 +0530152def process_args(args):
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530153 if isinstance(args, string_types):
Anand Doshidffec8f2014-07-01 17:45:15 +0530154 args = json.loads(args)
155
156 args = frappe._dict(args)
157
Anand Doshidffec8f2014-07-01 17:45:15 +0530158 if not args.get("price_list"):
159 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
160
161 if args.barcode:
162 args.item_code = get_item_code(barcode=args.barcode)
163 elif not args.item_code and args.serial_no:
164 args.item_code = get_item_code(serial_no=args.serial_no)
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530165
mbauskar6f603392016-01-21 16:10:22 +0530166 set_transaction_type(args)
Anand Doshidffec8f2014-07-01 17:45:15 +0530167 return args
168
tundebabzyacccdb32017-11-23 08:35:15 +0100169
Neil Trini Lasrado4abda672015-02-25 17:34:27 +0530170@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530171def get_item_code(barcode=None, serial_no=None):
172 if barcode:
Giovanni2144e022017-12-10 17:27:09 +0100173 item_code = frappe.db.get_value("Item Barcode", {"barcode": barcode}, fieldname=["parent"])
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530174 if not item_code:
175 frappe.throw(_("No Item with Barcode {0}").format(barcode))
Nabin Hait436f5262014-02-10 14:47:54 +0530176 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +0530177 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530178 if not item_code:
179 frappe.throw(_("No Item with Serial No {0}").format(serial_no))
Anand Doshibd67e872014-04-11 16:51:27 +0530180
Nabin Hait436f5262014-02-10 14:47:54 +0530181 return item_code
Anand Doshibd67e872014-04-11 16:51:27 +0530182
tundebabzyacccdb32017-11-23 08:35:15 +0100183
Nabin Hait436f5262014-02-10 14:47:54 +0530184def validate_item_details(args, item):
185 if not args.company:
186 throw(_("Please specify Company"))
Anand Doshibd67e872014-04-11 16:51:27 +0530187
Nabin Hait436f5262014-02-10 14:47:54 +0530188 from erpnext.stock.doctype.item.item import validate_end_of_life
Anand Doshi21e09a22015-10-29 12:21:41 +0530189 validate_end_of_life(item.name, item.end_of_life, item.disabled)
Anand Doshibd67e872014-04-11 16:51:27 +0530190
tundebabzyacccdb32017-11-23 08:35:15 +0100191 if args.transaction_type == "selling" and cint(item.has_variants):
Umair Sayyed72534de2016-04-15 12:52:12 +0530192 throw(_("Item {0} is a template, please select one of its variants").format(item.name))
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530193
tundebabzyacccdb32017-11-23 08:35:15 +0100194 elif args.transaction_type == "buying" and args.doctype != "Material Request":
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530195 if args.get("is_subcontracted") == "Yes" and item.is_sub_contracted_item != 1:
Rushabh Mehtac38fc712014-04-16 17:21:25 +0530196 throw(_("Item {0} must be a Sub-contracted Item").format(item.name))
Anand Doshibd67e872014-04-11 16:51:27 +0530197
tundebabzyacccdb32017-11-23 08:35:15 +0100198
Suraj Shetty182f4de2019-08-16 08:16:22 +0530199def get_basic_details(args, item, overwrite_warehouse=True):
tundebabzyacccdb32017-11-23 08:35:15 +0100200 """
201 :param args: {
202 "item_code": "",
203 "warehouse": None,
204 "customer": "",
205 "conversion_rate": 1.0,
206 "selling_price_list": None,
207 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530208 "price_list_uom_dependant": None,
tundebabzyacccdb32017-11-23 08:35:15 +0100209 "plc_conversion_rate": 1.0,
210 "doctype": "",
211 "name": "",
212 "supplier": None,
213 "transaction_date": None,
214 "conversion_rate": 1.0,
215 "buying_price_list": None,
216 "is_subcontracted": "Yes" / "No",
217 "ignore_pricing_rule": 0/1
218 "project": "",
219 barcode: "",
220 serial_no: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100221 currency: "",
222 update_stock: "",
223 price_list: "",
224 company: "",
225 order_type: "",
226 is_pos: "",
tundebabzyacccdb32017-11-23 08:35:15 +0100227 project: "",
228 qty: "",
229 stock_qty: "",
ronelvcabrera370cdc02019-12-04 18:37:11 +0800230 conversion_factor: "",
231 against_blanket_order: 0/1
tundebabzyacccdb32017-11-23 08:35:15 +0100232 }
233 :param item: `item_code` of Item object
234 :return: frappe._dict
235 """
236
Rushabh Mehta1a763742014-10-03 16:36:43 +0530237 if not item:
238 item = frappe.get_doc("Item", args.get("item_code"))
Anand Doshibd67e872014-04-11 16:51:27 +0530239
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530240 if item.variant_of:
241 item.update_template_tables()
242
Manas Solankib16a4ec2018-05-04 16:49:33 +0530243 item_defaults = get_item_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530244 item_group_defaults = get_item_group_defaults(item.name, args.company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500245 brand_defaults = get_brand_defaults(item.name, args.company)
Shreya Shah3c9839f2018-07-17 18:01:44 +0530246
Saqib438e0432020-04-03 10:02:56 +0530247 defaults = frappe._dict({
248 'item_defaults': item_defaults,
249 'item_group_defaults': item_group_defaults,
250 'brand_defaults': brand_defaults
251 })
marinatione05013e2020-04-06 22:13:13 +0530252
Saqib438e0432020-04-03 10:02:56 +0530253 warehouse = get_item_warehouse(item, args, overwrite_warehouse, defaults)
Nabin Hait36028bf2014-02-12 19:09:28 +0530254
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530255 if args.get('doctype') == "Material Request" and not args.get('material_request_type'):
256 args['material_request_type'] = frappe.db.get_value('Material Request',
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530257 args.get('name'), 'material_request_type', cache=True)
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530258
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530259 expense_account = None
260
261 if args.get('doctype') == 'Purchase Invoice' and item.is_fixed_asset:
262 from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
263 expense_account = get_asset_category_account(fieldname = "fixed_asset_account", item = args.item_code, company= args.company)
264
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530265 #Set the UOM to the Default Sales UOM or Default Purchase UOM if configured in the Item Master
Saqib438e0432020-04-03 10:02:56 +0530266 if not args.get('uom'):
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530267 if args.get('doctype') in sales_doctypes:
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530268 args.uom = item.sales_uom if item.sales_uom else item.stock_uom
rohitwaghchauree8ccc0e2017-11-21 16:17:22 +0530269 elif (args.get('doctype') in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']) or \
Rohit Waghchaure6cdaa6e2018-05-18 16:30:14 +0530270 (args.get('doctype') == 'Material Request' and args.get('material_request_type') == 'Purchase'):
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530271 args.uom = item.purchase_uom if item.purchase_uom else item.stock_uom
272 else:
273 args.uom = item.stock_uom
274
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530275 out = frappe._dict({
Nabin Hait139dc7b2014-02-12 14:53:18 +0530276 "item_code": item.name,
277 "item_name": item.item_name,
Neil Trini Lasradoc48f06c2015-02-10 16:49:16 +0530278 "description": cstr(item.description).strip(),
279 "image": cstr(item.image).strip(),
Saurabhd3135532016-02-25 18:59:20 +0530280 "warehouse": warehouse,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500281 "income_account": get_default_income_account(args, item_defaults, item_group_defaults, brand_defaults),
Anurag Mishraf3b393f2019-11-28 18:52:16 +0530282 "expense_account": expense_account or get_default_expense_account(args, item_defaults, item_group_defaults, brand_defaults) ,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500283 "cost_center": get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults),
Rushabh Mehta551406a2017-04-21 12:40:19 +0530284 'has_serial_no': item.has_serial_no,
285 'has_batch_no': item.has_batch_no,
marinatione05013e2020-04-06 22:13:13 +0530286 "batch_no": args.get("batch_no"),
Nabin Hait79a1d2a2017-09-29 18:14:10 +0530287 "uom": args.uom,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530288 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
Fisher Yu2cd49f52019-01-11 18:01:33 +0800289 "qty": flt(args.qty) or 1.0,
290 "stock_qty": flt(args.qty) or 1.0,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530291 "price_list_rate": 0.0,
292 "base_price_list_rate": 0.0,
293 "rate": 0.0,
294 "base_rate": 0.0,
295 "amount": 0.0,
296 "base_amount": 0.0,
Nabin Hait82e3e252015-02-23 16:58:30 +0530297 "net_rate": 0.0,
298 "net_amount": 0.0,
Saurabhc6dbe702015-10-19 14:17:52 +0530299 "discount_percentage": 0.0,
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500300 "supplier": get_default_supplier(args, item_defaults, item_group_defaults, brand_defaults),
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530301 "update_stock": args.get("update_stock") if args.get('doctype') in ['Sales Invoice', 'Purchase Invoice'] else 0,
Rohit Waghchaurec858d522016-12-12 13:01:43 +0530302 "delivered_by_supplier": item.delivered_by_supplier if args.get("doctype") in ["Sales Order", "Sales Invoice"] else 0,
Vishal Dhayaguded42242d2017-11-29 16:09:59 +0530303 "is_fixed_asset": item.is_fixed_asset,
304 "weight_per_unit":item.weight_per_unit,
305 "weight_uom":item.weight_uom,
Nabin Haite45ec662018-08-01 17:44:34 +0530306 "last_purchase_rate": item.last_purchase_rate if args.get("doctype") in ["Purchase Order"] else 0,
ronelvcabrera370cdc02019-12-04 18:37:11 +0800307 "transaction_date": args.get("transaction_date"),
rohitwaghchaureaa85e512020-05-19 19:51:45 +0530308 "against_blanket_order": args.get("against_blanket_order"),
309 "bom_no": item.get("default_bom")
Nabin Hait139dc7b2014-02-12 14:53:18 +0530310 })
Anand Doshibd67e872014-04-11 16:51:27 +0530311
Zlash65627be1d2019-01-15 14:16:32 +0530312 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zlash6580f5cb02018-08-29 11:39:08 +0530313 out.update(calculate_service_end_date(args, item))
Manas Solanki03938482018-05-14 16:16:46 +0530314
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530315 # calculate conversion factor
mbauskar287fe812017-04-10 19:15:57 +0530316 if item.stock_uom == args.uom:
317 out.conversion_factor = 1.0
318 else:
319 out.conversion_factor = args.conversion_factor or \
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530320 get_conversion_factor(item.name, args.uom).get("conversion_factor")
mbauskar287fe812017-04-10 19:15:57 +0530321
322 args.conversion_factor = out.conversion_factor
323 out.stock_qty = out.qty * out.conversion_factor
Rohit Waghchauredc981dc2017-04-03 14:17:08 +0530324
Shreya Shah44fa9a62018-01-08 14:58:20 +0530325 # calculate last purchase rate
Nabin Hait0d1ccc32019-02-14 18:30:10 +0530326 if args.get('doctype') in purchase_doctypes:
327 from erpnext.buying.doctype.purchase_order.purchase_order import item_last_purchase_rate
328 out.last_purchase_rate = item_last_purchase_rate(args.name, args.conversion_rate, item.name, out.conversion_factor)
Shreya Shah44fa9a62018-01-08 14:58:20 +0530329
Nabin Haitb09ed412015-02-17 10:33:58 +0530330 # if default specified in item is for another company, fetch from company
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530331 for d in [
332 ["Account", "income_account", "default_income_account"],
Rushabh Mehta0394aec2016-04-22 17:22:22 +0530333 ["Account", "expense_account", "default_expense_account"],
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530334 ["Cost Center", "cost_center", "cost_center"],
335 ["Warehouse", "warehouse", ""]]:
Nabin Hait33df0b42018-05-26 09:09:02 +0530336 if not out[d[1]]:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530337 out[d[1]] = frappe.get_cached_value('Company', args.company, d[2]) if d[2] else None
Nabin Haitb09ed412015-02-17 10:33:58 +0530338
Giovanni2144e022017-12-10 17:27:09 +0100339 for fieldname in ("item_name", "item_group", "barcodes", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530340 out[fieldname] = item.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530341
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530342 if args.get("manufacturer"):
343 part_no = get_item_manufacturer_part_no(args.get("item_code"), args.get("manufacturer"))
344 if part_no:
345 out["manufacturer_part_no"] = part_no
346 else:
347 out["manufacturer_part_no"] = None
348 out["manufacturer"] = None
marination3e7a8ab2020-04-07 21:00:57 +0530349 else:
rohitwaghchaurebe16e5c2020-05-01 10:50:17 +0530350 data = frappe.get_value("Item", item.name,
351 ["default_item_manufacturer", "default_manufacturer_part_no"] , as_dict=1)
352
353 if data:
354 out.update({
355 "manufacturer": data.default_item_manufacturer,
356 "manufacturer_part_no": data.default_manufacturer_part_no
357 })
Rohit Waghchaure3cf24362019-06-02 16:03:05 +0530358
Nabin Hait34c551d2019-07-03 10:34:31 +0530359 child_doctype = args.doctype + ' Item'
360 meta = frappe.get_meta(child_doctype)
361 if meta.get_field("barcode"):
362 update_barcode_value(out)
363
Nabin Hait436f5262014-02-10 14:47:54 +0530364 return out
Anand Doshibd67e872014-04-11 16:51:27 +0530365
Saqib438e0432020-04-03 10:02:56 +0530366def get_item_warehouse(item, args, overwrite_warehouse, defaults={}):
367 if not defaults:
368 defaults = frappe._dict({
369 'item_defaults' : get_item_defaults(item.name, args.company),
370 'item_group_defaults' : get_item_group_defaults(item.name, args.company),
371 'brand_defaults' : get_brand_defaults(item.name, args.company)
372 })
373
374 if overwrite_warehouse or not args.warehouse:
375 warehouse = (
376 args.get("set_warehouse") or
377 defaults.item_defaults.get("default_warehouse") or
378 defaults.item_group_defaults.get("default_warehouse") or
379 defaults.brand_defaults.get("default_warehouse") or
380 args.get('warehouse')
381 )
382
383 if not warehouse:
384 defaults = frappe.defaults.get_defaults() or {}
385 warehouse_exists = frappe.db.exists("Warehouse", {
386 'name': defaults.default_warehouse,
387 'company': args.company
388 })
389 if defaults.get("default_warehouse") and warehouse_exists:
390 warehouse = defaults.default_warehouse
391
392 else:
393 warehouse = args.get('warehouse')
marinatione05013e2020-04-06 22:13:13 +0530394
Saqib438e0432020-04-03 10:02:56 +0530395 return warehouse
396
Nabin Hait34c551d2019-07-03 10:34:31 +0530397def update_barcode_value(out):
398 from erpnext.accounts.doctype.sales_invoice.pos import get_barcode_data
399 barcode_data = get_barcode_data([out])
400
401 # If item has one barcode then update the value of the barcode field
402 if barcode_data and len(barcode_data.get(out.item_code)) == 1:
403 out['barcode'] = barcode_data.get(out.item_code)[0]
404
Zlash6580f5cb02018-08-29 11:39:08 +0530405@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500406def get_item_tax_info(company, tax_category, item_codes):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500407 out = {}
408 if isinstance(item_codes, string_types):
409 item_codes = json.loads(item_codes)
410
411 for item_code in item_codes:
412 if not item_code or item_code in out:
413 continue
414 out[item_code] = {}
415 item = frappe.get_cached_doc("Item", item_code)
416 get_item_tax_template({"tax_category": tax_category}, item, out[item_code])
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500417 out[item_code]["item_tax_rate"] = get_item_tax_map(company, out[item_code].get("item_tax_template"), as_json=True)
Saif Ur Rehman67786682018-12-27 02:11:07 +0500418
419 return out
420
421def get_item_tax_template(args, item, out):
422 """
423 args = {
424 "tax_category": None
425 "item_tax_template": None
426 }
427 """
428 item_tax_template = args.get("item_tax_template")
429
430 if not item_tax_template:
431 item_tax_template = _get_item_tax_template(args, item.taxes, out)
432
433 if not item_tax_template:
434 item_group = item.item_group
435 while item_group and not item_tax_template:
436 item_group_doc = frappe.get_cached_doc("Item Group", item_group)
437 item_tax_template = _get_item_tax_template(args, item_group_doc.taxes, out)
438 item_group = item_group_doc.parent_item_group
439
Deepesh Gargef0d26c2020-01-06 15:34:15 +0530440def _get_item_tax_template(args, taxes, out={}, for_validate=False):
441 taxes_with_validity = []
442 taxes_with_no_validity = []
443
444 for tax in taxes:
445 if tax.valid_from:
446 # In purchase Invoice first preference will be given to supplier invoice date
447 # if supplier date is not present then posting date
448 validation_date = args.get('transaction_date') or args.get('bill_date') or args.get('posting_date')
449
450 if getdate(tax.valid_from) <= getdate(validation_date):
451 taxes_with_validity.append(tax)
452 else:
453 taxes_with_no_validity.append(tax)
454
455 if taxes_with_validity:
456 taxes = sorted(taxes_with_validity, key = lambda i: i.valid_from, reverse=True)
457 else:
458 taxes = taxes_with_no_validity
459
460 if for_validate:
461 return [tax.item_tax_template for tax in taxes if (cstr(tax.tax_category) == cstr(args.get('tax_category')) \
462 and (tax.item_tax_template not in taxes))]
463
464 # all templates have validity and no template is valid
465 if not taxes_with_validity and (not taxes_with_no_validity):
466 return None
467
Saif Ur Rehman67786682018-12-27 02:11:07 +0500468 for tax in taxes:
469 if cstr(tax.tax_category) == cstr(args.get("tax_category")):
470 out["item_tax_template"] = tax.item_tax_template
471 return tax.item_tax_template
472 return None
473
474@frappe.whitelist()
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500475def get_item_tax_map(company, item_tax_template, as_json=True):
Saif Ur Rehman67786682018-12-27 02:11:07 +0500476 item_tax_map = {}
477 if item_tax_template:
478 template = frappe.get_cached_doc("Item Tax Template", item_tax_template)
479 for d in template.taxes:
Saif Ur Rehmaneeead1d2018-12-29 02:25:00 +0500480 if frappe.get_cached_value("Account", d.tax_type, "company") == company:
481 item_tax_map[d.tax_type] = d.tax_rate
Saif Ur Rehman67786682018-12-27 02:11:07 +0500482
483 return json.dumps(item_tax_map) if as_json else item_tax_map
484
485@frappe.whitelist()
Zlash6580f5cb02018-08-29 11:39:08 +0530486def calculate_service_end_date(args, item=None):
487 args = process_args(args)
488 if not item:
489 item = frappe.get_cached_doc("Item", args.item_code)
490
Zlash65627be1d2019-01-15 14:16:32 +0530491 doctype = args.get("parenttype") or args.get("doctype")
Zlash65a3dd7982019-01-15 14:36:11 +0530492 if doctype == "Sales Invoice":
493 enable_deferred = "enable_deferred_revenue"
494 no_of_months = "no_of_months"
495 account = "deferred_revenue_account"
496 else:
497 enable_deferred = "enable_deferred_expense"
498 no_of_months = "no_of_months_exp"
499 account = "deferred_expense_account"
Zarrare83ff382018-09-21 15:45:40 +0530500
Zlash6580f5cb02018-08-29 11:39:08 +0530501 service_start_date = args.service_start_date if args.service_start_date else args.transaction_date
Zarrare83ff382018-09-21 15:45:40 +0530502 service_end_date = add_months(service_start_date, item.get(no_of_months))
Zlash6580f5cb02018-08-29 11:39:08 +0530503 deferred_detail = {
Zlash6580f5cb02018-08-29 11:39:08 +0530504 "service_start_date": service_start_date,
505 "service_end_date": service_end_date
506 }
Zarrare83ff382018-09-21 15:45:40 +0530507 deferred_detail[enable_deferred] = item.get(enable_deferred)
508 deferred_detail[account] = get_default_deferred_account(args, item, fieldname=account)
Zlash6580f5cb02018-08-29 11:39:08 +0530509
510 return deferred_detail
tundebabzyacccdb32017-11-23 08:35:15 +0100511
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500512def get_default_income_account(args, item, item_group, brand):
Manas Solanki38667ab2018-05-16 16:55:23 +0530513 return (item.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530514 or item_group.get("income_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500515 or brand.get("income_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530516 or args.income_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530517
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500518def get_default_expense_account(args, item, item_group, brand):
Manas Solanki38667ab2018-05-16 16:55:23 +0530519 return (item.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530520 or item_group.get("expense_account")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500521 or brand.get("expense_account")
Shreya Shah3c9839f2018-07-17 18:01:44 +0530522 or args.expense_account)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530523
Zarrare83ff382018-09-21 15:45:40 +0530524def get_default_deferred_account(args, item, fieldname=None):
Zlash65627be1d2019-01-15 14:16:32 +0530525 if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
Zarrare83ff382018-09-21 15:45:40 +0530526 return (item.get(fieldname)
527 or args.get(fieldname)
528 or frappe.get_cached_value('Company', args.company, "default_"+fieldname))
Manas Solanki03938482018-05-14 16:16:46 +0530529 else:
530 return None
531
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530532def get_default_cost_center(args, item, item_group, brand, company=None):
Nabin Hait50238c32018-08-08 18:43:04 +0530533 cost_center = None
534 if args.get('project'):
535 cost_center = frappe.db.get_value("Project", args.get("project"), "cost_center", cache=True)
Rushabh Mehta49f97472018-08-30 18:50:48 +0530536
Nabin Hait50238c32018-08-08 18:43:04 +0530537 if not cost_center:
538 if args.get('customer'):
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500539 cost_center = item.get('selling_cost_center') or item_group.get('selling_cost_center') or brand.get('selling_cost_center')
Nabin Hait50238c32018-08-08 18:43:04 +0530540 else:
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500541 cost_center = item.get('buying_cost_center') or item_group.get('buying_cost_center') or brand.get('buying_cost_center')
Rushabh Mehta49f97472018-08-30 18:50:48 +0530542
Rohit Waghchaure9a792c22019-05-15 12:42:37 +0530543 cost_center = cost_center or args.get("cost_center")
544
545 if (company and cost_center
546 and frappe.get_cached_value("Cost Center", cost_center, "company") != company):
547 return None
548
549 return cost_center
Rushabh Mehta1a763742014-10-03 16:36:43 +0530550
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500551def get_default_supplier(args, item, item_group, brand):
Shreya Shah3c9839f2018-07-17 18:01:44 +0530552 return (item.get("default_supplier")
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +0500553 or item_group.get("default_supplier")
554 or brand.get("default_supplier"))
Shreya Shah3c9839f2018-07-17 18:01:44 +0530555
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530556def get_price_list_rate(args, item_doc, out):
Anand Doshi39a28912016-02-15 11:42:18 +0530557 meta = frappe.get_meta(args.parenttype or args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530558
Rohit Waghchaure4d4fb6d2018-05-15 22:12:44 +0530559 if meta.get_field("currency") or args.get('currency'):
Nabin Hait158e7dc2019-01-04 11:04:37 +0530560 pl_details = get_price_list_currency_and_exchange_rate(args)
561 args.update(pl_details)
Nabin Hait06c8cf42019-05-16 19:17:02 +0530562 if meta.get_field("currency"):
rohitwaghchaure4cccdbd2017-07-25 14:05:01 +0530563 validate_conversion_rate(args, meta)
Nabin Hait436f5262014-02-10 14:47:54 +0530564
Nabin Haite45ec662018-08-01 17:44:34 +0530565 price_list_rate = get_price_list_rate_for(args, item_doc.name) or 0
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530566
hiousi1516e292019-01-08 18:34:08 +0100567 # variant
568 if not price_list_rate and item_doc.variant_of:
569 price_list_rate = get_price_list_rate_for(args, item_doc.variant_of)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530570
571 # insert in database
Rushabh Mehta1a763742014-10-03 16:36:43 +0530572 if not price_list_rate:
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530573 if args.price_list and args.rate:
574 insert_item_price(args)
Rushabh Mehta1a763742014-10-03 16:36:43 +0530575 return {}
Anand Doshibd67e872014-04-11 16:51:27 +0530576
Nabin Hait436f5262014-02-10 14:47:54 +0530577 out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) \
578 / flt(args.conversion_rate)
mbauskar287fe812017-04-10 19:15:57 +0530579
Nabin Hait34d28222016-01-19 15:45:49 +0530580 if not out.price_list_rate and args.transaction_type=="buying":
Nabin Hait436f5262014-02-10 14:47:54 +0530581 from erpnext.stock.doctype.item.item import get_last_purchase_details
Anand Doshibd67e872014-04-11 16:51:27 +0530582 out.update(get_last_purchase_details(item_doc.name,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530583 args.name, args.conversion_rate))
Anand Doshibd67e872014-04-11 16:51:27 +0530584
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530585def insert_item_price(args):
586 """Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530587 if frappe.db.get_value("Price List", args.price_list, "currency", cache=True) == args.currency \
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530588 and cint(frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")):
589 if frappe.has_permission("Item Price", "write"):
Nabin Haite45ec662018-08-01 17:44:34 +0530590 price_list_rate = (args.rate / args.get('conversion_factor')
591 if args.get("conversion_factor") else args.rate)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530592
Nabin Haitb479a872018-09-07 13:17:11 +0530593 item_price = frappe.db.get_value('Item Price',
594 {'item_code': args.item_code, 'price_list': args.price_list, 'currency': args.currency},
595 ['name', 'price_list_rate'], as_dict=1)
596 if item_price and item_price.name:
597 if item_price.price_list_rate != price_list_rate:
598 frappe.db.set_value('Item Price', item_price.name, "price_list_rate", price_list_rate)
599 frappe.msgprint(_("Item Price updated for {0} in Price List {1}").format(args.item_code,
600 args.price_list), alert=True)
Rushabh Mehta985cb822016-12-30 15:06:54 +0530601 else:
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530602 item_price = frappe.get_doc({
603 "doctype": "Item Price",
604 "price_list": args.price_list,
605 "item_code": args.item_code,
606 "currency": args.currency,
607 "price_list_rate": price_list_rate
608 })
Kanchan Chauhan5ee8fcc2016-06-24 17:11:15 +0530609 item_price.insert()
610 frappe.msgprint(_("Item Price added for {0} in Price List {1}").format(args.item_code,
Rushabh Mehta49f97472018-08-30 18:50:48 +0530611 args.price_list), alert=True)
Rushabh Mehtaa208c562015-08-03 13:18:54 +0530612
Nabin Hait01ca3e52019-01-25 16:25:15 +0530613def get_item_price(args, item_code, ignore_party=False):
Nabin Haite45ec662018-08-01 17:44:34 +0530614 """
615 Get name, price_list_rate from Item Price based on conditions
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530616 Check if the desired qty is within the increment of the packing list.
Nabin Haite45ec662018-08-01 17:44:34 +0530617 :param args: dict (or frappe._dict) with mandatory fields price_list, uom
Nabin Hait03b116d2020-01-20 15:45:04 +0530618 optional fields transaction_date, customer, supplier
Nabin Haite45ec662018-08-01 17:44:34 +0530619 :param item_code: str, Item Doctype field item_code
620 """
621
622 args['item_code'] = item_code
Nabin Haite45ec662018-08-01 17:44:34 +0530623
Nabin Hait01ca3e52019-01-25 16:25:15 +0530624 conditions = """where item_code=%(item_code)s
Nabin Haite45ec662018-08-01 17:44:34 +0530625 and price_list=%(price_list)s
626 and ifnull(uom, '') in ('', %(uom)s)"""
627
Nabin Hait01ca3e52019-01-25 16:25:15 +0530628 if not ignore_party:
Nabin Hait01ca3e52019-01-25 16:25:15 +0530629 if args.get("customer"):
630 conditions += " and customer=%(customer)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530631 elif args.get("supplier"):
Nabin Hait01ca3e52019-01-25 16:25:15 +0530632 conditions += " and supplier=%(supplier)s"
Nabin Hait4e456632019-01-29 14:02:08 +0530633 else:
Saqib41b47a62020-05-15 04:24:36 +0530634 conditions += "and (customer is null or customer = '') and (supplier is null or supplier = '')"
Nabin Hait01ca3e52019-01-25 16:25:15 +0530635
Nabin Haite45ec662018-08-01 17:44:34 +0530636 if args.get('transaction_date'):
637 conditions += """ and %(transaction_date)s between
638 ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')"""
639
640 return frappe.db.sql(""" select name, price_list_rate, uom
641 from `tabItem Price` {conditions}
Nabin Hait03b116d2020-01-20 15:45:04 +0530642 order by valid_from desc, uom desc """.format(conditions=conditions), args)
Nabin Haite45ec662018-08-01 17:44:34 +0530643
644def get_price_list_rate_for(args, item_code):
645 """
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530646 :param customer: link to Customer DocType
647 :param supplier: link to Supplier DocType
Nabin Haite45ec662018-08-01 17:44:34 +0530648 :param price_list: str (Standard Buying or Standard Selling)
649 :param item_code: str, Item Doctype field item_code
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530650 :param qty: Desired Qty
Nabin Haite45ec662018-08-01 17:44:34 +0530651 :param transaction_date: Date of the price
652 """
653 item_price_args = {
654 "item_code": item_code,
655 "price_list": args.get('price_list'),
656 "customer": args.get('customer'),
657 "supplier": args.get('supplier'),
658 "uom": args.get('uom'),
Nabin Haite45ec662018-08-01 17:44:34 +0530659 "transaction_date": args.get('transaction_date'),
660 }
661
662 item_price_data = 0
663 price_list_rate = get_item_price(item_price_args, item_code)
664 if price_list_rate:
665 desired_qty = args.get("qty")
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530666 if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
Nabin Haite45ec662018-08-01 17:44:34 +0530667 item_price_data = price_list_rate
668 else:
Don-Leopardoccdf1932020-01-09 03:54:43 -0300669 for field in ["customer", "supplier"]:
Nabin Haite45ec662018-08-01 17:44:34 +0530670 del item_price_args[field]
671
Nabin Haite321fbb2020-01-16 13:37:25 +0530672 general_price_list_rate = get_item_price(item_price_args, item_code,
673 ignore_party=args.get("ignore_party"))
Don-Leopardoccdf1932020-01-09 03:54:43 -0300674
Nabin Haite45ec662018-08-01 17:44:34 +0530675 if not general_price_list_rate and args.get("uom") != args.get("stock_uom"):
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530676 item_price_args["uom"] = args.get("stock_uom")
Nabin Hait01ca3e52019-01-25 16:25:15 +0530677 general_price_list_rate = get_item_price(item_price_args, item_code, ignore_party=args.get("ignore_party"))
Nabin Haite45ec662018-08-01 17:44:34 +0530678
679 if general_price_list_rate:
680 item_price_data = general_price_list_rate
681
682 if item_price_data:
683 if item_price_data[0][2] == args.get("uom"):
684 return item_price_data[0][1]
685 elif not args.get('price_list_uom_dependant'):
686 return flt(item_price_data[0][1] * flt(args.get("conversion_factor", 1)))
687 else:
688 return item_price_data[0][1]
689
690def check_packing_list(price_list_rate_name, desired_qty, item_code):
691 """
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530692 Check if the desired qty is within the increment of the packing list.
Nabin Haite45ec662018-08-01 17:44:34 +0530693 :param price_list_rate_name: Name of Item Price
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530694 :param desired_qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530695 :param item_code: str, Item Doctype field item_code
Suraj Shettyc87b47a2019-04-29 23:18:47 +0530696 :param qty: Desired Qt
Nabin Haite45ec662018-08-01 17:44:34 +0530697 """
698
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530699 flag = True
Nabin Haite45ec662018-08-01 17:44:34 +0530700 item_price = frappe.get_doc("Item Price", price_list_rate_name)
Rohit Waghchaureb48effe2019-02-27 19:31:32 +0530701 if item_price.packing_unit:
Nabin Haite45ec662018-08-01 17:44:34 +0530702 packing_increment = desired_qty % item_price.packing_unit
703
Rohit Waghchaurecd34c702019-02-27 18:01:25 +0530704 if packing_increment != 0:
705 flag = False
706
707 return flag
Rushabh Mehta1a763742014-10-03 16:36:43 +0530708
Nabin Hait436f5262014-02-10 14:47:54 +0530709def validate_conversion_rate(args, meta):
Rushabh Mehta66e08e32014-09-29 12:17:03 +0530710 from erpnext.controllers.accounts_controller import validate_conversion_rate
Anand Doshibd67e872014-04-11 16:51:27 +0530711
Anand Doshife13bfe2015-08-25 12:49:40 +0530712 if (not args.conversion_rate
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530713 and args.currency==frappe.get_cached_value('Company', args.company, "default_currency")):
Anand Doshife13bfe2015-08-25 12:49:40 +0530714 args.conversion_rate = 1.0
715
Nabin Hait436f5262014-02-10 14:47:54 +0530716 # validate currency conversion rate
Anand Doshibd67e872014-04-11 16:51:27 +0530717 validate_conversion_rate(args.currency, args.conversion_rate,
Nabin Hait436f5262014-02-10 14:47:54 +0530718 meta.get_label("conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530719
720 args.conversion_rate = flt(args.conversion_rate,
721 get_field_precision(meta.get_field("conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530722 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530723
Nabin Hait06c8cf42019-05-16 19:17:02 +0530724 if args.price_list:
725 if (not args.plc_conversion_rate
726 and args.price_list_currency==frappe.db.get_value("Price List", args.price_list, "currency", cache=True)):
727 args.plc_conversion_rate = 1.0
Manas Solanki3504a232018-06-06 12:46:06 +0530728
Nabin Hait06c8cf42019-05-16 19:17:02 +0530729 # validate price list currency conversion rate
730 if not args.get("price_list_currency"):
731 throw(_("Price List Currency not selected"))
732 else:
733 validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate,
734 meta.get_label("plc_conversion_rate"), args.company)
Anand Doshibd67e872014-04-11 16:51:27 +0530735
Nabin Hait06c8cf42019-05-16 19:17:02 +0530736 if meta.get_field("plc_conversion_rate"):
737 args.plc_conversion_rate = flt(args.plc_conversion_rate,
738 get_field_precision(meta.get_field("plc_conversion_rate"),
739 frappe._dict({"fields": args})))
Anand Doshibd67e872014-04-11 16:51:27 +0530740
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530741def get_party_item_code(args, item_doc, out):
Nabin Hait34d28222016-01-19 15:45:49 +0530742 if args.transaction_type=="selling" and args.customer:
Zarrar3fd63472018-03-09 12:10:45 +0530743 out.customer_item_code = None
Nabin Hait34c551d2019-07-03 10:34:31 +0530744
745 if args.quotation_to and args.quotation_to != 'Customer':
746 return
747
Nabin Hait79f091e2014-12-26 11:41:15 +0530748 customer_item_code = item_doc.get("customer_items", {"customer_name": args.customer})
Zarrar3fd63472018-03-09 12:10:45 +0530749
750 if customer_item_code:
751 out.customer_item_code = customer_item_code[0].ref_code
752 else:
Nabin Hait9a33bc62018-08-09 10:47:09 +0530753 customer_group = frappe.get_cached_value("Customer", args.customer, "customer_group")
Zarrar3fd63472018-03-09 12:10:45 +0530754 customer_group_item_code = item_doc.get("customer_items", {"customer_group": customer_group})
755 if customer_group_item_code and not customer_group_item_code[0].customer_name:
756 out.customer_item_code = customer_group_item_code[0].ref_code
Anand Doshi54abf022016-01-21 22:28:47 +0530757
Nabin Hait34d28222016-01-19 15:45:49 +0530758 if args.transaction_type=="buying" and args.supplier:
Nabin Hait79f091e2014-12-26 11:41:15 +0530759 item_supplier = item_doc.get("supplier_items", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +0530760 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
Anand Doshibd67e872014-04-11 16:51:27 +0530761
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530762def get_pos_profile_item_details(company, args, pos_profile=None, update_data=False):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530763 res = frappe._dict()
Anand Doshibd67e872014-04-11 16:51:27 +0530764
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530765 if not frappe.flags.pos_profile and not pos_profile:
766 pos_profile = frappe.flags.pos_profile = get_pos_profile(company, args.get('pos_profile'))
Anand Doshibd67e872014-04-11 16:51:27 +0530767
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530768 if pos_profile:
Nabin Hait436f5262014-02-10 14:47:54 +0530769 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
rohitwaghchaure2ea593b2018-04-12 13:37:08 +0530770 if (not args.get(fieldname) or update_data) and pos_profile.get(fieldname):
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530771 res[fieldname] = pos_profile.get(fieldname)
Anand Doshibd67e872014-04-11 16:51:27 +0530772
Nabin Hait436f5262014-02-10 14:47:54 +0530773 if res.get("warehouse"):
Saurabhd3135532016-02-25 18:59:20 +0530774 res.actual_qty = get_bin_details(args.item_code,
Nabin Hait436f5262014-02-10 14:47:54 +0530775 res.warehouse).get("actual_qty")
Anand Doshibd67e872014-04-11 16:51:27 +0530776
Nabin Hait436f5262014-02-10 14:47:54 +0530777 return res
778
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530779@frappe.whitelist()
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530780def get_pos_profile(company, pos_profile=None, user=None):
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530781 if pos_profile: return frappe.get_cached_doc('POS Profile', pos_profile)
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530782
783 if not user:
784 user = frappe.session['user']
785
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530786 condition = "pfu.user = %(user)s AND pfu.default=1"
787 if user and company:
788 condition = "pfu.user = %(user)s AND pf.company = %(company)s AND pfu.default=1"
789
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530790 pos_profile = frappe.db.sql("""SELECT pf.*
791 FROM
792 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
793 ON
rohitwaghchaurec037dc72017-11-28 16:11:15 +0530794 pf.name = pfu.parent
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530795 WHERE
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530796 {cond} AND pf.disabled = 0
797 """.format(cond = condition), {
Suraj Shetty1eb098c2018-11-21 14:36:58 +0530798 'user': user,
799 'company': company
800 }, as_dict=1)
Anand Doshibd67e872014-04-11 16:51:27 +0530801
Rohit Waghchauree8e3fb12019-04-05 00:42:48 +0530802 if not pos_profile and company:
803 pos_profile = frappe.db.sql("""SELECT pf.*
804 FROM
805 `tabPOS Profile` pf LEFT JOIN `tabPOS Profile User` pfu
806 ON
807 pf.name = pfu.parent
808 WHERE
809 pf.company = %(company)s AND pf.disabled = 0
810 """, {
811 'company': company
812 }, as_dict=1)
813
Rushabh Mehtaad9156a2015-08-18 15:29:42 +0530814 return pos_profile and pos_profile[0] or None
Anand Doshibd67e872014-04-11 16:51:27 +0530815
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530816def get_serial_nos_by_fifo(args, sales_order=None):
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530817 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
818 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530819 where item_code=%(item_code)s and warehouse=%(warehouse)s and
820 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
821 order by timestamp(purchase_date, purchase_time)
822 asc limit %(qty)s""",
823 {
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530824 "item_code": args.item_code,
825 "warehouse": args.warehouse,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530826 "qty": abs(cint(args.stock_qty)),
827 "sales_order": sales_order
Rushabh Mehta85abdc42015-09-03 10:29:38 +0530828 }))
Nabin Hait08222152014-02-28 11:30:47 +0530829
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530830def get_serial_no_batchwise(args, sales_order=None):
Shreyaa20157a2018-04-13 12:03:42 +0530831 if frappe.db.get_single_value("Stock Settings", "automatically_set_serial_nos_based_on_fifo"):
832 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530833 where item_code=%(item_code)s and warehouse=%(warehouse)s and
834 sales_order=IF(%(sales_order)s IS NULL, sales_order, %(sales_order)s)
835 and batch_no=IF(%(batch_no)s IS NULL, batch_no, %(batch_no)s) order
836 by timestamp(purchase_date, purchase_time) asc limit %(qty)s""", {
Shreyaa20157a2018-04-13 12:03:42 +0530837 "item_code": args.item_code,
838 "warehouse": args.warehouse,
839 "batch_no": args.batch_no,
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +0530840 "qty": abs(cint(args.stock_qty)),
841 "sales_order": sales_order
Shreyaa20157a2018-04-13 12:03:42 +0530842 }))
843
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530844@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530845def get_conversion_factor(item_code, uom):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530846 variant_of = frappe.db.get_value("Item", item_code, "variant_of", cache=True)
Rushabh Mehta724f9e52014-10-07 15:29:58 +0530847 filters = {"parent": item_code, "uom": uom}
848 if variant_of:
Nabin Hait314086d2015-10-07 11:55:01 +0530849 filters["parent"] = ("in", (item_code, variant_of))
Sagar Vora508189e2018-09-11 17:22:25 +0530850 conversion_factor = frappe.db.get_value("UOM Conversion Detail",
851 filters, "conversion_factor")
852 if not conversion_factor:
853 stock_uom = frappe.db.get_value("Item", item_code, "stock_uom")
854 conversion_factor = get_uom_conv_factor(uom, stock_uom)
rohitwaghchaureffdadbf2019-01-08 16:21:25 +0530855 return {"conversion_factor": conversion_factor or 1.0}
Nabin Hait08222152014-02-28 11:30:47 +0530856
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530857@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530858def get_projected_qty(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530859 return {"projected_qty": frappe.db.get_value("Bin",
Nabin Hait436f5262014-02-10 14:47:54 +0530860 {"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
Nabin Hait08222152014-02-28 11:30:47 +0530861
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530862@frappe.whitelist()
Saurabhd3135532016-02-25 18:59:20 +0530863def get_bin_details(item_code, warehouse):
Anand Doshibd67e872014-04-11 16:51:27 +0530864 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Nabin Haita804d6d2018-08-29 13:34:58 +0530865 ["projected_qty", "actual_qty", "reserved_qty"], as_dict=True, cache=True) \
Shreya Shahbe770332018-08-22 14:45:22 +0530866 or {"projected_qty": 0, "actual_qty": 0, "reserved_qty": 0}
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530867
868@frappe.whitelist()
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530869def get_serial_no_details(item_code, warehouse, stock_qty, serial_no):
870 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "serial_no":serial_no})
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530871 serial_no = get_serial_no(args)
872 return {'serial_no': serial_no}
Rushabh Mehta985cb822016-12-30 15:06:54 +0530873
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530874@frappe.whitelist()
Rohit Waghchaure6daab3c2019-09-19 17:01:26 +0530875def get_bin_details_and_serial_nos(item_code, warehouse, has_batch_no=None, stock_qty=None, serial_no=None):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530876 bin_details_and_serial_nos = {}
877 bin_details_and_serial_nos.update(get_bin_details(item_code, warehouse))
Rushabh Mehta49f97472018-08-30 18:50:48 +0530878 if flt(stock_qty) > 0:
Shreyaa20157a2018-04-13 12:03:42 +0530879 if has_batch_no:
880 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty})
881 serial_no = get_serial_no(args)
882 bin_details_and_serial_nos.update({'serial_no': serial_no})
883 return bin_details_and_serial_nos
884
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +0530885 bin_details_and_serial_nos.update(get_serial_no_details(item_code, warehouse, stock_qty, serial_no))
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +0530886 return bin_details_and_serial_nos
Anand Doshidffec8f2014-07-01 17:45:15 +0530887
888@frappe.whitelist()
Shreyaa20157a2018-04-13 12:03:42 +0530889def get_batch_qty_and_serial_no(batch_no, stock_qty, warehouse, item_code, has_serial_no):
890 batch_qty_and_serial_no = {}
891 batch_qty_and_serial_no.update(get_batch_qty(batch_no, warehouse, item_code))
892
893 if (flt(batch_qty_and_serial_no.get('actual_batch_qty')) >= flt(stock_qty)) and has_serial_no:
894 args = frappe._dict({"item_code":item_code, "warehouse":warehouse, "stock_qty":stock_qty, "batch_no":batch_no})
895 serial_no = get_serial_no(args)
896 batch_qty_and_serial_no.update({'serial_no': serial_no})
897 return batch_qty_and_serial_no
898
899@frappe.whitelist()
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530900def get_batch_qty(batch_no, warehouse, item_code):
sburanaw66951e52017-04-25 15:28:57 +0700901 from erpnext.stock.doctype.batch import batch
Sambhaji Kolate98dbccd2015-03-10 15:04:28 +0530902 if batch_no:
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530903 return {'actual_batch_qty': batch.get_batch_qty(batch_no, warehouse)}
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530904
Anand Doshidffec8f2014-07-01 17:45:15 +0530905@frappe.whitelist()
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530906def apply_price_list(args, as_doc=False):
907 """Apply pricelist on a document-like dict object and return as
908 {'parent': dict, 'children': list}
909
910 :param args: See below
911 :param as_doc: Updates value in the passed dict
912
Anand Doshidffec8f2014-07-01 17:45:15 +0530913 args = {
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530914 "doctype": "",
915 "name": "",
916 "items": [{"doctype": "", "name": "", "item_code": "", "brand": "", "item_group": ""}, ...],
Anand Doshidffec8f2014-07-01 17:45:15 +0530917 "conversion_rate": 1.0,
918 "selling_price_list": None,
919 "price_list_currency": None,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530920 "price_list_uom_dependant": None,
Anand Doshidffec8f2014-07-01 17:45:15 +0530921 "plc_conversion_rate": 1.0,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530922 "doctype": "",
923 "name": "",
Anand Doshidffec8f2014-07-01 17:45:15 +0530924 "supplier": None,
925 "transaction_date": None,
926 "conversion_rate": 1.0,
927 "buying_price_list": None,
Anand Doshidffec8f2014-07-01 17:45:15 +0530928 "ignore_pricing_rule": 0/1
929 }
930 """
931 args = process_args(args)
932
933 parent = get_price_list_currency_and_exchange_rate(args)
934 children = []
935
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530936 if "items" in args:
937 item_list = args.get("items")
Anand Doshidffec8f2014-07-01 17:45:15 +0530938 args.update(parent)
939
940 for item in item_list:
941 args_copy = frappe._dict(args.copy())
942 args_copy.update(item)
943 item_details = apply_price_list_on_item(args_copy)
944 children.append(item_details)
945
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530946 if as_doc:
Shreya Shahb13a54a2017-12-06 19:17:04 +0530947 args.price_list_currency = parent.price_list_currency,
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530948 args.plc_conversion_rate = parent.plc_conversion_rate
949 if args.get('items'):
950 for i, item in enumerate(args.get('items')):
951 for fieldname in children[i]:
952 # if the field exists in the original doc
953 # update the value
954 if fieldname in item and fieldname not in ("name", "doctype"):
955 item[fieldname] = children[i][fieldname]
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530956 return args
957 else:
958 return {
959 "parent": parent,
960 "children": children
961 }
Anand Doshidffec8f2014-07-01 17:45:15 +0530962
963def apply_price_list_on_item(args):
964 item_details = frappe._dict()
965 item_doc = frappe.get_doc("Item", args.item_code)
966 get_price_list_rate(args, item_doc, item_details)
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530967
Rohit Waghchaure8bfe3302019-03-18 14:34:19 +0530968 item_details.update(get_pricing_rule_for_item(args, item_details.price_list_rate))
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530969
Anand Doshidffec8f2014-07-01 17:45:15 +0530970 return item_details
971
Anand Doshidffec8f2014-07-01 17:45:15 +0530972def get_price_list_currency_and_exchange_rate(args):
Anand Doshi70f57eb2015-11-27 14:37:40 +0530973 if not args.price_list:
974 return {}
975
Shreya3f778522018-05-15 16:59:20 +0530976 if args.doctype in ['Quotation', 'Sales Order', 'Delivery Note', 'Sales Invoice']:
977 args.update({"exchange_rate": "for_selling"})
978 elif args.doctype in ['Purchase Order', 'Purchase Receipt', 'Purchase Invoice']:
979 args.update({"exchange_rate": "for_buying"})
980
rohitwaghchaurea85ddf22019-11-19 18:47:48 +0530981 price_list_details = get_price_list_details(args.price_list)
982
983 price_list_currency = price_list_details.get("currency")
984 price_list_uom_dependant = price_list_details.get("price_list_uom_dependant")
985
Anand Doshidffec8f2014-07-01 17:45:15 +0530986 plc_conversion_rate = args.plc_conversion_rate
tundebabzy6e90f492018-02-12 10:48:57 +0100987 company_currency = get_company_currency(args.company)
Anand Doshidffec8f2014-07-01 17:45:15 +0530988
Nabin Haitdd82bf22015-05-11 16:49:17 +0530989 if (not plc_conversion_rate) or (price_list_currency and args.price_list_currency \
990 and price_list_currency != args.price_list_currency):
Rushabh Mehta6b537922017-03-14 16:59:11 +0530991 # cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
tundebabzy6e90f492018-02-12 10:48:57 +0100992 plc_conversion_rate = get_exchange_rate(price_list_currency, company_currency,
Shreya3f778522018-05-15 16:59:20 +0530993 args.transaction_date, args.exchange_rate) or plc_conversion_rate
Anand Doshidffec8f2014-07-01 17:45:15 +0530994
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530995 return frappe._dict({
Anand Doshidffec8f2014-07-01 17:45:15 +0530996 "price_list_currency": price_list_currency,
Shreya Shahb13a54a2017-12-06 19:17:04 +0530997 "price_list_uom_dependant": price_list_uom_dependant,
Anand Doshidffec8f2014-07-01 17:45:15 +0530998 "plc_conversion_rate": plc_conversion_rate
Rushabh Mehtab46069d2016-01-15 16:59:26 +0530999 })
ankitjavalkarwork5edae0e2014-11-05 20:14:53 +05301000
1001@frappe.whitelist()
1002def get_default_bom(item_code=None):
1003 if item_code:
1004 bom = frappe.db.get_value("BOM", {"docstatus": 1, "is_default": 1, "is_active": 1, "item": item_code})
1005 if bom:
1006 return bom
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301007
Deepesh Garg15ff6a52020-02-18 12:28:41 +05301008@frappe.whitelist()
Manas Solanki087a2252018-05-04 16:02:38 +05301009def get_valuation_rate(item_code, company, warehouse=None):
Manas Solankib16a4ec2018-05-04 16:49:33 +05301010 item = get_item_defaults(item_code, company)
Shreya Shah3c9839f2018-07-17 18:01:44 +05301011 item_group = get_item_group_defaults(item_code, company)
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001012 brand = get_brand_defaults(item_code, company)
Manas Solanki087a2252018-05-04 16:02:38 +05301013 # item = frappe.get_doc("Item", item_code)
Manas Solankie3910fb2018-05-16 15:50:17 +05301014 if item.get("is_stock_item"):
Saurabhbd01a812016-03-07 14:32:23 +05301015 if not warehouse:
Saif Ur Rehmanc819ea32018-09-25 14:53:12 +05001016 warehouse = item.get("default_warehouse") or item_group.get("default_warehouse") or brand.get("default_warehouse")
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301017
1018 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Saurabhbd01a812016-03-07 14:32:23 +05301019 ["valuation_rate"], as_dict=True) or {"valuation_rate": 0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301020
Manas Solankie3910fb2018-05-16 15:50:17 +05301021 elif not item.get("is_stock_item"):
Nabin Haitfe876c02017-03-06 16:32:57 +05301022 valuation_rate =frappe.db.sql("""select sum(base_net_amount) / sum(qty*conversion_factor)
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301023 from `tabPurchase Invoice Item`
Saurabhbd01a812016-03-07 14:32:23 +05301024 where item_code = %s and docstatus=1""", item_code)
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301025
Saurabhbd01a812016-03-07 14:32:23 +05301026 if valuation_rate:
1027 return {"valuation_rate": valuation_rate[0][0] or 0.0}
1028 else:
1029 return {"valuation_rate": 0.0}
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301030
Saurabh2d7af632016-02-26 11:09:20 +05301031def get_gross_profit(out):
Saurabh5ada14b2016-02-26 18:02:55 +05301032 if out.valuation_rate:
1033 out.update({
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301034 "gross_profit": ((out.base_rate - out.valuation_rate) * out.stock_qty)
Saurabh5ada14b2016-02-26 18:02:55 +05301035 })
Rushabh Mehta0394aec2016-04-22 17:22:22 +05301036
Saurabhd3135532016-02-25 18:59:20 +05301037 return out
mbauskar6f603392016-01-21 16:10:22 +05301038
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301039@frappe.whitelist()
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301040def get_serial_no(args, serial_nos=None, sales_order=None):
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +05301041 serial_no = None
Achilles Rasquinha56b2e122018-02-13 14:42:40 +05301042 if isinstance(args, string_types):
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301043 args = json.loads(args)
1044 args = frappe._dict(args)
Rohit Waghchauredc981dc2017-04-03 14:17:08 +05301045 if args.get('doctype') == 'Sales Invoice' and not args.get('update_stock'):
1046 return ""
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301047 if args.get('warehouse') and args.get('stock_qty') and args.get('item_code'):
Shreyaa20157a2018-04-13 12:03:42 +05301048 has_serial_no = frappe.get_value('Item', {'item_code': args.item_code}, "has_serial_no")
Shreyaa20157a2018-04-13 12:03:42 +05301049 if args.get('batch_no') and has_serial_no == 1:
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301050 return get_serial_no_batchwise(args, sales_order)
Shreyaa20157a2018-04-13 12:03:42 +05301051 elif has_serial_no == 1:
Kanchan Chauhan5a980ac2017-02-10 14:27:11 +05301052 args = json.dumps({"item_code": args.get('item_code'),"warehouse": args.get('warehouse'),"stock_qty": args.get('stock_qty')})
Kanchan Chauhanaf0d6372016-11-13 21:19:09 +05301053 args = process_args(args)
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301054 serial_no = get_serial_nos_by_fifo(args, sales_order)
Rohit Waghchaureba3f0e62017-08-28 17:19:28 +05301055
1056 if not serial_no and serial_nos:
1057 # For POS
1058 serial_no = serial_nos
1059
1060 return serial_no
Manas Solankie5e87f72018-05-28 20:07:08 +05301061
1062
1063def update_party_blanket_order(args, out):
ronelvcabrera370cdc02019-12-04 18:37:11 +08001064 if out["against_blanket_order"]:
1065 blanket_order_details = get_blanket_order_details(args)
1066 if blanket_order_details:
1067 out.update(blanket_order_details)
Manas Solankie5e87f72018-05-28 20:07:08 +05301068
1069@frappe.whitelist()
1070def get_blanket_order_details(args):
1071 if isinstance(args, string_types):
1072 args = frappe._dict(json.loads(args))
1073
1074 blanket_order_details = None
Nabin Hait2737b082018-06-14 18:07:22 +05301075 condition = ''
Manas Solankie5e87f72018-05-28 20:07:08 +05301076 if args.item_code:
1077 if args.customer and args.doctype == "Sales Order":
Nabin Hait2737b082018-06-14 18:07:22 +05301078 condition = ' and bo.customer=%(customer)s'
Manas Solankie5e87f72018-05-28 20:07:08 +05301079 elif args.supplier and args.doctype == "Purchase Order":
Nabin Hait2737b082018-06-14 18:07:22 +05301080 condition = ' and bo.supplier=%(supplier)s'
Manas Solankie5e87f72018-05-28 20:07:08 +05301081 if args.blanket_order:
Nabin Hait2737b082018-06-14 18:07:22 +05301082 condition += ' and bo.name =%(blanket_order)s'
1083 if args.transaction_date:
1084 condition += ' and bo.to_date>=%(transaction_date)s'
1085
Manas Solankie5e87f72018-05-28 20:07:08 +05301086 blanket_order_details = frappe.db.sql('''
1087 select boi.rate as blanket_order_rate, bo.name as blanket_order
1088 from `tabBlanket Order` bo, `tabBlanket Order Item` boi
Nabin Hait2737b082018-06-14 18:07:22 +05301089 where bo.company=%(company)s and boi.item_code=%(item_code)s
1090 and bo.docstatus=1 and bo.name = boi.parent {0}
1091 '''.format(condition), args, as_dict=True)
1092
Manas Solankie5e87f72018-05-28 20:07:08 +05301093 blanket_order_details = blanket_order_details[0] if blanket_order_details else ''
1094 return blanket_order_details
Ranjith Kurungadamd54991d2018-08-01 17:47:07 +05301095
1096def get_so_reservation_for_item(args):
1097 reserved_so = None
1098 if args.get('against_sales_order'):
1099 if get_reserved_qty_for_so(args.get('against_sales_order'), args.get('item_code')):
1100 reserved_so = args.get('against_sales_order')
1101 elif args.get('against_sales_invoice'):
1102 sales_order = frappe.db.sql("""select sales_order from `tabSales Invoice Item` where
1103 parent=%s and item_code=%s""", (args.get('against_sales_invoice'), args.get('item_code')))
1104 if sales_order and sales_order[0]:
1105 if get_reserved_qty_for_so(sales_order[0][0], args.get('item_code')):
1106 reserved_so = sales_order[0]
1107 elif args.get("sales_order"):
1108 if get_reserved_qty_for_so(args.get('sales_order'), args.get('item_code')):
1109 reserved_so = args.get('sales_order')
1110 return reserved_so
1111
1112def get_reserved_qty_for_so(sales_order, item_code):
1113 reserved_qty = frappe.db.sql("""select sum(qty) from `tabSales Order Item`
1114 where parent=%s and item_code=%s and ensure_delivery_based_on_produced_serial_no=1
1115 """, (sales_order, item_code))
1116 if reserved_qty and reserved_qty[0][0]:
1117 return reserved_qty[0][0]
1118 else:
1119 return 0