blob: eeff2750ef2f414045fecbf436d2548b5c8169f6 [file] [log] [blame]
Nabin Hait436f5262014-02-10 14:47:54 +05301# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
2# 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
7from frappe.utils import flt, cint, add_days
Nabin Hait436f5262014-02-10 14:47:54 +05308import json
9
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053010@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +053011def get_item_details(args):
12 """
13 args = {
14 "item_code": "",
15 "warehouse": None,
16 "customer": "",
17 "conversion_rate": 1.0,
18 "selling_price_list": None,
19 "price_list_currency": None,
Nabin Hait615d3422014-02-25 19:01:20 +053020 "plc_conversion_rate": 1.0,
Nabin Hait436f5262014-02-10 14:47:54 +053021 "doctype": "",
22 "docname": "",
23 "supplier": None,
24 "transaction_date": None,
25 "conversion_rate": 1.0,
26 "buying_price_list": None,
27 "is_subcontracted": "Yes" / "No",
28 "transaction_type": "selling"
29 }
30 """
31
32 if isinstance(args, basestring):
33 args = json.loads(args)
Anand Doshi4b269212014-03-19 16:58:42 +053034
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053035 args = frappe._dict(args)
Nabin Hait0f231062014-02-20 11:27:47 +053036
Nabin Hait0aa71a52014-02-11 16:14:52 +053037 if not args.get("transaction_type"):
Rushabh Mehta0a0f2492014-03-31 17:27:06 +053038 args.transaction_type = "buying" if frappe.get_meta(args.get("doctype")).get_field("supplier") \
Nabin Hait0f231062014-02-20 11:27:47 +053039 else "selling"
Nabin Hait139dc7b2014-02-12 14:53:18 +053040
41 if not args.get("price_list"):
42 args.price_list = args.get("selling_price_list") or args.get("buying_price_list")
Nabin Hait0aa71a52014-02-11 16:14:52 +053043
Nabin Hait436f5262014-02-10 14:47:54 +053044 if args.barcode:
45 args.item_code = get_item_code(barcode=args.barcode)
46 elif not args.item_code and args.serial_no:
47 args.item_code = get_item_code(serial_no=args.serial_no)
48
Rushabh Mehtaf14b8092014-04-03 14:30:42 +053049 item_doc = frappe.get_doc("Item", args.item_code)
50 item = item_doc
Nabin Hait436f5262014-02-10 14:47:54 +053051
52 validate_item_details(args, item)
53
Rushabh Mehtaf14b8092014-04-03 14:30:42 +053054 out = get_basic_details(args, item_doc)
Nabin Hait436f5262014-02-10 14:47:54 +053055
Rushabh Mehtaf14b8092014-04-03 14:30:42 +053056 get_party_item_code(args, item_doc, out)
Nabin Hait436f5262014-02-10 14:47:54 +053057
58 if out.get("warehouse"):
59 out.update(get_available_qty(args.item_code, out.warehouse))
60 out.update(get_projected_qty(item.name, out.warehouse))
61
Rushabh Mehtaf14b8092014-04-03 14:30:42 +053062 get_price_list_rate(args, item_doc, out)
Nabin Hait436f5262014-02-10 14:47:54 +053063
64 if args.transaction_type == "selling" and cint(args.is_pos):
65 out.update(get_pos_settings_item_details(args.company, args))
Nabin Hait615d3422014-02-25 19:01:20 +053066
67 apply_pricing_rule(out, args)
Nabin Hait436f5262014-02-10 14:47:54 +053068
Nabin Hait139dc7b2014-02-12 14:53:18 +053069 if args.get("doctype") in ("Sales Invoice", "Delivery Note"):
Rushabh Mehtaf14b8092014-04-03 14:30:42 +053070 if item_doc.has_serial_no == "Yes" and not args.serial_no:
71 out.serial_no = get_serial_nos_by_fifo(args, item_doc)
Nabin Hait139dc7b2014-02-12 14:53:18 +053072
73 if args.transaction_date and item.lead_time_days:
74 out.schedule_date = out.lead_time_date = add_days(args.transaction_date,
75 item.lead_time_days)
Nabin Hait436f5262014-02-10 14:47:54 +053076
77 return out
78
Nabin Hait436f5262014-02-10 14:47:54 +053079def get_item_code(barcode=None, serial_no=None):
80 if barcode:
Anand Doshie9baaa62014-02-26 12:35:33 +053081 item_code = frappe.db.get_value("Item", {"barcode": barcode})
Nabin Hait436f5262014-02-10 14:47:54 +053082 elif serial_no:
Anand Doshie9baaa62014-02-26 12:35:33 +053083 item_code = frappe.db.get_value("Serial No", serial_no, "item_code")
Nabin Hait436f5262014-02-10 14:47:54 +053084
85 if not item_code:
86 throw(_("No Item found with ") + _("Barcode") if barcode else _("Serial No") +
87 ": %s" % (barcode or serial_no))
88
89 return item_code
90
91def validate_item_details(args, item):
92 if not args.company:
93 throw(_("Please specify Company"))
94
95 from erpnext.stock.doctype.item.item import validate_end_of_life
96 validate_end_of_life(item.name, item.end_of_life)
97
98 if args.transaction_type == "selling":
99 # validate if sales item or service item
Nabin Hait139dc7b2014-02-12 14:53:18 +0530100 if args.get("order_type") == "Maintenance":
Nabin Hait436f5262014-02-10 14:47:54 +0530101 if item.is_service_item != "Yes":
102 throw(_("Item") + (" %s: " % item.name) +
Nabin Hait08222152014-02-28 11:30:47 +0530103 _("is not a service item.") +
Nabin Hait436f5262014-02-10 14:47:54 +0530104 _("Please select a service item or change the order type to Sales."))
105
106 elif item.is_sales_item != "Yes":
Nabin Hait08222152014-02-28 11:30:47 +0530107 throw(_("Item") + (" %s: " % item.name) + _("is not a sales item"))
Nabin Hait436f5262014-02-10 14:47:54 +0530108
109 elif args.transaction_type == "buying":
110 # validate if purchase item or subcontracted item
111 if item.is_purchase_item != "Yes":
Nabin Hait08222152014-02-28 11:30:47 +0530112 throw(_("Item") + (" %s: " % item.name) + _("is not a purchase item"))
Nabin Hait436f5262014-02-10 14:47:54 +0530113
Nabin Hait139dc7b2014-02-12 14:53:18 +0530114 if args.get("is_subcontracted") == "Yes" and item.is_sub_contracted_item != "Yes":
Nabin Hait436f5262014-02-10 14:47:54 +0530115 throw(_("Item") + (" %s: " % item.name) +
116 _("not a sub-contracted item.") +
117 _("Please select a sub-contracted item or do not sub-contract the transaction."))
118
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530119def get_basic_details(args, item_doc):
120 item = item_doc
Nabin Hait436f5262014-02-10 14:47:54 +0530121
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530122 from frappe.defaults import get_user_default_as_list
Nabin Hait436f5262014-02-10 14:47:54 +0530123 user_default_warehouse_list = get_user_default_as_list('warehouse')
124 user_default_warehouse = user_default_warehouse_list[0] \
125 if len(user_default_warehouse_list)==1 else ""
Nabin Hait36028bf2014-02-12 19:09:28 +0530126
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530127 out = frappe._dict({
Nabin Hait139dc7b2014-02-12 14:53:18 +0530128 "item_code": item.name,
129 "item_name": item.item_name,
130 "description": item.description_html or item.description,
131 "warehouse": user_default_warehouse or args.warehouse or item.default_warehouse,
Nabin Haiteba1bdb2014-02-12 16:04:17 +0530132 "income_account": item.income_account or args.income_account \
Anand Doshie9baaa62014-02-26 12:35:33 +0530133 or frappe.db.get_value("Company", args.company, "default_income_account"),
Nabin Hait139dc7b2014-02-12 14:53:18 +0530134 "expense_account": item.expense_account or args.expense_account \
Anand Doshie9baaa62014-02-26 12:35:33 +0530135 or frappe.db.get_value("Company", args.company, "default_expense_account"),
Nabin Hait139dc7b2014-02-12 14:53:18 +0530136 "cost_center": item.selling_cost_center \
Nabin Hait36028bf2014-02-12 19:09:28 +0530137 if args.transaction_type == "selling" else item.buying_cost_center,
Nabin Hait139dc7b2014-02-12 14:53:18 +0530138 "batch_no": None,
139 "item_tax_rate": json.dumps(dict(([d.tax_type, d.tax_rate] for d in
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530140 item_doc.get("item_tax")))),
Nabin Hait139dc7b2014-02-12 14:53:18 +0530141 "uom": item.stock_uom,
142 "min_order_qty": flt(item.min_order_qty) if args.doctype == "Material Request" else "",
143 "conversion_factor": 1.0,
144 "qty": 1.0,
145 "price_list_rate": 0.0,
146 "base_price_list_rate": 0.0,
147 "rate": 0.0,
148 "base_rate": 0.0,
149 "amount": 0.0,
150 "base_amount": 0.0,
151 "discount_percentage": 0.0
152 })
Nabin Hait436f5262014-02-10 14:47:54 +0530153
154 for fieldname in ("item_name", "item_group", "barcode", "brand", "stock_uom"):
Anand Doshif78d1ae2014-03-28 13:55:00 +0530155 out[fieldname] = item.get(fieldname)
Nabin Hait436f5262014-02-10 14:47:54 +0530156
157 return out
158
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530159def get_price_list_rate(args, item_doc, out):
Rushabh Mehtae88bc8b2014-03-27 17:51:41 +0530160 meta = frappe.get_meta(args.doctype)
Nabin Hait436f5262014-02-10 14:47:54 +0530161
162 if meta.get_field("currency"):
163 validate_price_list(args)
164 validate_conversion_rate(args, meta)
165
Anand Doshie9baaa62014-02-26 12:35:33 +0530166 price_list_rate = frappe.db.get_value("Item Price",
Nabin Haita7f757a2014-02-10 17:54:04 +0530167 {"price_list": args.price_list, "item_code": args.item_code}, "price_list_rate")
Nabin Hait436f5262014-02-10 14:47:54 +0530168
169 if not price_list_rate: return {}
170
171 out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) \
172 / flt(args.conversion_rate)
173
174 if not out.price_list_rate and args.transaction_type == "buying":
175 from erpnext.stock.doctype.item.item import get_last_purchase_details
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530176 out.update(get_last_purchase_details(item_doc.name,
Nabin Hait436f5262014-02-10 14:47:54 +0530177 args.docname, args.conversion_rate))
178
179def validate_price_list(args):
180 if args.get("price_list"):
Anand Doshie9baaa62014-02-26 12:35:33 +0530181 if not frappe.db.get_value("Price List",
Nabin Hait436f5262014-02-10 14:47:54 +0530182 {"name": args.price_list, args.transaction_type: 1, "enabled": 1}):
183 throw(_("Price List is either disabled or for not ") + _(args.transaction_type))
184 else:
185 throw(_("Price List not selected"))
186
187def validate_conversion_rate(args, meta):
188 from erpnext.setup.doctype.currency.currency import validate_conversion_rate
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530189 from frappe.model.meta import get_field_precision
Nabin Hait436f5262014-02-10 14:47:54 +0530190
191 # validate currency conversion rate
192 validate_conversion_rate(args.currency, args.conversion_rate,
193 meta.get_label("conversion_rate"), args.company)
194
195 args.conversion_rate = flt(args.conversion_rate,
196 get_field_precision(meta.get_field("conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530197 frappe._dict({"fields": args})))
Nabin Hait436f5262014-02-10 14:47:54 +0530198
199 # validate price list currency conversion rate
200 if not args.get("price_list_currency"):
201 throw(_("Price List Currency not selected"))
202 else:
203 validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate,
204 meta.get_label("plc_conversion_rate"), args.company)
205
206 args.plc_conversion_rate = flt(args.plc_conversion_rate,
207 get_field_precision(meta.get_field("plc_conversion_rate"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530208 frappe._dict({"fields": args})))
Nabin Hait436f5262014-02-10 14:47:54 +0530209
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530210def get_party_item_code(args, item_doc, out):
Nabin Hait436f5262014-02-10 14:47:54 +0530211 if args.transaction_type == "selling":
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530212 customer_item_code = item_doc.get("item_customer_details", {"customer_name": args.customer})
Nabin Hait436f5262014-02-10 14:47:54 +0530213 out.customer_item_code = customer_item_code[0].ref_code if customer_item_code else None
214 else:
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530215 item_supplier = item_doc.get("item_supplier_details", {"supplier": args.supplier})
Nabin Hait436f5262014-02-10 14:47:54 +0530216 out.supplier_part_no = item_supplier[0].supplier_part_no if item_supplier else None
217
218
219def get_pos_settings_item_details(company, args, pos_settings=None):
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530220 res = frappe._dict()
Nabin Hait436f5262014-02-10 14:47:54 +0530221
222 if not pos_settings:
223 pos_settings = get_pos_settings(company)
224
225 if pos_settings:
226 for fieldname in ("income_account", "cost_center", "warehouse", "expense_account"):
227 if not args.get(fieldname):
228 res[fieldname] = pos_settings.get(fieldname)
229
230 if res.get("warehouse"):
231 res.actual_qty = get_available_qty(args.item_code,
232 res.warehouse).get("actual_qty")
233
234 return res
235
236def get_pos_settings(company):
Anand Doshie9baaa62014-02-26 12:35:33 +0530237 pos_settings = frappe.db.sql("""select * from `tabPOS Setting` where user = %s
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530238 and company = %s""", (frappe.session['user'], company), as_dict=1)
Nabin Hait436f5262014-02-10 14:47:54 +0530239
240 if not pos_settings:
Anand Doshie9baaa62014-02-26 12:35:33 +0530241 pos_settings = frappe.db.sql("""select * from `tabPOS Setting`
Nabin Hait436f5262014-02-10 14:47:54 +0530242 where ifnull(user,'') = '' and company = %s""", company, as_dict=1)
243
244 return pos_settings and pos_settings[0] or None
Nabin Hait139dc7b2014-02-12 14:53:18 +0530245
Nabin Hait615d3422014-02-25 19:01:20 +0530246def apply_pricing_rule(out, args):
247 args_dict = frappe._dict().update(args)
248 args_dict.update(out)
Nabin Hait08222152014-02-28 11:30:47 +0530249 all_pricing_rules = get_pricing_rules(args_dict)
250
251 for rule_for in ["price", "discount_percentage"]:
252 pricing_rules = filter(lambda x: x[rule_for] > 0.0, all_pricing_rules)
253 pricing_rules = filter_pricing_rules(args_dict, pricing_rules, rule_for)
Nabin Hait615d3422014-02-25 19:01:20 +0530254 if pricing_rules:
Nabin Hait08222152014-02-28 11:30:47 +0530255 if rule_for == "discount_percentage":
256 out["discount_percentage"] = pricing_rules[-1]["discount_percentage"]
257 out["pricing_rule_for_discount"] = pricing_rules[-1]["name"]
Nabin Hait615d3422014-02-25 19:01:20 +0530258 else:
259 out["base_price_list_rate"] = pricing_rules[0]["price"]
260 out["price_list_rate"] = pricing_rules[0]["price"] * \
261 flt(args_dict.plc_conversion_rate) / flt(args_dict.conversion_rate)
Nabin Hait08222152014-02-28 11:30:47 +0530262 out["pricing_rule_for_price"] = pricing_rules[-1]["name"]
Nabin Hait615d3422014-02-25 19:01:20 +0530263
Nabin Haited5f4232014-02-28 12:52:06 +0530264def get_pricing_rules(args_dict):
Nabin Hait177b86a2014-02-28 15:47:22 +0530265 def _get_tree_conditions(doctype, allow_blank=True):
Nabin Haited5f4232014-02-28 12:52:06 +0530266 field = frappe.scrub(doctype)
267 condition = ""
268 if args_dict.get(field):
269 lft, rgt = frappe.db.get_value(doctype, args_dict[field], ["lft", "rgt"])
270 parent_groups = frappe.db.sql_list("""select name from `tab%s`
Nabin Hait177b86a2014-02-28 15:47:22 +0530271 where lft<=%s and rgt>=%s""" % (doctype, '%s', '%s'), (lft, rgt))
Nabin Haited5f4232014-02-28 12:52:06 +0530272
273 if parent_groups:
Nabin Hait177b86a2014-02-28 15:47:22 +0530274 if allow_blank: parent_groups.append('')
275 condition = " ifnull("+field+", '') in ('" + "', '".join(parent_groups)+"')"
Nabin Haited5f4232014-02-28 12:52:06 +0530276
277 return condition
278
279
Nabin Hait7e8e8ba2014-02-26 15:13:44 +0530280 conditions = ""
Nabin Hait33191702014-02-28 13:01:33 +0530281 for field in ["customer", "supplier", "supplier_type", "campaign", "sales_partner"]:
Nabin Hait615d3422014-02-25 19:01:20 +0530282 if args_dict.get(field):
283 conditions += " and ifnull("+field+", '') in (%("+field+")s, '')"
Nabin Hait08222152014-02-28 11:30:47 +0530284 else:
285 conditions += " and ifnull("+field+", '') = ''"
286
Nabin Hait33191702014-02-28 13:01:33 +0530287 for doctype in ["Customer Group", "Territory"]:
288 group_condition = _get_tree_conditions(doctype)
289 if group_condition:
290 conditions += " and " + group_condition
Nabin Haited5f4232014-02-28 12:52:06 +0530291
Nabin Hait08222152014-02-28 11:30:47 +0530292 conditions += " and ifnull(for_price_list, '') in (%(price_list)s, '')"
Nabin Haited5f4232014-02-28 12:52:06 +0530293
Nabin Hait08222152014-02-28 11:30:47 +0530294
Nabin Hait615d3422014-02-25 19:01:20 +0530295 if args_dict.get("transaction_date"):
296 conditions += """ and %(transaction_date)s between ifnull(valid_from, '2000-01-01')
297 and ifnull(valid_upto, '2500-12-31')"""
298
Nabin Hait08222152014-02-28 11:30:47 +0530299 return frappe.db.sql("""select * from `tabPricing Rule`
Nabin Haited5f4232014-02-28 12:52:06 +0530300 where (item_code=%(item_code)s or {item_group_condition} or brand=%(brand)s)
301 and docstatus < 2 and ifnull(disable, 0) = 0 {conditions}
302 order by priority desc, name desc""".format(
Nabin Hait177b86a2014-02-28 15:47:22 +0530303 item_group_condition=_get_tree_conditions("Item Group", False), conditions=conditions),
Nabin Haited5f4232014-02-28 12:52:06 +0530304 args_dict, as_dict=1)
Nabin Hait08222152014-02-28 11:30:47 +0530305
306def filter_pricing_rules(args_dict, pricing_rules, price_or_discount):
307 # filter for qty
308 if pricing_rules and args_dict.get("qty"):
309 pricing_rules = filter(lambda x: (args_dict.qty>=flt(x.min_qty)
310 and (args_dict.qty<=x.max_qty if x.max_qty else True)), pricing_rules)
311
312 # find pricing rule with highest priority
313 if pricing_rules:
314 max_priority = max([cint(p.priority) for p in pricing_rules])
315 if max_priority:
316 pricing_rules = filter(lambda x: cint(x.priority)==max_priority, pricing_rules)
317
318 # apply internal priority
319 all_fields = ["item_code", "item_group", "brand", "customer", "customer_group", "territory",
320 "supplier", "supplier_type", "campaign", "for_price_list", "sales_partner"]
Nabin Hait615d3422014-02-25 19:01:20 +0530321
Nabin Hait08222152014-02-28 11:30:47 +0530322 if len(pricing_rules) > 1:
323 for field_set in [["item_code", "item_group", "brand"],
324 ["customer", "customer_group", "territory"], ["supplier", "supplier_type"]]:
325 remaining_fields = list(set(all_fields) - set(field_set))
326 if if_all_rules_same(pricing_rules, remaining_fields):
327 pricing_rules = apply_internal_priority(pricing_rules, field_set, args_dict)
328 break
329
330 if len(pricing_rules) > 1:
331 pricing_rules = sorted(pricing_rules, key=lambda x: x[price_or_discount])
332
333 return pricing_rules
334
335def if_all_rules_same(pricing_rules, fields):
336 all_rules_same = True
337 val = [pricing_rules[0][k] for k in fields]
338 for p in pricing_rules[1:]:
339 if val != [p[k] for k in fields]:
340 all_rules_same = False
341 break
342
343 return all_rules_same
344
345def apply_internal_priority(pricing_rules, field_set, args_dict):
346 filtered_rules = []
347 for field in field_set:
348 if args_dict.get(field):
349 filtered_rules = filter(lambda x: x[field]==args_dict[field], pricing_rules)
350 if filtered_rules: break
351
352 return filtered_rules or pricing_rules
353
Rushabh Mehtaf14b8092014-04-03 14:30:42 +0530354def get_serial_nos_by_fifo(args, item_doc):
Anand Doshie9baaa62014-02-26 12:35:33 +0530355 return "\n".join(frappe.db.sql_list("""select name from `tabSerial No`
Nabin Hait139dc7b2014-02-12 14:53:18 +0530356 where item_code=%(item_code)s and warehouse=%(warehouse)s and status='Available'
357 order by timestamp(purchase_date, purchase_time) asc limit %(qty)s""", {
358 "item_code": args.item_code,
359 "warehouse": args.warehouse,
360 "qty": cint(args.qty)
361 }))
Nabin Hait08222152014-02-28 11:30:47 +0530362
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530363@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530364def get_conversion_factor(item_code, uom):
Anand Doshie9baaa62014-02-26 12:35:33 +0530365 return {"conversion_factor": frappe.db.get_value("UOM Conversion Detail",
Nabin Hait436f5262014-02-10 14:47:54 +0530366 {"parent": item_code, "uom": uom}, "conversion_factor")}
Nabin Hait08222152014-02-28 11:30:47 +0530367
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530368@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530369def get_projected_qty(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +0530370 return {"projected_qty": frappe.db.get_value("Bin",
Nabin Hait436f5262014-02-10 14:47:54 +0530371 {"item_code": item_code, "warehouse": warehouse}, "projected_qty")}
Nabin Hait08222152014-02-28 11:30:47 +0530372
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530373@frappe.whitelist()
Nabin Hait436f5262014-02-10 14:47:54 +0530374def get_available_qty(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +0530375 return frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse},
Nabin Hait436f5262014-02-10 14:47:54 +0530376 ["projected_qty", "actual_qty"], as_dict=True) or {}